import { createFileRoute, Link } from "@tanstack/react-router";
import { useMemo } from "react";
import {
  FileText,
  Send,
  CheckCircle2,
  TrendingUp,
  ArrowUpRight,
  PenLine,
  Wallet,
  Plus,
  AlertTriangle,
  Sparkles,
} from "lucide-react";

import { Card, CardContent } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { ProposalStatusBadge } from "@/components/proposal-status-badge";
import { useProposals } from "@/lib/store/proposals-store";
import { formatBRL, formatDate } from "@/lib/format";
import { getEffectiveStatus, isExpired } from "@/lib/proposal-status";
import type { ProposalStatus, ProposalSummary } from "@/lib/mock/types";
import heroBg from "@/assets/hero-bg.webp";

export const Route = createFileRoute("/_admin/dashboard")({
  component: DashboardPage,
});

function DashboardPage() {
  const proposals = useProposals();

  const stats = useMemo(() => {
    const sum = (list: ProposalSummary[]) =>
      list.reduce((acc, p) => acc + p.total, 0);
    const withEff = proposals.map((p) => ({ p, eff: getEffectiveStatus(p) }));
    const rascunho = withEff.filter((x) => x.eff === "rascunho").map((x) => x.p);
    const enviada = withEff.filter((x) => x.eff === "enviada").map((x) => x.p);
    const aprovada = withEff.filter((x) => x.eff === "aprovada").map((x) => x.p);
    const vencida = withEff.filter((x) => x.eff === "expirada").map((x) => x.p);
    const pipeline = withEff
      .filter((x) => x.eff !== "aprovada")
      .map((x) => x.p);
    return {
      total: proposals.length,
      rascunho: rascunho.length,
      enviada: enviada.length,
      aprovada: aprovada.length,
      vencida: vencida.length,
      pipelineValue: sum(pipeline),
      approvedValue: sum(aprovada),
    };
  }, [proposals]);

  const recent = useMemo(
    () =>
      [...proposals]
        .sort((a, b) => b.createdAt.localeCompare(a.createdAt))
        .slice(0, 5),
    [proposals],
  );

  const kpis = [
    {
      label: "Total de propostas",
      value: String(stats.total),
      icon: FileText,
      tint: "primary" as const,
    },
    {
      label: "Rascunhos",
      value: String(stats.rascunho),
      icon: PenLine,
      tint: "muted" as const,
    },
    {
      label: "Enviadas",
      value: String(stats.enviada),
      icon: Send,
      tint: "primary" as const,
    },
    {
      label: "Aprovadas",
      value: String(stats.aprovada),
      icon: CheckCircle2,
      tint: "success" as const,
    },
    {
      label: "Pipeline",
      value: formatBRL(stats.pipelineValue),
      icon: Wallet,
      tint: "primary" as const,
      compact: true,
    },
    {
      label: "Aprovado",
      value: formatBRL(stats.approvedValue),
      icon: TrendingUp,
      tint: "success" as const,
      compact: true,
    },
  ];

  const distribution: Array<{
    label: string;
    status: ProposalStatus | "vencida";
    count: number;
  }> = [
    { label: "Rascunho", status: "rascunho", count: stats.rascunho },
    { label: "Enviada", status: "enviada", count: stats.enviada },
    { label: "Aprovada", status: "aprovada", count: stats.aprovada },
    { label: "Vencida", status: "expirada", count: stats.vencida },
  ];
  const distMax = Math.max(1, ...distribution.map((d) => d.count));

  return (
    <div className="space-y-8">
      {/* ---------- Hero ---------- */}
      <section
        className="relative overflow-hidden rounded-2xl border border-border/50 bg-gradient-dark p-6 text-white shadow-glow sm:p-10"
        style={{
          backgroundImage: `linear-gradient(135deg, oklch(0.12 0.02 250 / 0.85), oklch(0.12 0.02 250 / 0.6)), url(${heroBg})`,
          backgroundSize: "cover",
          backgroundPosition: "center",
        }}
      >
        <div className="max-w-2xl">
          <span className="inline-flex items-center gap-1.5 rounded-full border border-white/20 bg-white/5 px-3 py-1 text-xs font-medium uppercase tracking-wider text-white/80">
            <Sparkles className="h-3.5 w-3.5" /> X3 Sites · Propostas
          </span>
          <h2 className="mt-4 font-display text-3xl font-semibold leading-tight sm:text-4xl">
            Crie propostas comerciais{" "}
            <span className="text-gradient-brand">memoráveis</span> em minutos.
          </h2>
          <p className="mt-3 max-w-xl text-sm text-white/70 sm:text-base">
            Organize clientes, monte escopos personalizados e envie propostas
            profissionais com link público e PDF.
          </p>
          <div className="mt-6 flex flex-wrap gap-3">
            <Button
              asChild
              size="lg"
              className="bg-white text-foreground hover:bg-white/90"
            >
              <Link to="/propostas/nova">
                <Plus className="h-4 w-4" /> Nova proposta
              </Link>
            </Button>
            <Button
              asChild
              size="lg"
              variant="outline"
              className="border-white/30 bg-white/0 text-white hover:bg-white/10 hover:text-white"
            >
              <Link to="/propostas">Ver propostas</Link>
            </Button>
          </div>
        </div>
      </section>

      {/* ---------- KPIs ---------- */}
      <section className="grid gap-3 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-6">
        {kpis.map((k) => (
          <StatCard
            key={k.label}
            icon={k.icon}
            label={k.label}
            value={k.value}
            tint={k.tint}
            compact={k.compact}
          />
        ))}
      </section>

      {/* ---------- Distribution + Recent ---------- */}
      <section className="grid gap-6 lg:grid-cols-3">
        <Card className="border-border/60 shadow-soft lg:col-span-1">
          <CardContent className="p-6">
            <div className="mb-4 flex items-center justify-between">
              <h3 className="font-display text-lg font-semibold">
                Distribuição por status
              </h3>
            </div>
            {stats.total === 0 ? (
              <p className="text-sm text-muted-foreground">
                Sem propostas para distribuir ainda.
              </p>
            ) : (
              <ul className="space-y-3">
                {distribution.map((d) => {
                  const pct = Math.round((d.count / distMax) * 100);
                  const barClass =
                    d.status === "aprovada"
                      ? "bg-success"
                      : d.status === "enviada"
                        ? "bg-gradient-brand"
                        : d.status === "expirada"
                          ? "bg-destructive/70"
                          : "bg-muted-foreground/40";
                  return (
                    <li key={d.label} className="space-y-1.5">
                      <div className="flex items-center justify-between text-sm">
                        <span className="font-medium">{d.label}</span>
                        <span className="font-display font-semibold">
                          {d.count}
                        </span>
                      </div>
                      <div className="h-2 overflow-hidden rounded-full bg-muted">
                        <div
                          className={`h-full rounded-full transition-all ${barClass}`}
                          style={{ width: `${pct}%` }}
                        />
                      </div>
                    </li>
                  );
                })}
              </ul>
            )}
          </CardContent>
        </Card>

        <div className="lg:col-span-2">
          <div className="mb-4 flex items-center justify-between">
            <h3 className="font-display text-lg font-semibold">
              Propostas recentes
            </h3>
            <Button
              asChild
              variant="ghost"
              size="sm"
              className="gap-1 text-primary hover:text-primary"
            >
              <Link to="/propostas">
                Ver todas <ArrowUpRight className="h-4 w-4" />
              </Link>
            </Button>
          </div>
          <Card className="border-border/60 shadow-soft">
            <CardContent className="divide-y divide-border/60 p-0">
              {recent.length === 0 ? (
                <div className="flex flex-col items-center gap-3 px-6 py-10 text-center">
                  <div className="flex h-12 w-12 items-center justify-center rounded-full bg-muted">
                    <FileText className="h-5 w-5 text-muted-foreground" />
                  </div>
                  <div>
                    <div className="font-display text-base font-semibold">
                      Nenhuma proposta ainda
                    </div>
                    <p className="mt-1 text-sm text-muted-foreground">
                      Crie sua primeira proposta para começar a acompanhar o
                      pipeline.
                    </p>
                  </div>
                  <Button
                    asChild
                    size="sm"
                    className="bg-gradient-brand text-white"
                  >
                    <Link to="/propostas/nova">
                      <Plus className="h-4 w-4" /> Nova proposta
                    </Link>
                  </Button>
                </div>
              ) : (
                recent.map((p) => (
                  <div
                    key={p.id}
                    className="flex flex-col gap-3 p-4 sm:flex-row sm:items-center sm:justify-between"
                  >
                    <div className="min-w-0">
                      <div className="text-xs text-muted-foreground">
                        #{p.number} · {p.clientName}
                      </div>
                      <div className="truncate font-medium">{p.title}</div>
                    </div>
                    <div className="flex flex-wrap items-center gap-3">
                      <span className="inline-flex items-center gap-1 text-xs text-muted-foreground">
                        {isExpired(p) && p.status !== "aprovada" && (
                          <AlertTriangle className="h-3.5 w-3.5 text-destructive" />
                        )}
                        Válida até {formatDate(p.validUntil)}
                      </span>
                      <span className="font-display font-semibold">
                        {formatBRL(p.total)}
                      </span>
                      <ProposalStatusBadge status={getEffectiveStatus(p)} />
                      <Button
                        asChild
                        size="sm"
                        variant="outline"
                        className="h-8 gap-1 border-primary/30 text-primary hover:bg-primary/5"
                      >
                        <Link to="/propostas/$id" params={{ id: p.id }}>
                          Ver detalhes <ArrowUpRight className="h-3.5 w-3.5" />
                        </Link>
                      </Button>
                    </div>
                  </div>
                ))
              )}
            </CardContent>
          </Card>
        </div>
      </section>
    </div>
  );
}

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

function StatCard({
  icon: Icon,
  label,
  value,
  tint,
  compact,
}: {
  icon: React.ComponentType<{ className?: string }>;
  label: string;
  value: string;
  tint: "primary" | "success" | "muted";
  compact?: boolean;
}) {
  const tintClass =
    tint === "success"
      ? "bg-success/15 text-success"
      : tint === "muted"
        ? "bg-muted text-muted-foreground"
        : "bg-gradient-brand text-white";

  return (
    <Card className="border-border/60 shadow-soft transition hover:-translate-y-0.5 hover:shadow-glow">
      <CardContent className="flex items-center gap-3 p-4">
        <div
          className={`flex h-10 w-10 shrink-0 items-center justify-center rounded-lg ${tintClass}`}
        >
          <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={`font-display font-semibold ${compact ? "text-lg" : "text-2xl"} truncate`}
          >
            {value}
          </div>
        </div>
      </CardContent>
    </Card>
  );
}
