"use client";

import { useState, useTransition } from "react";
import { Loader2 } from "lucide-react";
import type { OfferListCard } from "@/lib/offer-queries";

type Props = {
  leads: Array<{ id: string; name: string; company: string | null }>;
  clients: Array<{ id: string; name: string; brand_name: string }>;
  offers: OfferListCard[];
  action: (formData: FormData) => Promise<void>;
  preselectedLeadId?: string;
};

export function GeneraProposalForm({ leads, clients, offers, action, preselectedLeadId }: Props) {
  const [subjectType, setSubjectType] = useState<"lead" | "client">(
    preselectedLeadId ? "lead" : "lead"
  );
  const [model, setModel] = useState<"opus" | "sonnet">("opus");
  const [isPending, startTransition] = useTransition();
  const [error, setError] = useState<string | null>(null);

  async function handleSubmit(e: React.FormEvent<HTMLFormElement>) {
    e.preventDefault();
    setError(null);
    const form = e.currentTarget;
    const formData = new FormData(form);

    formData.append("model", model);

    startTransition(async () => {
      try {
        await action(formData);
      } catch (err) {
        setError(err instanceof Error ? err.message : "Errore sconosciuto");
      }
    });
  }

  return (
    <form onSubmit={handleSubmit} className="space-y-6 bg-white border border-border rounded-lg p-6">
      {/* Tipo soggetto */}
      <div className="space-y-2">
        <label className="text-sm font-medium text-foreground">Soggetto</label>
        <div className="flex gap-3">
          <button
            type="button"
            onClick={() => setSubjectType("lead")}
            className={`px-4 py-2 rounded-md text-sm border transition-colors ${
              subjectType === "lead"
                ? "bg-primary text-primary-foreground border-primary"
                : "border-border text-muted-foreground hover:border-primary/50"
            }`}
          >
            Lead
          </button>
          <button
            type="button"
            onClick={() => setSubjectType("client")}
            className={`px-4 py-2 rounded-md text-sm border transition-colors ${
              subjectType === "client"
                ? "bg-primary text-primary-foreground border-primary"
                : "border-border text-muted-foreground hover:border-primary/50"
            }`}
          >
            Cliente
          </button>
        </div>
      </div>

      {/* Modello AI */}
      <div className="space-y-2">
        <label className="text-sm font-medium text-foreground">Modello AI</label>
        <div className="flex gap-3">
          <button
            type="button"
            onClick={() => setModel("opus")}
            className={`px-4 py-2 rounded-md text-sm border transition-colors ${
              model === "opus"
                ? "bg-primary text-primary-foreground border-primary"
                : "border-border text-muted-foreground hover:border-primary/50"
            }`}
          >
            Opus
          </button>
          <button
            type="button"
            onClick={() => setModel("sonnet")}
            className={`px-4 py-2 rounded-md text-sm border transition-colors ${
              model === "sonnet"
                ? "bg-primary text-primary-foreground border-primary"
                : "border-border text-muted-foreground hover:border-primary/50"
            }`}
          >
            Sonnet
          </button>
        </div>
      </div>

      {/* Select lead o cliente */}
      {subjectType === "lead" ? (
        <div className="space-y-1">
          <label htmlFor="lead_id" className="text-sm font-medium text-foreground">
            Lead
          </label>
          <select
            id="lead_id"
            name="lead_id"
            required
            className="w-full border border-border rounded-md px-3 py-2 text-sm focus:outline-none focus:ring-1 focus:ring-primary"
          >
            <option value="">Seleziona un lead…</option>
            {leads.map((l) => (
              <option key={l.id} value={l.id} selected={l.id === preselectedLeadId}>
                {l.name}{l.company ? ` — ${l.company}` : ""}
              </option>
            ))}
          </select>
        </div>
      ) : (
        <div className="space-y-1">
          <label htmlFor="client_id" className="text-sm font-medium text-foreground">
            Cliente
          </label>
          <select
            id="client_id"
            name="client_id"
            required
            className="w-full border border-border rounded-md px-3 py-2 text-sm focus:outline-none focus:ring-1 focus:ring-primary"
          >
            <option value="">Seleziona un cliente…</option>
            {clients.map((c) => (
              <option key={c.id} value={c.id}>
                {c.brand_name} ({c.name})
              </option>
            ))}
          </select>
        </div>
      )}

      {/* Select offerta */}
      <div className="space-y-1">
        <label htmlFor="offer_macro_id" className="text-sm font-medium text-foreground">
          Offerta
        </label>
        <select
          id="offer_macro_id"
          name="offer_macro_id"
          required
          className="w-full border border-border rounded-md px-3 py-2 text-sm focus:outline-none focus:ring-1 focus:ring-primary"
        >
          <option value="">Seleziona un&apos;offerta…</option>
          {offers.map((o) => (
            <option key={o.id} value={o.id}>
              {o.internal_name}{o.description ? ` — ${o.description}` : ""}
            </option>
          ))}
        </select>
      </div>

      {/* Errore */}
      {error && (
        <p className="text-sm text-destructive bg-destructive/10 border border-destructive/20 rounded-md px-3 py-2">
          {error}
        </p>
      )}

      {/* Info generazione */}
      <div className="text-xs text-muted-foreground bg-muted rounded-md px-3 py-2">
        L&apos;AI (Claude {model === "opus" ? "Opus" : "Sonnet"}) legge i transcript del soggetto selezionato e genera una bozza
        personalizzata. La generazione richiede 30–60 secondi.
      </div>

      {/* Submit */}
      <button
        type="submit"
        disabled={isPending}
        className="w-full flex items-center justify-center gap-2 px-4 py-2.5 bg-primary text-primary-foreground rounded-md text-sm font-medium hover:bg-primary/90 disabled:opacity-60 transition-colors"
      >
        {isPending ? (
          <>
            <Loader2 size={16} className="animate-spin" />
            Generazione in corso…
          </>
        ) : (
          "Genera con AI →"
        )}
      </button>
    </form>
  );
}
