import { notFound } from "next/navigation";
import { getQuoteByToken } from "@/lib/quote-service";
import { QuoteMultistep } from "@/components/public/quote/QuoteMultistep";
import { Card } from "@/components/ui/card";

export const revalidate = 0; // Always fetch fresh data (no caching)

interface QuotePageProps {
  params: Promise<{ token: string }>;
}

export default async function QuotePage({ params }: QuotePageProps) {
  const { token } = await params;

  // Validate token format (nanoid: 21 chars, alphanumeric + underscore/dash)
  if (!token || typeof token !== "string" || !/^[a-zA-Z0-9_-]{21}$/.test(token)) {
    notFound();
  }

  // Fetch quote data
  const quote = await getQuoteByToken(token);
  if (!quote) {
    notFound();
  }

  // If already accepted, show read-only message
  if (quote.state === "accepted" && quote.accepted_at) {
    return (
      <div className="space-y-6 p-8">
        <div className="bg-green-50 border border-green-200 rounded-lg p-6">
          <h2 className="text-lg font-semibold text-green-900 mb-2">
            ✓ Preventivo già accettato
          </h2>
          <p className="text-green-800">
            Questo preventivo è stato accettato il{" "}
            <span className="font-medium">
              {new Date(quote.accepted_at).toLocaleDateString("it-IT", {
                year: "numeric",
                month: "long",
                day: "numeric",
              })}
            </span>
          </p>
        </div>
        <div className="border-t border-slate-200 pt-6">
          <h3 className="font-semibold text-slate-900 mb-3">Dettagli preventivo</h3>
          <Card className="p-4 space-y-2">
            <div className="flex justify-between text-sm">
              <span className="text-slate-600">Offerta:</span>
              <span className="font-medium">{quote.offerName}</span>
            </div>
            <div className="flex justify-between text-sm">
              <span className="text-slate-600">Totale:</span>
              <span className="font-medium">
                {parseFloat(quote.accepted_total).toLocaleString("it-IT", {
                  style: "currency",
                  currency: "EUR",
                })}
              </span>
            </div>
          </Card>
        </div>
      </div>
    );
  }

  // If rejected, show message
  if (quote.state === "rejected") {
    return (
      <div className="space-y-6 p-8">
        <div className="bg-amber-50 border border-amber-200 rounded-lg p-6">
          <h2 className="text-lg font-semibold text-amber-900 mb-2">
            Preventivo rifiutato
          </h2>
          <p className="text-amber-800">
            Hai rifiutato questo preventivo. Se desideri discutere una proposta diversa,
            contattaci direttamente.
          </p>
        </div>
      </div>
    );
  }

  // Active quote — show multistep form
  return (
    <QuoteMultistep quote={quote} />
  );
}
