import { useEffect, useRef } from "react";
import type { SyntheticSample } from "../samples.ts";
import type { UploadRecord } from "../imageStore.ts";

function SyntheticThumb({ sample }: { sample: SyntheticSample }) {
  const ref = useRef<HTMLCanvasElement>(null);
  useEffect(() => {
    const canvas = ref.current;
    if (!canvas) return;
    const raw = sample.generate();
    const tmp = document.createElement("canvas");
    tmp.width = raw.width;
    tmp.height = raw.height;
    tmp
      .getContext("2d")!
      .putImageData(
        new ImageData(new Uint8ClampedArray(raw.rgba), raw.width, raw.height),
        0,
        0
      );
    const ctx = canvas.getContext("2d")!;
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    ctx.drawImage(tmp, 0, 0, canvas.width, canvas.height);
  }, [sample]);
  return <canvas ref={ref} width={72} height={72} className="thumb-canvas" />;
}

interface Props {
  samples: SyntheticSample[];
  uploads: UploadRecord[];
  selectedId: string | null;
  onSelectSample: (sample: SyntheticSample) => void;
  onSelectUpload: (rec: UploadRecord) => void;
  onUpload: (file: File) => void;
  onDeleteUpload: (id: string) => void;
  disabled?: boolean;
}

export function SamplePicker({
  samples,
  uploads,
  selectedId,
  onSelectSample,
  onSelectUpload,
  onUpload,
  onDeleteUpload,
  disabled,
}: Props) {
  const fileRef = useRef<HTMLInputElement>(null);

  return (
    <div className="picker">
      <div className="picker-row">
        {samples.map((sample) => (
          <button
            key={sample.id}
            className={
              "sample" + (sample.id === selectedId ? " sample-selected" : "")
            }
            onClick={() => onSelectSample(sample)}
            disabled={disabled}
            title="Generated"
          >
            <SyntheticThumb sample={sample} />
            <span className="sample-name">{sample.name}</span>
          </button>
        ))}

        {uploads.length > 0 && <div className="picker-divider" aria-hidden />}

        {uploads.map((rec) => (
          <div className="sample-wrap" key={rec.id}>
            <button
              className={
                "sample" + (rec.id === selectedId ? " sample-selected" : "")
              }
              onClick={() => onSelectUpload(rec)}
              disabled={disabled}
              title={`${rec.name} · ${rec.width}×${rec.height}`}
            >
              <img className="thumb-canvas" src={rec.thumb} alt={rec.name} />
              <span className="sample-name">{rec.name}</span>
            </button>
            <button
              className="sample-delete"
              title="Delete"
              aria-label={`Delete ${rec.name}`}
              onClick={(e) => {
                e.stopPropagation();
                onDeleteUpload(rec.id);
              }}
              disabled={disabled}
            >
              ×
            </button>
          </div>
        ))}

        <button
          className="sample sample-upload"
          onClick={() => fileRef.current?.click()}
          disabled={disabled}
          title="Upload an image (stored locally in your browser)"
        >
          <span className="upload-plus">+</span>
          <span className="sample-name">Upload</span>
        </button>
        <input
          ref={fileRef}
          type="file"
          accept="image/*"
          style={{ display: "none" }}
          onChange={(e) => {
            const f = e.target.files?.[0];
            if (f) onUpload(f);
            e.target.value = "";
          }}
        />
      </div>
    </div>
  );
}
