import { notFound } from "next/navigation";
import Link from "next/link";
import { getProposalById } from "@/lib/proposal/queries";
import { publishProposal, deleteProposal } from "../actions";
import { ExternalLink, ArrowLeft, Trash2 } from "lucide-react";

export const revalidate = 0;

export default async function ProposalDetailPage({
  params,
}: {
  params: Promise<{ id: string }>;
}) {
  const { id } = await params;
  const proposal = await getProposalById(id);
  if (!proposal) notFound();

  const { content } = proposal;
  const isDraft = proposal.state === "draft";

  return (
    <div className="max-w-4xl mx-auto space-y-6">
      {/* Breadcrumb */}
      <Link
        href="/admin/preventivi"
        className="inline-flex items-center gap-1.5 text-sm text-muted-foreground hover:text-foreground transition-colors"
      >
        <ArrowLeft size={14} /> Preventivi
      </Link>

      {/* Header */}
      <div className="flex items-start justify-between gap-4">
        <div>
          <h1 className="text-2xl font-semibold text-foreground">
            {proposal.title ?? "Senza titolo"}
          </h1>
          <div className="flex items-center gap-3 mt-2">
            <StateBadge state={proposal.state} />
            <span className="text-sm text-muted-foreground">
              Generato il {proposal.createdAt.toLocaleDateString("it-IT")} · {proposal.model ?? "AI"}
            </span>
          </div>
        </div>

        <div className="flex items-center gap-2 shrink-0">
          {/* Link pubblico */}
          {(proposal.state === "published" || proposal.state === "accepted") && (
            <a
              href={`/preventivo/${proposal.slug}`}
              target="_blank"
              rel="noopener noreferrer"
              className="flex items-center gap-1.5 px-3 py-2 border border-border rounded-md text-sm hover:bg-muted transition-colors"
            >
              <ExternalLink size={14} />
              Apri deck
            </a>
          )}

          {/* Pubblica */}
          {isDraft && (
            <form action={publishProposal.bind(null, id)}>
              <button
                type="submit"
                className="px-4 py-2 bg-primary text-primary-foreground rounded-md text-sm font-medium hover:bg-primary/90 transition-colors"
              >
                Pubblica →
              </button>
            </form>
          )}

          {/* Elimina (solo draft) */}
          {isDraft && (
            <form action={deleteProposal.bind(null, id)}>
              <button
                type="submit"
                className="p-2 text-muted-foreground hover:text-destructive hover:bg-destructive/10 rounded-md transition-colors"
                title="Elimina bozza"
              >
                <Trash2 size={16} />
              </button>
            </form>
          )}
        </div>
      </div>

      {/* Link pubblico (draft) */}
      {isDraft && (
        <div className="text-xs text-muted-foreground bg-yellow-50 border border-yellow-200 rounded-md px-3 py-2">
          Bozza — non ancora visibile al cliente. Pubblica per generare il link pubblico.
        </div>
      )}
      {!isDraft && (
        <div className="text-xs bg-muted border border-border rounded-md px-3 py-2 font-mono">
          {typeof window === "undefined" ? "" : window.location.origin}/preventivo/{proposal.slug}
        </div>
      )}

      {/* Preview contenuto */}
      <div className="space-y-4">
        <h2 className="text-base font-semibold text-foreground">Anteprima contenuto</h2>

        <Section title="Vision">
          <p className="font-medium">{content.ai.vision.headline}</p>
          <p className="text-muted-foreground text-sm mt-1">{content.ai.vision.body}</p>
        </Section>

        <Section title={`Problemi (${content.ai.problems.length})`}>
          <div className="space-y-2">
            {content.ai.problems.map((p) => (
              <div key={p.id} className="border border-border rounded-md px-3 py-2">
                <p className="font-medium text-sm">{p.id}. {p.title}</p>
                <p className="text-xs text-muted-foreground mt-0.5">{p.subtitle}</p>
              </div>
            ))}
          </div>
        </Section>

        <Section title="Scope">
          <p className="font-medium text-sm">{content.ai.scope.scopeTitle}</p>
          <p className="text-sm text-muted-foreground mt-1">{content.ai.scope.scopeBody}</p>
        </Section>

        <Section title={`Tier offerta (${content.offer.tiers.length})`}>
          <div className="grid grid-cols-3 gap-3">
            {content.offer.tiers.map((t) => (
              <div key={t.id} className="border border-border rounded-md p-3 text-sm">
                <p className="font-semibold text-primary">{t.tierLetter}</p>
                <p className="font-medium mt-0.5">{t.publicName}</p>
                <p className="text-muted-foreground mt-1">
                  {t.publicPrice ? `€${t.publicPrice}` : `€${t.servicesTotal} (calcolato)`}
                </p>
              </div>
            ))}
          </div>
        </Section>
      </div>
    </div>
  );
}

function StateBadge({ state }: { state: string }) {
  const map: Record<string, { label: string; className: string }> = {
    draft:     { label: "Bozza",      className: "bg-yellow-100 text-yellow-800" },
    published: { label: "Pubblicato", className: "bg-blue-100 text-blue-800" },
    accepted:  { label: "Accettato",  className: "bg-green-100 text-green-800" },
    rejected:  { label: "Rifiutato",  className: "bg-red-100 text-red-800" },
  };
  const info = map[state] ?? { label: state, className: "bg-gray-100 text-gray-700" };
  return (
    <span className={`inline-flex items-center px-2 py-0.5 rounded text-xs font-medium ${info.className}`}>
      {info.label}
    </span>
  );
}

function Section({ title, children }: { title: string; children: React.ReactNode }) {
  return (
    <div className="border border-border rounded-lg p-4 space-y-2">
      <h3 className="text-sm font-semibold text-muted-foreground uppercase tracking-wide">{title}</h3>
      {children}
    </div>
  );
}
