"use client";

import { useState, useCallback, useTransition } from "react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { Card } from "@/components/ui/card";
import { QuotePreview } from "./QuotePreview";
import { OfferSelector } from "./OfferSelector";
import { PriceOverrideInput } from "./PriceOverrideInput";
import { createQuote, getOfferWithPhases } from "@/lib/quote-actions";
import { OfferMacro, OfferMicro } from "@/db/schema";
import { Check, Copy } from "lucide-react";

interface ClientOption {
  id: string;
  name: string;
}

interface QuoteBuilderFormProps {
  clients: ClientOption[];
  offerMacros: (OfferMacro & { micros: OfferMicro[] })[];
}

export function QuoteBuilderForm({ clients, offerMacros }: QuoteBuilderFormProps) {
  const [isPending, startTransition] = useTransition();
  const [selectedClient, setSelectedClient] = useState<string>("");
  const [selectedOffer, setSelectedOffer] = useState<string>("");
  const [selectedTotal, setSelectedTotal] = useState<string>("");
  const [currentOffer, setCurrentOffer] = useState<any>(null);
  const [successLink, setSuccessLink] = useState<string | null>(null);
  const [error, setError] = useState<string | null>(null);
  const [copied, setCopied] = useState(false);

  // Fetch offer details when selection changes
  const handleOfferChange = useCallback((offerId: string) => {
    setSelectedOffer(offerId);
    setError(null);
    startTransition(async () => {
      const offer = await getOfferWithPhases(offerId);
      setCurrentOffer(offer);
    });
  }, []);

  const handleSubmit = (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    setError(null);
    setSuccessLink(null);

    startTransition(async () => {
      const result = await createQuote({
        client_id: selectedClient,
        offer_micro_id: selectedOffer,
        accepted_total: selectedTotal,
      });

      if (result.success) {
        setSuccessLink(result.publicLink || "");
        // Reset form
        setSelectedClient("");
        setSelectedOffer("");
        setSelectedTotal("");
        setCurrentOffer(null);
      } else {
        setError(result.error || "Errore sconosciuto");
      }
    });
  };

  const handleCopyLink = async () => {
    if (successLink) {
      const fullUrl = `${window.location.origin}${successLink}`;
      await navigator.clipboard.writeText(fullUrl);
      setCopied(true);
      setTimeout(() => setCopied(false), 2000);
    }
  };

  if (successLink) {
    return (
      <Card className="p-6 space-y-4">
        <div className="text-center space-y-3">
          <div className="inline-flex items-center justify-center w-12 h-12 bg-green-100 rounded-full">
            <Check size={24} className="text-green-600" />
          </div>
          <h3 className="text-lg font-semibold text-gray-900">Preventivo creato</h3>
          <p className="text-sm text-gray-600">
            Il preventivo è stato salvato e il link è pronto per essere condiviso
          </p>
        </div>

        <div className="bg-gray-50 rounded-lg p-4">
          <p className="text-xs text-gray-500 mb-2">Link pubblico</p>
          <div className="flex gap-2">
            <code className="flex-1 bg-white border border-gray-200 rounded px-3 py-2 text-xs text-gray-900 font-mono">
              {window.location.origin}
              {successLink}
            </code>
            <Button
              type="button"
              size="sm"
              variant={copied ? "default" : "outline"}
              onClick={handleCopyLink}
              className="flex items-center gap-2"
            >
              {copied ? (
                <>
                  <Check size={16} /> Copiato
                </>
              ) : (
                <>
                  <Copy size={16} /> Copia
                </>
              )}
            </Button>
          </div>
        </div>

        <Button
          type="button"
          variant="ghost"
          className="w-full"
          onClick={() => {
            setSuccessLink(null);
            setSelectedClient("");
            setSelectedOffer("");
            setSelectedTotal("");
            setCurrentOffer(null);
          }}
        >
          Crea un altro preventivo
        </Button>
      </Card>
    );
  }

  return (
    <div className="grid grid-cols-2 gap-6">
      {/* LEFT COLUMN: FORM */}
      <div>
        <form onSubmit={handleSubmit} className="space-y-4">
          <h2 className="text-lg font-semibold text-gray-900">Crea Preventivo</h2>

          {/* Client Select */}
          <div className="space-y-2">
            <Label htmlFor="client">Cliente*</Label>
            <Select value={selectedClient} onValueChange={setSelectedClient}>
              <SelectTrigger id="client">
                <SelectValue placeholder="Seleziona un cliente" />
              </SelectTrigger>
              <SelectContent>
                {clients.map((client) => (
                  <SelectItem key={client.id} value={client.id}>
                    {client.name}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>

          {/* Offer Select */}
          {selectedClient && (
            <OfferSelector
              macros={offerMacros}
              value={selectedOffer}
              onValueChange={handleOfferChange}
            />
          )}

          {/* Price Input */}
          {selectedOffer && (
            <PriceOverrideInput
              value={selectedTotal}
              onChange={setSelectedTotal}
              calculatedTotal={currentOffer?.duration_months ? currentOffer.duration_months * 1000 : undefined}
            />
          )}

          {/* Error Message */}
          {error && (
            <div className="p-3 bg-red-50 border border-red-200 rounded-lg">
              <p className="text-sm text-red-800">{error}</p>
            </div>
          )}

          {/* Submit Button */}
          <Button
            type="submit"
            disabled={!selectedClient || !selectedOffer || !selectedTotal || isPending}
            className="w-full bg-[#1A463C] text-white hover:bg-[#1A463C]/90"
          >
            {isPending ? "Salvataggio…" : "Salva Preventivo"}
          </Button>
        </form>
      </div>

      {/* RIGHT COLUMN: PREVIEW */}
      <div>
        <QuotePreview offer={currentOffer} selectedTotal={parseFloat(selectedTotal) || 0} />
      </div>
    </div>
  );
}
