import { createFileRoute, Link, useParams } from "@tanstack/react-router";
import { useState, useSyncExternalStore } from "react";
import { SendProposalDialog } from "@/components/send-proposal-dialog";
import {
  ArrowLeft,
  Pencil,
  Eye,
  FileDown,
  Send,
  Mail,
  Phone,
  Globe,
  User,
  Package,
  Wallet,
  Clock,
  CalendarClock,
  CheckCircle2,
  StickyNote,
  FileText,
} from "lucide-react";

import { Button } from "@/components/ui/button";
import { Card, CardContent } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Separator } from "@/components/ui/separator";
import { ProposalStatusBadge } from "@/components/proposal-status-badge";
import { proposalsStore } from "@/lib/store/proposals-store";
import { formatBRL, formatDate } from "@/lib/format";
import { cn } from "@/lib/utils";
import { generateProposalPdf } from "@/lib/pdf/proposal-pdf";
import { getEffectiveStatus, normalizeLegacyStatus } from "@/lib/proposal-status";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { toast } from "sonner";

export const Route = createFileRoute("/_admin/propostas/$id")({
  component: PropostaDetalhesPage,
});

const paymentLabel = {
  pix: "Pix",
  boleto: "Boleto bancário",
  cartao: "Cartão de crédito",
} as const;

function getPaymentMethods(detail: { paymentMethod: keyof typeof paymentLabel; paymentMethods?: (keyof typeof paymentLabel)[] }) {
  return detail.paymentMethods && detail.paymentMethods.length > 0
    ? detail.paymentMethods
    : [detail.paymentMethod];
}

function PropostaDetalhesPage() {
  const { id } = useParams({ from: "/_admin/propostas/$id" });
  const [sendOpen, setSendOpen] = useState(false);

  // Subscreve no store para reagir a mudanças (ex.: criação no wizard).
  const summaries = useSyncExternalStore(
    proposalsStore.subscribe,
    proposalsStore.getAll,
    proposalsStore.getAll,
  );
  const summary = summaries.find((p) => p.id === id);
  const detail = proposalsStore.getDetail(id);

  if (!summary || !detail) {
    return <NotFoundState />;
  }

  const oneTimeTotal = detail.items
    .filter((i) => !i.recurring)
    .reduce((s, i) => s + i.unitPrice * i.quantity, 0);
  const recurringTotal = detail.items
    .filter((i) => i.recurring === "mensal")
    .reduce((s, i) => s + i.unitPrice * i.quantity, 0);
  const installmentValue =
    detail.installments > 0 ? oneTimeTotal / detail.installments : oneTimeTotal;

  return (
    <div className="space-y-8">
      <Button
        asChild
        variant="ghost"
        size="sm"
        className="-ml-2 gap-1 text-muted-foreground"
      >
        <Link to="/propostas">
          <ArrowLeft className="h-4 w-4" /> Voltar para propostas
        </Link>
      </Button>

      {/* ---------------- Header ---------------- */}
      <section
        className="relative overflow-hidden rounded-2xl border border-border/60 bg-gradient-dark p-6 text-white shadow-glow sm:p-8"
      >
        <div className="absolute inset-0 opacity-30 [background:radial-gradient(circle_at_top_right,theme(colors.brand.cyan/40),transparent_60%)]" />
        <div className="relative flex flex-col gap-6 lg:flex-row lg:items-start lg:justify-between">
          <div className="space-y-3">
            <div className="flex flex-wrap items-center gap-2 text-xs uppercase tracking-wider text-white/70">
              <span className="font-mono">#{summary.number}</span>
              <span>·</span>
              <span>{summary.clientName}</span>
            </div>
            <h1 className="font-display text-2xl font-semibold leading-tight sm:text-3xl lg:text-4xl">
              {summary.title}
            </h1>
            <div className="flex flex-wrap items-center gap-3 pt-1">
              <ProposalStatusBadge status={getEffectiveStatus(summary)} />
              <span className="inline-flex items-center gap-1.5 rounded-full border border-white/20 bg-white/5 px-3 py-1 text-xs">
                <CalendarClock className="h-3.5 w-3.5" />
                Válida até {formatDate(summary.validUntil)}
              </span>
              <span className="inline-flex items-center gap-1.5 rounded-full border border-white/20 bg-white/5 px-3 py-1 text-xs">
                <Clock className="h-3.5 w-3.5" />
                Entrega em {detail.deadlineDays} dias
              </span>
            </div>
          </div>

          <div className="rounded-xl border border-white/15 bg-white/5 p-5 backdrop-blur">
            <div className="text-xs uppercase tracking-wider text-white/60">
              Valor total
            </div>
            <div className="mt-1 font-display text-3xl font-semibold">
              {formatBRL(oneTimeTotal)}
            </div>
            {recurringTotal > 0 && (
              <div className="mt-1 text-sm text-brand-mint">
                + {formatBRL(recurringTotal)}/mês recorrente
              </div>
            )}
          </div>
        </div>

        <div className="relative mt-6 flex flex-wrap gap-2 border-t border-white/10 pt-5">
          <Button
            asChild
            size="sm"
            className="bg-white text-foreground hover:bg-white/90"
          >
            <Link to="/propostas/$id/editar" params={{ id: summary.id }}>
              <Pencil className="h-4 w-4" /> Editar proposta
            </Link>

          </Button>
          <Button
            asChild
            size="sm"
            variant="outline"
            className="border-white/30 bg-white/0 text-white hover:bg-white/10"
          >
            <Link to="/p/$slug" params={{ slug: summary.slug }} target="_blank">
              <Eye className="h-4 w-4" /> Ver proposta pública
            </Link>
          </Button>
          <Button
            size="sm"
            variant="outline"
            onClick={() => generateProposalPdf(summary, detail)}
            className="border-white/30 bg-white/0 text-white hover:bg-white/10"
          >
            <FileDown className="h-4 w-4" /> Gerar PDF
          </Button>
          <Button
            size="sm"
            onClick={() => setSendOpen(true)}
            className="bg-gradient-brand text-white shadow-soft hover:opacity-95"
          >
            <Send className="h-4 w-4" /> Enviar proposta
          </Button>

          <div className="ml-auto flex items-center gap-2">
            <span className="text-xs uppercase tracking-wider text-white/60">
              Status
            </span>
            <Select
              value={normalizeLegacyStatus(summary.status)}
              onValueChange={(v) => {
                const next = v as "rascunho" | "enviada" | "aprovada";
                proposalsStore.setStatus(summary.id, next);
                toast.success("Status atualizado", {
                  description:
                    next === "aprovada"
                      ? "Proposta marcada como aprovada"
                      : next === "enviada"
                        ? "Proposta marcada como enviada"
                        : "Proposta voltou para rascunho",
                });
              }}
            >
              <SelectTrigger className="h-8 w-[150px] border-white/30 bg-white/10 text-white hover:bg-white/15">
                <SelectValue />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="rascunho">Rascunho</SelectItem>
                <SelectItem value="enviada">Enviada</SelectItem>
                <SelectItem value="aprovada">Aprovada</SelectItem>
              </SelectContent>
            </Select>
          </div>
        </div>
      </section>

      <SendProposalDialog
        open={sendOpen}
        onOpenChange={setSendOpen}
        proposal={summary}
      />


      {/* ---------------- Summary cards ---------------- */}
      <section className="grid gap-4 md:grid-cols-2 xl:grid-cols-3">
        <InfoCard icon={User} title="Cliente">
          <div className="font-medium">{summary.clientName}</div>
          <div className="text-sm text-muted-foreground">{detail.contactName}</div>
        </InfoCard>

        <InfoCard icon={Package} title="Serviços selecionados">
          <div className="font-display text-2xl font-semibold">
            {detail.items.length}
          </div>
          <div className="text-sm text-muted-foreground">
            {detail.items.length === 1 ? "item" : "itens"} no escopo
          </div>
        </InfoCard>

        <InfoCard icon={Wallet} title="Investimento">
          <div className="font-display text-2xl font-semibold">
            {formatBRL(oneTimeTotal)}
          </div>
          {recurringTotal > 0 && (
            <div className="text-sm text-muted-foreground">
              + {formatBRL(recurringTotal)}/mês
            </div>
          )}
        </InfoCard>

        <InfoCard icon={Wallet} title="Formas de pagamento">
          <ul className="space-y-1 text-sm">
            {getPaymentMethods(detail).map((m) => (
              <li key={m} className="font-medium">
                {paymentLabel[m]}
                {m === "cartao" && detail.installments > 1 && (
                  <span className="ml-1 font-normal text-muted-foreground">
                    em até {detail.installments}x de {formatBRL(installmentValue)}
                  </span>
                )}
              </li>
            ))}
          </ul>
        </InfoCard>

        <InfoCard icon={Clock} title="Prazo de entrega">
          <div className="font-display text-2xl font-semibold">
            {detail.deadlineDays} dias
          </div>
          <div className="text-sm text-muted-foreground">a partir da aprovação</div>
        </InfoCard>

        <InfoCard icon={CalendarClock} title="Validade da proposta">
          <div className="font-display text-2xl font-semibold">
            {formatDate(summary.validUntil)}
          </div>
          <div className="text-sm text-muted-foreground">
            Criada em {formatDate(summary.createdAt)}
          </div>
        </InfoCard>
      </section>

      {/* ---------------- Items table ---------------- */}
      <SectionCard icon={Package} title="Itens da proposta">
        <div className="overflow-hidden rounded-xl border border-border/60">
          <table className="w-full text-sm">
            <thead className="bg-muted/40 text-xs uppercase tracking-wider text-muted-foreground">
              <tr>
                <th className="px-4 py-3 text-left">Serviço</th>
                <th className="px-4 py-3 text-right">Qtd.</th>
                <th className="px-4 py-3 text-right">Valor unit.</th>
                <th className="px-4 py-3 text-right">Subtotal</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-border/60">
              {detail.items.map((it) => (
                <tr key={it.serviceId}>
                  <td className="px-4 py-3">
                    <div className="font-medium">{it.name}</div>
                    {it.recurring && (
                      <Badge
                        variant="outline"
                        className="mt-1 border-brand-cyan/30 bg-brand-cyan/10 text-foreground"
                      >
                        Recorrente · {it.recurring === "mensal" ? "mensal" : "anual"}
                      </Badge>
                    )}
                  </td>
                  <td className="px-4 py-3 text-right">{it.quantity}</td>
                  <td className="px-4 py-3 text-right">{formatBRL(it.unitPrice)}</td>
                  <td className="px-4 py-3 text-right font-medium">
                    {formatBRL(it.unitPrice * it.quantity)}
                  </td>
                </tr>
              ))}
            </tbody>
            <tfoot className="bg-muted/30 text-sm">
              <tr>
                <td colSpan={3} className="px-4 py-3 text-right text-muted-foreground">
                  Total único
                </td>
                <td className="px-4 py-3 text-right font-display font-semibold">
                  {formatBRL(oneTimeTotal)}
                </td>
              </tr>
              {recurringTotal > 0 && (
                <tr>
                  <td colSpan={3} className="px-4 py-3 text-right text-muted-foreground">
                    Total recorrente
                  </td>
                  <td className="px-4 py-3 text-right font-display font-semibold text-brand-cyan">
                    {formatBRL(recurringTotal)}/mês
                  </td>
                </tr>
              )}
            </tfoot>
          </table>
        </div>
      </SectionCard>

      {/* ---------------- Scope ---------------- */}
      <SectionCard icon={FileText} title="Escopo do projeto">
        <p className="whitespace-pre-line text-sm leading-relaxed text-muted-foreground">
          {detail.scope}
        </p>
      </SectionCard>

      {/* ---------------- Deliverables ---------------- */}
      <SectionCard icon={CheckCircle2} title="Entregas">
        <ul className="grid gap-2 sm:grid-cols-2">
          {detail.deliverables.map((d, i) => (
            <li
              key={`${d}-${i}`}
              className="flex items-start gap-2 rounded-lg border border-border/60 bg-card p-3 text-sm"
            >
              <CheckCircle2 className="mt-0.5 h-4 w-4 shrink-0 text-brand-mint" />
              <span>{d}</span>
            </li>
          ))}
        </ul>
      </SectionCard>

      {/* ---------------- Observations ---------------- */}
      {detail.observations && (
        <SectionCard icon={StickyNote} title="Observações">
          <p className="whitespace-pre-line text-sm leading-relaxed text-muted-foreground">
            {detail.observations}
          </p>
        </SectionCard>
      )}

      {/* ---------------- Client contact ---------------- */}
      <SectionCard icon={User} title="Contato do cliente">
        <div className="grid gap-3 sm:grid-cols-2">
          <ContactRow icon={User} label="Responsável" value={detail.contactName} />
          <ContactRow icon={Mail} label="E-mail" value={detail.email} />
          <ContactRow icon={Phone} label="WhatsApp" value={detail.whatsapp} />
          {detail.website && (
            <ContactRow icon={Globe} label="Site atual" value={detail.website} />
          )}
        </div>
      </SectionCard>
    </div>
  );
}

// ---------------- Subcomponents ----------------

function InfoCard({
  icon: Icon,
  title,
  children,
}: {
  icon: React.ComponentType<{ className?: string }>;
  title: string;
  children: React.ReactNode;
}) {
  return (
    <Card className="border-border/60 shadow-soft transition hover:-translate-y-0.5 hover:shadow-glow">
      <CardContent className="p-5">
        <div className="flex items-center justify-between">
          <span className="text-xs font-medium uppercase tracking-wider text-muted-foreground">
            {title}
          </span>
          <div className="flex h-9 w-9 items-center justify-center rounded-lg bg-gradient-brand text-white">
            <Icon className="h-4 w-4" />
          </div>
        </div>
        <div className="mt-3 space-y-1">{children}</div>
      </CardContent>
    </Card>
  );
}

function SectionCard({
  icon: Icon,
  title,
  children,
  className,
}: {
  icon: React.ComponentType<{ className?: string }>;
  title: string;
  children: React.ReactNode;
  className?: string;
}) {
  return (
    <Card className={cn("border-border/60 shadow-soft", className)}>
      <CardContent className="p-6">
        <div className="mb-4 flex items-center gap-2">
          <Icon className="h-4 w-4 text-primary" />
          <h2 className="font-display text-lg font-semibold">{title}</h2>
        </div>
        <Separator className="mb-4" />
        {children}
      </CardContent>
    </Card>
  );
}

function ContactRow({
  icon: Icon,
  label,
  value,
}: {
  icon: React.ComponentType<{ className?: string }>;
  label: string;
  value: string;
}) {
  return (
    <div className="flex items-start gap-3 rounded-lg border border-border/60 bg-card p-3">
      <div className="flex h-8 w-8 shrink-0 items-center justify-center rounded-md bg-primary/10 text-primary">
        <Icon className="h-4 w-4" />
      </div>
      <div className="min-w-0">
        <div className="text-xs uppercase tracking-wider text-muted-foreground">
          {label}
        </div>
        <div className="truncate text-sm font-medium">{value}</div>
      </div>
    </div>
  );
}

function NotFoundState() {
  return (
    <div className="mx-auto max-w-lg py-16 text-center">
      <div className="mx-auto mb-4 flex h-12 w-12 items-center justify-center rounded-full bg-muted">
        <FileText className="h-5 w-5 text-muted-foreground" />
      </div>
      <h1 className="font-display text-2xl font-semibold">Proposta não encontrada</h1>
      <p className="mt-2 text-sm text-muted-foreground">
        A proposta que você tentou abrir não existe ou foi removida.
      </p>
      <Button asChild className="mt-6 bg-gradient-brand text-white">
        <Link to="/propostas">
          <ArrowLeft className="h-4 w-4" /> Voltar para propostas
        </Link>
      </Button>
    </div>
  );
}
