import { useState, useEffect } from "react";
import { Bell, Plus, Trash2, TriangleAlert, TrendingUp } from "lucide-react";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { Badge } from "@/components/ui/badge";
import { Separator } from "@/components/ui/separator";
import { useCosts } from "@/api/costs";

interface BudgetAlert {
  id: string;
  name: string;
  scope: string;
  threshold: number;
  createdAt: string;
}

const STORAGE_KEY = "veylant_budget_alerts";

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

function saveAlerts(alerts: BudgetAlert[]) {
  localStorage.setItem(STORAGE_KEY, JSON.stringify(alerts));
}

const alertSchema = z.object({
  name: z.string().min(1, "Le nom est requis"),
  scope: z.string().min(1, "Le périmètre est requis"),
  threshold: z.coerce.number().positive("Le seuil doit être positif"),
});

type AlertFormData = z.infer<typeof alertSchema>;

export function AlertsPage() {
  const [alerts, setAlerts] = useState<BudgetAlert[]>(loadAlerts);
  const [showForm, setShowForm] = useState(false);

  const { data: costData } = useCosts({ group_by: "provider" }, 30_000);
  const providerRows = costData?.data ?? [];
  const costByProvider = Object.fromEntries(
    providerRows.map((c) => [c.key, c.total_cost_usd])
  );
  const totalCost = providerRows.reduce((s, c) => s + c.total_cost_usd, 0);
  const totalRequests = providerRows.reduce((s, c) => s + c.request_count, 0);

  function getSpendForScope(scope: string): number {
    return scope === "global" ? totalCost : (costByProvider[scope] ?? 0);
  }

  const form = useForm<AlertFormData>({
    resolver: zodResolver(alertSchema),
    defaultValues: { name: "", scope: "global", threshold: 10 },
  });

  useEffect(() => {
    saveAlerts(alerts);
  }, [alerts]);

  const handleCreate = form.handleSubmit((data) => {
    const newAlert: BudgetAlert = {
      id: crypto.randomUUID(),
      name: data.name,
      scope: data.scope,
      threshold: data.threshold,
      createdAt: new Date().toISOString(),
    };
    setAlerts((prev) => [...prev, newAlert]);
    form.reset();
    setShowForm(false);
  });

  const handleDelete = (id: string) => {
    setAlerts((prev) => prev.filter((a) => a.id !== id));
  };

  const triggeredCount = alerts.filter(
    (a) => getSpendForScope(a.scope) >= a.threshold
  ).length;

  return (
    <div className="space-y-6 max-w-3xl">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div>
          <h2 className="text-xl font-bold">Alertes Budget</h2>
          <p className="text-sm text-muted-foreground">
            Règles de seuil — les notifications apparaissent dans la cloche en haut à droite
          </p>
        </div>
        <Button onClick={() => setShowForm((v) => !v)}>
          <Plus className="h-4 w-4 mr-2" /> Nouvelle règle
        </Button>
      </div>

      {/* Status strip */}
      <div className="grid grid-cols-2 sm:grid-cols-4 gap-4">
        <div className="rounded-lg border bg-card p-4 col-span-2 sm:col-span-1">
          <p className="text-xs text-muted-foreground">Total dépensé</p>
          <p className="text-2xl font-bold mt-1">${totalCost.toFixed(6)}</p>
          <p className="text-xs text-muted-foreground mt-0.5">
            {totalRequests.toLocaleString("fr-FR")} req · 30 s
          </p>
        </div>
        {providerRows.slice(0, 3).map((c) => (
          <div key={c.key} className="rounded-lg border bg-card p-4">
            <p className="text-xs text-muted-foreground capitalize">{c.key}</p>
            <p className="text-xl font-bold mt-1">${c.total_cost_usd.toFixed(6)}</p>
            <p className="text-xs text-muted-foreground mt-0.5">{c.request_count} req.</p>
          </div>
        ))}
      </div>

      {/* Summary badges */}
      {alerts.length > 0 && (
        <div className="flex items-center gap-3 text-sm">
          <span className="text-muted-foreground">
            {alerts.length} règle{alerts.length > 1 ? "s" : ""} configurée
            {alerts.length > 1 ? "s" : ""}
          </span>
          {triggeredCount > 0 && (
            <Badge variant="destructive" className="gap-1">
              <TriangleAlert className="h-3 w-3" />
              {triggeredCount} déclenchée{triggeredCount > 1 ? "s" : ""}
            </Badge>
          )}
          {triggeredCount === 0 && (
            <Badge variant="secondary" className="gap-1 text-green-700 bg-green-100">
              Tout OK
            </Badge>
          )}
        </div>
      )}

      {/* Create form */}
      {showForm && (
        <>
          <Separator />
          <form onSubmit={handleCreate} className="rounded-lg border bg-card p-5 space-y-4">
            <h3 className="font-semibold text-sm">Nouvelle règle d&apos;alerte</h3>
            <div className="space-y-1.5">
              <Label htmlFor="alert-name">Nom de la règle</Label>
              <Input
                id="alert-name"
                {...form.register("name")}
                placeholder="ex. Budget mensuel OpenAI"
              />
              {form.formState.errors.name && (
                <p className="text-xs text-destructive">
                  {form.formState.errors.name.message}
                </p>
              )}
            </div>
            <div className="grid grid-cols-2 gap-3">
              <div className="space-y-1.5">
                <Label>Périmètre</Label>
                <Select
                  value={form.watch("scope")}
                  onValueChange={(v) => form.setValue("scope", v)}
                >
                  <SelectTrigger>
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="global">Global (tous fournisseurs)</SelectItem>
                    <SelectItem value="openai">OpenAI</SelectItem>
                    <SelectItem value="anthropic">Anthropic</SelectItem>
                    <SelectItem value="azure">Azure</SelectItem>
                    <SelectItem value="mistral">Mistral</SelectItem>
                    <SelectItem value="ollama">Ollama</SelectItem>
                  </SelectContent>
                </Select>
              </div>
              <div className="space-y-1.5">
                <Label htmlFor="threshold">Seuil (USD)</Label>
                <Input
                  id="threshold"
                  type="number"
                  step="0.000001"
                  min="0"
                  {...form.register("threshold")}
                  placeholder="10.00"
                />
                {form.formState.errors.threshold && (
                  <p className="text-xs text-destructive">
                    {form.formState.errors.threshold.message}
                  </p>
                )}
              </div>
            </div>
            <div className="flex gap-2">
              <Button
                type="button"
                variant="outline"
                onClick={() => {
                  setShowForm(false);
                  form.reset();
                }}
              >
                Annuler
              </Button>
              <Button type="submit">Créer la règle</Button>
            </div>
          </form>
        </>
      )}

      {/* Rules list */}
      <Separator />

      {alerts.length === 0 ? (
        <div className="flex flex-col items-center justify-center h-48 text-center border rounded-lg border-dashed">
          <Bell className="h-8 w-8 text-muted-foreground mb-2" />
          <p className="text-sm font-medium text-muted-foreground">Aucune règle configurée</p>
          <p className="text-xs text-muted-foreground mt-1">
            Créez une règle pour générer des notifications dans la cloche
          </p>
        </div>
      ) : (
        <div className="space-y-3">
          {alerts.map((alert) => {
            const spend = getSpendForScope(alert.scope);
            const pct =
              alert.threshold > 0
                ? Math.min((spend / alert.threshold) * 100, 100)
                : 0;
            const isTriggered = spend >= alert.threshold;
            const isWarning = !isTriggered && pct >= 80;

            return (
              <div key={alert.id} className="rounded-lg border bg-card p-4 space-y-3">
                <div className="flex items-start justify-between gap-3">
                  <div className="flex items-center gap-3 min-w-0">
                    {isTriggered ? (
                      <TriangleAlert className="h-5 w-5 text-destructive shrink-0" />
                    ) : isWarning ? (
                      <TrendingUp className="h-5 w-5 text-amber-500 shrink-0" />
                    ) : (
                      <Bell className="h-5 w-5 text-muted-foreground shrink-0" />
                    )}
                    <div className="min-w-0">
                      <p className="font-medium text-sm truncate">{alert.name}</p>
                      <p className="text-xs text-muted-foreground capitalize">
                        {alert.scope === "global" ? "Tous fournisseurs" : alert.scope} · seuil $
                        {alert.threshold.toFixed(6)}
                      </p>
                    </div>
                  </div>
                  <div className="flex items-center gap-2 shrink-0">
                    <Badge
                      variant={isTriggered ? "destructive" : "secondary"}
                      className={
                        isWarning
                          ? "bg-amber-100 text-amber-800 border-amber-200 dark:bg-amber-900/30 dark:text-amber-400"
                          : ""
                      }
                    >
                      {isTriggered ? "Déclenchée" : isWarning ? "Attention" : "OK"}
                    </Badge>
                    <Button
                      variant="ghost"
                      size="icon"
                      onClick={() => handleDelete(alert.id)}
                      title="Supprimer la règle"
                    >
                      <Trash2 className="h-4 w-4 text-destructive" />
                    </Button>
                  </div>
                </div>

                {/* Progress bar */}
                <div className="space-y-1">
                  <div className="flex justify-between text-xs">
                    <span className="font-medium">${spend.toFixed(6)}</span>
                    <span className="text-muted-foreground">{pct.toFixed(1)} % du seuil</span>
                    <span className="text-muted-foreground">${alert.threshold.toFixed(6)}</span>
                  </div>
                  <div className="h-2 rounded-full bg-secondary overflow-hidden">
                    <div
                      className={`h-full rounded-full transition-all duration-500 ${
                        isTriggered
                          ? "bg-destructive"
                          : isWarning
                          ? "bg-amber-500"
                          : "bg-primary"
                      }`}
                      style={{ width: `${pct}%` }}
                    />
                  </div>
                </div>
              </div>
            );
          })}
        </div>
      )}
    </div>
  );
}
