import { createFileRoute, Link, useNavigate, useParams } from "@tanstack/react-router";
import { useMemo } from "react";
import { toast } from "sonner";
import { ArrowLeft, FileQuestion } from "lucide-react";

import { Button } from "@/components/ui/button";
import { Card, CardContent } from "@/components/ui/card";
import {
  ProposalWizard,
  type ProposalDraft,
  type ProposalWizardTotals,
} from "@/components/proposal-wizard";
import { proposalsStore, useProposals } from "@/lib/store/proposals-store";
import { slugify } from "@/lib/format";
import type { ProposalDetail, ProposalSummary } from "@/lib/mock/types";

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

function EditarPropostaPage() {
  const { id } = useParams({ from: "/_admin/propostas/$id/editar" });
  const navigate = useNavigate();
  // Subscribe so we reactively pick up store updates if any.
  useProposals();

  const summary = proposalsStore.getById(id);
  const detail = proposalsStore.getDetail(id);

  const initial = useMemo<ProposalDraft | null>(() => {
    if (!summary || !detail) return null;
    return {
      clientName: summary.clientName,
      contactName: detail.contactName,
      email: detail.email,
      whatsapp: detail.whatsapp,
      website: detail.website ?? "",
      title: summary.title,
      items: detail.items,
      scope: detail.scope,
      deliverables: detail.deliverables.length > 0 ? detail.deliverables : [""],
      observations: detail.observations ?? "",
      deadlineDays: detail.deadlineDays,
      validUntil: summary.validUntil,
      paymentMethods: detail.paymentMethods ?? [detail.paymentMethod],
      installments: detail.installments,
      status: summary.status,
    };
  }, [summary, detail]);

  if (!summary || !detail || !initial) {
    return (
      <div className="mx-auto max-w-2xl space-y-6">
        <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>
        <Card className="border-border/60 shadow-soft">
          <CardContent className="space-y-4 p-8 text-center">
            <div className="mx-auto flex h-12 w-12 items-center justify-center rounded-full bg-muted text-muted-foreground">
              <FileQuestion className="h-5 w-5" />
            </div>
            <h1 className="font-display text-2xl font-semibold">Proposta não encontrada</h1>
            <p className="text-sm text-muted-foreground">
              Não localizamos a proposta <span className="font-mono">{id}</span>. Ela pode
              ter sido removida.
            </p>
            <Button asChild className="bg-gradient-brand text-white">
              <Link to="/propostas">Voltar à listagem</Link>
            </Button>
          </CardContent>
        </Card>
      </div>
    );
  }

  const handleSubmit = (draft: ProposalDraft, totals: ProposalWizardTotals) => {
    const summaryPatch: Partial<ProposalSummary> = {
      clientName: draft.clientName,
      title: draft.title,
      total: totals.oneTime,
      recurringTotal: totals.recurring || undefined,
      status: draft.status,
      validUntil: draft.validUntil,
      // Recalcula slug caso o cliente tenha mudado, preservando o número.
      slug: `${slugify(draft.clientName)}-${summary.number.toLowerCase()}`,
    };
    const detailPatch: Partial<ProposalDetail> = {
      contactName: draft.contactName,
      email: draft.email,
      whatsapp: draft.whatsapp,
      website: draft.website || undefined,
      items: draft.items,
      scope: draft.scope,
      deliverables: draft.deliverables,
      observations: draft.observations || undefined,
      deadlineDays: draft.deadlineDays,
      paymentMethod: draft.paymentMethods[0] ?? "pix",
      paymentMethods: draft.paymentMethods,
      installments: draft.installments,
    };
    proposalsStore.update(id, summaryPatch, detailPatch);
    toast.success("Proposta atualizada!", {
      description: `#${summary.number} salva com sucesso.`,
    });
    navigate({ to: "/propostas/$id", params: { id } });
  };

  return (
    <ProposalWizard
      mode="edit"
      title="Editar proposta"
      subtitle={`#${summary.number}`}
      initial={initial}
      submitLabel="Salvar alterações"
      onSubmit={handleSubmit}
      backSlot={
        <Button asChild variant="ghost" size="sm" className="-ml-2 gap-1 text-muted-foreground">
          <Link to="/propostas/$id" params={{ id }}>
            <ArrowLeft className="h-4 w-4" /> Voltar para a proposta
          </Link>
        </Button>
      }

      summaryHint="As alterações serão salvas na proposta atual."
    />
  );
}
