import { useState, useEffect } from "react";
import { TrendingUp, TriangleAlert } from "lucide-react";
import {
  PieChart,
  Pie,
  Cell,
  BarChart,
  Bar,
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip,
  Legend,
  ResponsiveContainer,
} from "recharts";
import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert";
import { Badge } from "@/components/ui/badge";
import { Skeleton } from "@/components/ui/skeleton";
import { useCosts } from "@/api/costs";

const COLORS = [
  "#6366f1", "#10b981", "#f59e0b", "#ef4444",
  "#3b82f6", "#ec4899", "#14b8a6", "#f97316",
];

const STORAGE_KEY = "veylant_budget_alerts";

interface BudgetAlert {
  id: string;
  threshold: number;
}

function loadAlerts(): BudgetAlert[] {
  try {
    return JSON.parse(localStorage.getItem(STORAGE_KEY) ?? "[]");
  } catch {
    return [];
  }
}

// Extrapolate month-end cost from current total and elapsed days
function projectMonthEnd(total: number): number {
  const now = new Date();
  const dayOfMonth = now.getDate();
  const daysInMonth = new Date(now.getFullYear(), now.getMonth() + 1, 0).getDate();
  if (dayOfMonth === 0) return total;
  return (total / dayOfMonth) * daysInMonth;
}

export function CostsPage() {
  const { data: byModel, isLoading: loadingModel } = useCosts({ group_by: "model" }, 60_000);
  const { data: byDept, isLoading: loadingDept } = useCosts({ group_by: "department" }, 60_000);
  const [alerts] = useState<BudgetAlert[]>(loadAlerts);

  const totalCost = byModel?.data.reduce((s, c) => s + c.total_cost_usd, 0) ?? 0;
  const projection = projectMonthEnd(totalCost);
  const maxAlert = alerts.length > 0 ? Math.min(...alerts.map((a) => a.threshold)) : null;
  const budgetPct = maxAlert ? (totalCost / maxAlert) * 100 : null;
  const overBudget = budgetPct !== null && budgetPct >= 80;

  const modelData = (byModel?.data ?? []).map((c) => ({
    name: c.key || "unknown",
    value: parseFloat(c.total_cost_usd.toFixed(6)),
  }));

  const deptData = (byDept?.data ?? []).map((c) => ({
    name: c.key || "—",
    cost: parseFloat(c.total_cost_usd.toFixed(6)),
    requests: c.request_count,
  }));

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h2 className="text-xl font-bold flex items-center gap-2">
            <TrendingUp className="h-5 w-5 text-primary" />
            Coûts IA
          </h2>
          <p className="text-sm text-muted-foreground">
            Analyse des dépenses par modèle et département
          </p>
        </div>
      </div>

      {/* Budget alert */}
      {overBudget && (
        <Alert variant="destructive">
          <TriangleAlert className="h-4 w-4" />
          <AlertTitle>Alerte budget : {budgetPct!.toFixed(0)}% du seuil atteint</AlertTitle>
          <AlertDescription>
            Dépenses actuelles : <strong>${totalCost.toFixed(4)}</strong> sur un seuil de{" "}
            <strong>${maxAlert!.toFixed(2)}</strong>.
          </AlertDescription>
        </Alert>
      )}

      {/* KPIs */}
      <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
        <div className="rounded-lg border bg-card p-4">
          <p className="text-xs text-muted-foreground">Total période</p>
          <p className="text-2xl font-bold mt-1">${totalCost.toFixed(4)}</p>
        </div>
        <div className="rounded-lg border bg-card p-4">
          <p className="text-xs text-muted-foreground">Projection fin de mois</p>
          <p className="text-2xl font-bold mt-1">${projection.toFixed(4)}</p>
          <p className="text-xs text-muted-foreground mt-1">Extrapolation linéaire</p>
        </div>
        <div className="rounded-lg border bg-card p-4">
          <p className="text-xs text-muted-foreground">Modèles utilisés</p>
          <p className="text-2xl font-bold mt-1">{modelData.length}</p>
        </div>
        <div className="rounded-lg border bg-card p-4">
          <p className="text-xs text-muted-foreground">
            Budget consommé
            {maxAlert && (
              <Badge
                variant={overBudget ? "destructive" : "secondary"}
                className="ml-2 text-xs"
              >
                {budgetPct!.toFixed(0)}%
              </Badge>
            )}
          </p>
          <p className="text-2xl font-bold mt-1">
            {maxAlert ? `$${maxAlert.toFixed(2)}` : "—"}
          </p>
          <p className="text-xs text-muted-foreground mt-1">
            {maxAlert ? "Seuil configuré" : "Aucune alerte"}
          </p>
        </div>
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        {/* Pie: cost by model */}
        <div className="rounded-lg border bg-card p-4">
          <h3 className="text-sm font-semibold mb-4">Coûts par modèle</h3>
          {loadingModel ? (
            <Skeleton className="h-56 w-full" />
          ) : modelData.length === 0 ? (
            <p className="text-sm text-muted-foreground text-center py-12">Aucune donnée</p>
          ) : (
            <ResponsiveContainer width="100%" height={230}>
              <PieChart>
                <Pie
                  data={modelData}
                  dataKey="value"
                  nameKey="name"
                  cx="50%"
                  cy="50%"
                  outerRadius={80}
                  label={({ name, percent }) =>
                    `${name} (${(percent * 100).toFixed(0)}%)`
                  }
                  labelLine={false}
                >
                  {modelData.map((_, idx) => (
                    <Cell key={idx} fill={COLORS[idx % COLORS.length]} />
                  ))}
                </Pie>
                <Tooltip formatter={(v: number) => `$${v.toFixed(6)}`} />
              </PieChart>
            </ResponsiveContainer>
          )}
        </div>

        {/* Bar: cost by department */}
        <div className="rounded-lg border bg-card p-4">
          <h3 className="text-sm font-semibold mb-4">Coûts par département</h3>
          {loadingDept ? (
            <Skeleton className="h-56 w-full" />
          ) : deptData.length === 0 ? (
            <p className="text-sm text-muted-foreground text-center py-12">Aucune donnée</p>
          ) : (
            <ResponsiveContainer width="100%" height={230}>
              <BarChart data={deptData} margin={{ top: 4, right: 8, bottom: 24, left: 0 }}>
                <CartesianGrid strokeDasharray="3 3" className="stroke-border" />
                <XAxis dataKey="name" tick={{ fontSize: 11 }} angle={-20} textAnchor="end" />
                <YAxis tick={{ fontSize: 11 }} />
                <Tooltip formatter={(v: number) => `$${v.toFixed(6)}`} />
                <Legend />
                <Bar dataKey="cost" name="Coût USD" fill="#6366f1" radius={[4, 4, 0, 0]} />
              </BarChart>
            </ResponsiveContainer>
          )}
        </div>
      </div>

      {/* Model breakdown table */}
      <div className="rounded-lg border bg-card p-4">
        <h3 className="text-sm font-semibold mb-3">Détail par modèle</h3>
        {loadingModel ? (
          <Skeleton className="h-32 w-full" />
        ) : modelData.length === 0 ? (
          <p className="text-sm text-muted-foreground text-center py-4">Aucune donnée</p>
        ) : (
          <div className="space-y-2">
            {(byModel?.data ?? [])
              .sort((a, b) => b.total_cost_usd - a.total_cost_usd)
              .map((c, idx) => {
                const pct = totalCost > 0 ? (c.total_cost_usd / totalCost) * 100 : 0;
                return (
                  <div key={c.key} className="flex items-center gap-3">
                    <div
                      className="h-3 w-3 rounded-full shrink-0"
                      style={{ background: COLORS[idx % COLORS.length] }}
                    />
                    <span className="text-sm font-mono flex-1 truncate">{c.key || "unknown"}</span>
                    <span className="text-xs text-muted-foreground w-20 text-right">
                      {c.request_count.toLocaleString()} req.
                    </span>
                    <span className="text-xs text-muted-foreground w-20 text-right">
                      {c.total_tokens.toLocaleString()} tok.
                    </span>
                    <span className="text-sm font-semibold w-24 text-right">
                      ${c.total_cost_usd.toFixed(4)}
                    </span>
                    <div className="w-24 bg-muted rounded-full h-1.5">
                      <div
                        className="h-1.5 rounded-full"
                        style={{
                          width: `${pct}%`,
                          background: COLORS[idx % COLORS.length],
                        }}
                      />
                    </div>
                  </div>
                );
              })}
          </div>
        )}
      </div>
    </div>
  );
}
