import { useState } from "react";
import { Plus } from "lucide-react";
import { trpc } from "@/lib/trpc";
import { RegisterProjectDialog } from "./RegisterProjectDialog";

interface ProjectPickerProps {
  value: string[];
  onChange: (ids: string[]) => void;
  error?: string;
}

export function ProjectPicker({ value, onChange, error }: ProjectPickerProps) {
  const [registerOpen, setRegisterOpen] = useState(false);

  const projectsQuery = trpc.listProjects.useQuery();
  const projects = projectsQuery.data ?? [];

  function toggle(id: string) {
    if (value.includes(id)) {
      onChange(value.filter((v) => v !== id));
    } else {
      onChange([...value, id]);
    }
  }

  return (
    <div className="space-y-2">
      {projects.length === 0 && !projectsQuery.isLoading && (
        <p className="text-sm text-muted-foreground">No projects registered yet.</p>
      )}
      {projects.length > 0 && (
        <div className="max-h-40 overflow-y-auto rounded border border-border p-2 space-y-1">
          {projects.map((p) => (
            <label
              key={p.id}
              className="flex items-center gap-2 rounded px-2 py-1.5 text-sm hover:bg-accent cursor-pointer"
            >
              <input
                type="checkbox"
                checked={value.includes(p.id)}
                onChange={() => toggle(p.id)}
                className="rounded border-border"
              />
              <span className="font-medium">{p.name}</span>
              <span className="text-muted-foreground text-xs truncate">{p.url}</span>
            </label>
          ))}
        </div>
      )}
      <button
        type="button"
        onClick={() => setRegisterOpen(true)}
        className="inline-flex items-center gap-1 text-sm text-primary hover:underline"
      >
        <Plus className="h-3 w-3" />
        Register new project
      </button>
      {error && <p className="text-sm text-destructive">{error}</p>}
      <RegisterProjectDialog
        open={registerOpen}
        onOpenChange={setRegisterOpen}
      />
    </div>
  );
}
