"use client";

import { useState, useTransition } from "react";
import { Loader2 } from "lucide-react";
import type { AssembledProposal } from "@/lib/proposal/assemble";

type Props = {
  slug: string;
  tiers: AssembledProposal["offer"]["tiers"];
  header: AssembledProposal["header"];
  onAccept: (slug: string, tier: string, email?: string, notes?: string) => Promise<void>;
  onReject: (slug: string, notes?: string) => Promise<void>;
};

export function AcceptSection({ slug, tiers, header, onAccept, onReject }: Props) {
  const [selectedTier, setSelectedTier] = useState<string | null>(null);
  const [email, setEmail] = useState("");
  const [notes, setNotes] = useState("");
  const [action, setAction] = useState<"accept" | "reject" | null>(null);
  const [isPending, startTransition] = useTransition();
  const [error, setError] = useState<string | null>(null);

  function handleAccept() {
    if (!selectedTier) { setError("Seleziona un tier per procedere"); return; }
    setError(null);
    startTransition(async () => {
      try {
        await onAccept(slug, selectedTier, email || undefined, notes || undefined);
      } catch (e) {
        setError(e instanceof Error ? e.message : "Errore");
      }
    });
  }

  function handleReject() {
    setError(null);
    startTransition(async () => {
      try {
        await onReject(slug, notes || undefined);
      } catch (e) {
        setError(e instanceof Error ? e.message : "Errore");
      }
    });
  }

  return (
    <div className="h-full flex flex-col justify-center px-16 py-24 space-y-10">
      <div>
        <p className="text-xs font-mono tracking-widest text-muted-foreground uppercase">
          Accettazione formale
        </p>
        <h2 className="text-5xl font-light text-foreground mt-4">
          Scegli il tuo <span className="text-primary">tier.</span>
        </h2>
        <p className="text-base text-muted-foreground mt-4">
          Seleziona l&apos;opzione che preferisci. La conferma via questo modulo attiva il lavoro.
        </p>
      </div>

      {/* Selezione tier */}
      <div className="grid grid-cols-3 gap-4">
        {tiers.map((tier) => (
          <button
            key={tier.tierLetter}
            onClick={() => setSelectedTier(tier.tierLetter)}
            className={`rounded-xl border-2 p-6 text-left transition-all ${
              selectedTier === tier.tierLetter
                ? "border-primary bg-primary/5"
                : "border-border hover:border-primary/40"
            }`}
          >
            <p className="text-2xl font-light text-primary">{tier.tierLetter}</p>
            <p className="font-medium text-foreground mt-1">{tier.publicName}</p>
            <p className="text-sm text-muted-foreground mt-2">
              {tier.publicPrice ? `€${parseFloat(tier.publicPrice).toLocaleString("it-IT")}` : `€${parseFloat(tier.servicesTotal).toLocaleString("it-IT")}`}
            </p>
          </button>
        ))}
      </div>

      {/* Email e note */}
      <div className="grid grid-cols-2 gap-4">
        <div className="space-y-1">
          <label className="text-xs font-mono text-muted-foreground uppercase tracking-widest">
            Email (opzionale)
          </label>
          <input
            type="email"
            value={email}
            onChange={(e) => setEmail(e.target.value)}
            placeholder="tua@email.com"
            className="w-full border border-border rounded-md px-3 py-2 text-sm focus:outline-none focus:ring-1 focus:ring-primary"
          />
        </div>
        <div className="space-y-1">
          <label className="text-xs font-mono text-muted-foreground uppercase tracking-widest">
            Note (opzionale)
          </label>
          <input
            type="text"
            value={notes}
            onChange={(e) => setNotes(e.target.value)}
            placeholder="Note per il consulente…"
            className="w-full border border-border rounded-md px-3 py-2 text-sm focus:outline-none focus:ring-1 focus:ring-primary"
          />
        </div>
      </div>

      {error && (
        <p className="text-sm text-destructive">{error}</p>
      )}

      {/* CTA */}
      <div className="flex items-center gap-4">
        <button
          onClick={handleAccept}
          disabled={isPending}
          className="flex-1 flex items-center justify-center gap-2 px-6 py-3 bg-primary text-primary-foreground rounded-xl font-medium hover:bg-primary/90 disabled:opacity-60 transition-colors"
        >
          {isPending && action === "accept" ? <Loader2 size={16} className="animate-spin" /> : null}
          Accetto — {selectedTier ? `Opzione ${selectedTier}` : "scegli tier"}
        </button>
        <button
          onClick={() => { setAction("reject"); handleReject(); }}
          disabled={isPending}
          className="px-6 py-3 border border-border rounded-xl text-muted-foreground hover:text-destructive hover:border-destructive/40 disabled:opacity-60 transition-colors text-sm"
        >
          Non procedo
        </button>
      </div>

      <p className="text-xs font-mono text-muted-foreground">
        {header.consultantName} · Accettazione formale valida {header.validityDays} giorni dalla data di invio.
      </p>
    </div>
  );
}
