"use client";

import {
  AreaChart, Area, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer,
} from "recharts";
import {
  TrendingUp, TrendingDown, Euro, Receipt, Wallet, Building2, Clock, AlertTriangle,
} from "lucide-react";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Skeleton } from "@/components/ui/skeleton";
import { cn, formatCurrency, formatDate, INVOICE_STATUS_CONFIG } from "@/lib/utils";
import Link from "next/link";

type KPIs = {
  revenue: number; revenueTrend: number;
  expenses: number; expensesTrend: number;
  netProfit: number; netProfitTrend: number;
  cashBalance: number; cashTrend: number;
};

type Invoice = {
  id: string; number: string; customer: string;
  total: number; status: string; date: string;
};

type PendingInvoice = Invoice & { amountDue: number; dueDate: string | null };

type MonthlyData = { month: string; revenue: number; expenses: number };

type DashboardData = {
  kpis: KPIs;
  recentInvoices: Invoice[];
  pendingInvoices: PendingInvoice[];
  monthlyData: MonthlyData[];
};

function KpiCard({
  title,
  value,
  trend,
  icon: Icon,
  accentClass,
}: {
  title: string;
  value: number;
  trend: number;
  icon: React.ElementType;
  accentClass: string;
}) {
  const isPositive = trend >= 0;
  const TrendIcon = isPositive ? TrendingUp : TrendingDown;

  return (
    <Card className="relative overflow-hidden group">
      {/* Subtle top accent line */}
      <div className={cn("absolute top-0 left-0 right-0 h-[2px]", accentClass)} />
      <CardContent className="pt-5 pb-4">
        <div className="flex items-start justify-between mb-3">
          <p className="text-[11.5px] font-semibold uppercase tracking-[0.1em] text-muted-foreground/70">
            {title}
          </p>
          <div className={cn("h-7 w-7 rounded-md flex items-center justify-center opacity-80", accentClass.replace("bg-", "bg-").replace("[2px]", ""))}>
            <Icon className="h-3.5 w-3.5" />
          </div>
        </div>
        <div className="text-[22px] font-bold tracking-tight text-foreground tabular-nums">
          {formatCurrency(value)}
        </div>
        <div
          className={cn(
            "flex items-center gap-1 mt-1.5 text-[11px] font-medium",
            isPositive ? "text-emerald-600 dark:text-emerald-400" : "text-red-500"
          )}
        >
          <TrendIcon className="h-3 w-3 shrink-0" />
          <span>{Math.abs(trend)}% vs mois précédent</span>
        </div>
      </CardContent>
    </Card>
  );
}

function CustomTooltip({ active, payload, label }: any) {
  if (!active || !payload?.length) return null;
  return (
    <div className="rounded-lg border bg-background p-3 shadow-lg text-sm">
      <p className="font-semibold mb-2">{label}</p>
      {payload.map((entry: any) => (
        <div key={entry.name} className="flex items-center gap-2">
          <span className="h-2 w-2 rounded-full" style={{ background: entry.color }} />
          <span className="text-muted-foreground">{entry.name} :</span>
          <span className="font-medium">{formatCurrency(entry.value)}</span>
        </div>
      ))}
    </div>
  );
}

export function DashboardClient({ data }: { data: DashboardData }) {
  const { kpis, recentInvoices, pendingInvoices, monthlyData } = data;

  return (
    <div className="space-y-6">
      {/* KPIs */}
      <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
        <KpiCard
          title="Chiffre d'affaires"
          value={kpis.revenue}
          trend={kpis.revenueTrend}
          icon={Euro}
          accentClass="bg-primary/80"
        />
        <KpiCard
          title="Dépenses"
          value={kpis.expenses}
          trend={kpis.expensesTrend}
          icon={Receipt}
          accentClass="bg-rose-500/70"
        />
        <KpiCard
          title="Bénéfice net"
          value={kpis.netProfit}
          trend={kpis.netProfitTrend}
          icon={TrendingUp}
          accentClass="bg-emerald-500/70"
        />
        <KpiCard
          title="Trésorerie"
          value={kpis.cashBalance}
          trend={kpis.cashTrend}
          icon={Wallet}
          accentClass="bg-violet-500/70"
        />
      </div>

      {/* Graphique + Factures en attente */}
      <div className="grid gap-4 lg:grid-cols-3">
        {/* Graphique */}
        <Card className="lg:col-span-2">
          <CardHeader>
            <CardTitle className="text-base">Revenus vs Dépenses</CardTitle>
            <p className="text-xs text-muted-foreground">6 derniers mois</p>
          </CardHeader>
          <CardContent>
            <ResponsiveContainer width="100%" height={240}>
              <AreaChart data={monthlyData} margin={{ top: 4, right: 4, bottom: 0, left: 0 }}>
                <defs>
                  <linearGradient id="colorRevenue" x1="0" y1="0" x2="0" y2="1">
                    <stop offset="5%"  stopColor="hsl(var(--chart-1))" stopOpacity={0.2} />
                    <stop offset="95%" stopColor="hsl(var(--chart-1))" stopOpacity={0}   />
                  </linearGradient>
                  <linearGradient id="colorExpenses" x1="0" y1="0" x2="0" y2="1">
                    <stop offset="5%"  stopColor="hsl(var(--chart-4))" stopOpacity={0.2} />
                    <stop offset="95%" stopColor="hsl(var(--chart-4))" stopOpacity={0}   />
                  </linearGradient>
                </defs>
                <CartesianGrid strokeDasharray="3 3" stroke="hsl(var(--border))" vertical={false} />
                <XAxis
                  dataKey="month"
                  tick={{ fontSize: 12, fill: "hsl(var(--muted-foreground))" }}
                  axisLine={false}
                  tickLine={false}
                />
                <YAxis
                  tick={{ fontSize: 11, fill: "hsl(var(--muted-foreground))" }}
                  axisLine={false}
                  tickLine={false}
                  tickFormatter={(v) => `${(v / 1000).toFixed(0)}k€`}
                />
                <Tooltip content={<CustomTooltip />} />
                <Area
                  type="monotone"
                  dataKey="revenue"
                  name="Revenus"
                  stroke="hsl(var(--chart-1))"
                  strokeWidth={2}
                  fill="url(#colorRevenue)"
                />
                <Area
                  type="monotone"
                  dataKey="expenses"
                  name="Dépenses"
                  stroke="hsl(var(--chart-4))"
                  strokeWidth={2}
                  fill="url(#colorExpenses)"
                />
              </AreaChart>
            </ResponsiveContainer>
          </CardContent>
        </Card>

        {/* Factures en attente */}
        <Card>
          <CardHeader>
            <div className="flex items-center justify-between">
              <CardTitle className="text-base">En attente</CardTitle>
              <Badge variant="warning">{pendingInvoices.length}</Badge>
            </div>
          </CardHeader>
          <CardContent className="space-y-3">
            {pendingInvoices.length === 0 ? (
              <p className="text-sm text-muted-foreground text-center py-4">
                Aucune facture en attente
              </p>
            ) : (
              pendingInvoices.map((inv) => {
                const cfg = INVOICE_STATUS_CONFIG[inv.status as keyof typeof INVOICE_STATUS_CONFIG];
                const isOverdue = inv.status === "OVERDUE";
                return (
                  <Link key={inv.id} href={`/factures/${inv.id}`} className="block">
                    <div className="flex items-center justify-between p-2.5 rounded-md hover:bg-muted/50 transition-colors">
                      <div className="min-w-0">
                        <div className="flex items-center gap-1.5">
                          {isOverdue && <AlertTriangle className="h-3 w-3 text-red-500 shrink-0" />}
                          <p className="text-xs font-medium truncate">{inv.customer}</p>
                        </div>
                        <p className="text-[11px] text-muted-foreground">{inv.number}</p>
                      </div>
                      <div className="text-right shrink-0 ml-2">
                        <p className="text-xs font-semibold">{formatCurrency(inv.amountDue)}</p>
                        <span className={cn("text-[10px] px-1.5 py-0.5 rounded-full font-medium", cfg?.color)}>
                          {cfg?.label}
                        </span>
                      </div>
                    </div>
                  </Link>
                );
              })
            )}
            <Link
              href="/factures"
              className="block text-center text-xs text-primary hover:underline pt-1"
            >
              Voir toutes les factures →
            </Link>
          </CardContent>
        </Card>
      </div>

      {/* Dernières factures */}
      <Card>
        <CardHeader>
          <div className="flex items-center justify-between">
            <CardTitle className="text-base">Dernières factures</CardTitle>
            <Link href="/factures" className="text-xs text-primary hover:underline">
              Voir tout
            </Link>
          </div>
        </CardHeader>
        <CardContent className="p-0">
          <div className="overflow-x-auto">
            <table className="w-full text-sm">
              <thead>
                <tr className="border-b text-xs text-muted-foreground">
                  <th className="text-left font-medium px-6 py-3">Numéro</th>
                  <th className="text-left font-medium px-3 py-3">Client</th>
                  <th className="text-right font-medium px-3 py-3">Montant</th>
                  <th className="text-center font-medium px-3 py-3">Statut</th>
                  <th className="text-right font-medium px-6 py-3">Date</th>
                </tr>
              </thead>
              <tbody>
                {recentInvoices.map((inv, i) => {
                  const cfg = INVOICE_STATUS_CONFIG[inv.status as keyof typeof INVOICE_STATUS_CONFIG];
                  return (
                    <tr
                      key={inv.id}
                      className="border-b last:border-0 hover:bg-muted/30 transition-colors"
                    >
                      <td className="px-6 py-3">
                        <Link href={`/factures/${inv.id}`} className="font-mono text-xs font-medium text-primary hover:underline">
                          {inv.number}
                        </Link>
                      </td>
                      <td className="px-3 py-3 text-muted-foreground">{inv.customer}</td>
                      <td className="px-3 py-3 text-right font-semibold tabular-nums">
                        {formatCurrency(inv.total)}
                      </td>
                      <td className="px-3 py-3 text-center">
                        <span className={cn("inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-xs font-medium", cfg?.color)}>
                          <span className={cn("h-1.5 w-1.5 rounded-full", cfg?.dot)} />
                          {cfg?.label}
                        </span>
                      </td>
                      <td className="px-6 py-3 text-right text-xs text-muted-foreground">
                        {formatDate(inv.date)}
                      </td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </div>
        </CardContent>
      </Card>
    </div>
  );
}
