"use client";

import { useState, useTransition } from "react";
import { toast } from "sonner";
import { Button } from "@/components/ui/button";
import { Label } from "@/components/ui/label";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { addToShortlist } from "./actions";

export interface ApplyLead {
  id: string;
  full_name: string;
  phone: string | null;
}

export function ApplyClient({
  courseId,
  leads,
}: {
  courseId: string;
  leads: ApplyLead[];
}) {
  const [leadId, setLeadId] = useState<string>("");
  const [isPending, startTransition] = useTransition();

  function handleAdd() {
    if (!leadId) {
      toast.error("Please select a lead first.");
      return;
    }
    startTransition(async () => {
      const res = await addToShortlist(courseId, leadId);
      if (res.ok) {
        toast.success("Course added to the lead's shortlist.");
        setLeadId("");
      } else {
        toast.error(res.error ?? "Could not shortlist this course.");
      }
    });
  }

  return (
    <div className="flex flex-col gap-3 sm:flex-row sm:items-end">
      <div className="flex-1 space-y-2">
        <Label htmlFor="lead">Select lead</Label>
        <Select value={leadId} onValueChange={setLeadId} disabled={isPending}>
          <SelectTrigger id="lead" className="w-full">
            <SelectValue placeholder="Choose a lead…" />
          </SelectTrigger>
          <SelectContent>
            {leads.length === 0 ? (
              <SelectItem value="__none" disabled>
                No leads available
              </SelectItem>
            ) : (
              leads.map((lead) => (
                <SelectItem key={lead.id} value={lead.id}>
                  {lead.full_name}
                  {lead.phone ? ` · ${lead.phone}` : ""}
                </SelectItem>
              ))
            )}
          </SelectContent>
        </Select>
      </div>
      <Button onClick={handleAdd} disabled={isPending || !leadId}>
        {isPending ? "Adding…" : "Add to shortlist"}
      </Button>
    </div>
  );
}
