"use client";

import { useState } from "react";
import type { PublicQuoteView } from "@/lib/quote-service";
import { Button } from "@/components/ui/button";
import { Card } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import { ArrowLeft, CheckCircle, X } from "lucide-react";
import { acceptQuote, rejectQuote } from "@/app/quote/[token]/actions";

interface QuoteStep3SummaryProps {
  quote: PublicQuoteView;
  onPrev: () => void;
}

export function QuoteStep3Summary({ quote, onPrev }: QuoteStep3SummaryProps) {
  const [email, setEmail] = useState("");
  const [notes, setNotes] = useState("");
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [successMessage, setSuccessMessage] = useState<string | null>(null);
  const [errorMessage, setErrorMessage] = useState<string | null>(null);

  // Format total as currency
  const totalInCents = Math.round(parseFloat(quote.accepted_total) * 100);
  const totalFormatted = (totalInCents / 100).toLocaleString("it-IT", {
    style: "currency",
    currency: "EUR",
  });

  const handleAccept = async () => {
    setIsSubmitting(true);
    setErrorMessage(null);
    try {
      const result = await acceptQuote(quote.token, email || undefined, notes || undefined);
      if (result.success) {
        setSuccessMessage(result.message || "Preventivo accettato con successo!");
      } else {
        setErrorMessage(result.error || "Errore sconosciuto");
      }
    } catch (error) {
      setErrorMessage("Errore durante l'invio");
      console.error(error);
    } finally {
      setIsSubmitting(false);
    }
  };

  const handleReject = async () => {
    if (!window.confirm("Sei sicuro di rifiutare questo preventivo?")) return;

    setIsSubmitting(true);
    setErrorMessage(null);
    try {
      const result = await rejectQuote(quote.token, notes || undefined);
      if (result.success) {
        setSuccessMessage("Preventivo rifiutato");
      } else {
        setErrorMessage(result.error || "Errore sconosciuto");
      }
    } catch (error) {
      setErrorMessage("Errore durante l'invio");
      console.error(error);
    } finally {
      setIsSubmitting(false);
    }
  };

  // Success state
  if (successMessage) {
    return (
      <div className="space-y-8 p-8">
        <div className="flex justify-center">
          <div className="rounded-full bg-green-100 p-3">
            <CheckCircle className="h-12 w-12 text-green-600" />
          </div>
        </div>
        <div className="text-center space-y-2">
          <h2 className="text-2xl font-bold text-slate-900">Perfetto!</h2>
          <p className="text-slate-600">{successMessage}</p>
        </div>
        <div className="bg-green-50 border border-green-200 rounded-lg p-4 space-y-2">
          <p className="text-sm font-medium text-slate-900">Cosa succede ora?</p>
          <ul className="text-sm text-slate-600 space-y-1 ml-4">
            <li>✓ Abbiamo registrato l'accettazione del preventivo</li>
            <li>✓ Ti contatteremo entro 24 ore per concordare i prossimi passi</li>
            <li>✓ Inizieremo la pianificazione del tuo progetto di personal branding</li>
          </ul>
        </div>
      </div>
    );
  }

  return (
    <div className="space-y-8 p-8">
      {/* Summary Card */}
      <Card className="p-6 border-l-4 border-l-blue-500 bg-blue-50">
        <h2 className="text-lg font-semibold text-slate-900 mb-4">Riepilogo</h2>
        <div className="space-y-2 text-sm">
          <div className="flex justify-between">
            <span className="text-slate-600">Offerta:</span>
            <span className="font-medium text-slate-900">{quote.offerName}</span>
          </div>
          <div className="flex justify-between">
            <span className="text-slate-600">Investimento totale:</span>
            <span className="font-bold text-blue-600">{totalFormatted}</span>
          </div>
          <div className="flex justify-between">
            <span className="text-slate-600">Fasi incluse:</span>
            <span className="font-medium text-slate-900">{quote.phaseSummary.length}</span>
          </div>
        </div>
      </Card>

      {/* Form Fields */}
      <div className="space-y-4">
        <div>
          <Label htmlFor="email" className="block mb-2 font-medium text-slate-700">
            Email (facoltativo)
          </Label>
          <Input
            id="email"
            type="email"
            placeholder="il-tuo@email.com"
            value={email}
            onChange={(e) => setEmail(e.target.value)}
            disabled={isSubmitting}
            className="h-10"
          />
          <p className="text-xs text-slate-500 mt-1">
            Useremo questa email per contattarti riguardo al tuo preventivo
          </p>
        </div>

        <div>
          <Label htmlFor="notes" className="block mb-2 font-medium text-slate-700">
            Note (facoltativo, max 500 caratteri)
          </Label>
          <Textarea
            id="notes"
            placeholder="Es. Preferisco iniziare nel mese di settembre..."
            value={notes}
            onChange={(e) => setNotes(e.target.value.slice(0, 500))}
            disabled={isSubmitting}
            rows={4}
            className="resize-none"
          />
          <p className="text-xs text-slate-500 mt-1">
            {notes.length}/500 caratteri
          </p>
        </div>
      </div>

      {/* Error message */}
      {errorMessage && (
        <div className="bg-red-50 border border-red-200 rounded-lg p-4 flex gap-3">
          <X className="h-5 w-5 text-red-600 flex-shrink-0 mt-0.5" />
          <p className="text-sm text-red-800">{errorMessage}</p>
        </div>
      )}

      {/* CTA Buttons */}
      <div className="space-y-3 pt-4">
        <Button
          onClick={handleAccept}
          disabled={isSubmitting}
          size="lg"
          className="w-full bg-green-600 hover:bg-green-700 text-white h-12"
        >
          {isSubmitting ? "Invio in corso..." : "Accetta Preventivo"}
        </Button>

        <div className="flex gap-2">
          <Button
            onClick={onPrev}
            variant="outline"
            disabled={isSubmitting}
            className="flex-1 h-10"
          >
            <ArrowLeft className="h-4 w-4 mr-2" />
            Indietro
          </Button>
          <Button
            onClick={handleReject}
            disabled={isSubmitting}
            variant="ghost"
            className="flex-1 h-10 text-red-600 hover:text-red-700 hover:bg-red-50"
          >
            Rifiuta
          </Button>
        </div>
      </div>

      {/* Info text */}
      <p className="text-xs text-slate-500 text-center">
        Passo 3 di 3 • Conferma e accettazione
      </p>
    </div>
  );
}
