import { useQuery } from "@tanstack/react-query";
import { Label } from "@/components/ui/label";
import { Badge } from "@/components/ui/badge";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { X } from "lucide-react";

interface InstructorSelectProps {
  selectedIds: string[];
  onChange: (ids: string[]) => void;
}

const InstructorSelect = ({ selectedIds, onChange }: InstructorSelectProps) => {
  const { data: trainers } = useQuery({
    queryKey: ["trainers-list"],
    queryFn: async () => {
      const res = await fetch("/api/admin/trainers?fields=id,first_name,last_name");
      if (!res.ok) return [];
      return res.json();
    },
  });

  const available = trainers?.filter((t: any) => !selectedIds.includes(t.id)) || [];
  const selected = trainers?.filter((t: any) => selectedIds.includes(t.id)) || [];

  return (
    <div className="space-y-2">
      <Label className="font-semibold">Instructors</Label>
      <div className="flex flex-wrap gap-2 min-h-[40px] border border-input rounded-md p-2 bg-background">
        {selected.map((t: any) => (
          <Badge key={t.id} variant="secondary" className="gap-1">
            {t.first_name} {t.last_name}
            <button type="button" onClick={() => onChange(selectedIds.filter((id) => id !== t.id))}>
              <X className="h-3 w-3" />
            </button>
          </Badge>
        ))}
        {available.length > 0 && (
          <Select onValueChange={(id) => onChange([...selectedIds, id])}>
            <SelectTrigger className="w-[180px] h-7 border-0 shadow-none p-0 text-muted-foreground text-sm">
              <SelectValue placeholder="Add instructor..." />
            </SelectTrigger>
            <SelectContent>
              {available.map((t: any) => (
                <SelectItem key={t.id} value={t.id}>
                  {t.first_name} {t.last_name}
                </SelectItem>
              ))}
            </SelectContent>
          </Select>
        )}
      </div>
      <p className="text-xs text-muted-foreground">You can select multiple instructors</p>
    </div>
  );
};

export default InstructorSelect;
