import { useState, useEffect } from "react";
import { Bell, Plus, Trash2, TriangleAlert } from "lucide-react";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";
import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert";
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 { 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({}, 30_000);
  const totalCost = costData?.data.reduce((s, c) => s + c.total_cost_usd, 0) ?? 0;

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

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

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

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

  const triggeredAlerts = alerts.filter((a) => totalCost >= a.threshold);

  return (
    <div className="space-y-6 max-w-2xl">
      <div className="flex items-center justify-between">
        <div>
          <h2 className="text-xl font-bold">Alertes Budget</h2>
          <p className="text-sm text-muted-foreground">
            Soyez notifié quand vos dépenses IA dépassent un seuil
          </p>
        </div>
        <Button onClick={() => setShowForm(!showForm)}>
          <Plus className="h-4 w-4 mr-2" /> Nouvelle alerte
        </Button>
      </div>

      {/* Triggered alerts */}
      {triggeredAlerts.length > 0 && (
        <Alert variant="destructive">
          <TriangleAlert className="h-4 w-4" />
          <AlertTitle>
            {triggeredAlerts.length} alerte{triggeredAlerts.length > 1 ? "s" : ""} déclenchée
            {triggeredAlerts.length > 1 ? "s" : ""}
          </AlertTitle>
          <AlertDescription>
            Coût actuel : <strong>${totalCost.toFixed(4)}</strong> — dépasse les seuils :{" "}
            {triggeredAlerts.map((a) => a.name).join(", ")}
          </AlertDescription>
        </Alert>
      )}

      {/* Current spend */}
      <div className="rounded-lg border bg-card p-4">
        <p className="text-sm text-muted-foreground">Dépenses totales (période actuelle)</p>
        <p className="text-3xl font-bold mt-1">${totalCost.toFixed(4)}</p>
        <p className="text-xs text-muted-foreground mt-1">USD · Mis à jour automatiquement</p>
      </div>

      {/* Create form */}
      {showForm && (
        <form onSubmit={handleCreate} className="rounded-lg border p-4 space-y-4">
          <h3 className="font-semibold text-sm">Nouvelle alerte budget</h3>
          <div className="space-y-1">
            <Label htmlFor="alert-name">Nom</Label>
            <Input id="alert-name" {...form.register("name")} placeholder="Alerte mensuelle" />
          </div>
          <div className="grid grid-cols-2 gap-3">
            <div className="space-y-1">
              <Label>Périmètre</Label>
              <Select
                value={form.watch("scope")}
                onValueChange={(v) => form.setValue("scope", v)}
              >
                <SelectTrigger>
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="global">Global</SelectItem>
                  <SelectItem value="openai">OpenAI</SelectItem>
                  <SelectItem value="anthropic">Anthropic</SelectItem>
                  <SelectItem value="azure">Azure</SelectItem>
                  <SelectItem value="mistral">Mistral</SelectItem>
                </SelectContent>
              </Select>
            </div>
            <div className="space-y-1">
              <Label htmlFor="threshold">Seuil (USD)</Label>
              <Input
                id="threshold"
                type="number"
                step="0.01"
                {...form.register("threshold")}
                placeholder="10.00"
              />
            </div>
          </div>
          <div className="flex gap-2">
            <Button type="button" variant="outline" onClick={() => setShowForm(false)}>
              Annuler
            </Button>
            <Button type="submit">Créer l&apos;alerte</Button>
          </div>
        </form>
      )}

      {/* Alerts list */}
      {alerts.length === 0 ? (
        <div className="flex flex-col items-center justify-center h-48 text-center border rounded-lg">
          <Bell className="h-8 w-8 text-muted-foreground mb-2" />
          <p className="text-muted-foreground text-sm">Aucune alerte configurée</p>
        </div>
      ) : (
        <div className="space-y-2">
          {alerts.map((alert) => {
            const isTriggered = totalCost >= alert.threshold;
            return (
              <div
                key={alert.id}
                className="flex items-center justify-between rounded-lg border p-4"
              >
                <div className="flex items-center gap-3">
                  <Bell
                    className={
                      isTriggered ? "h-5 w-5 text-destructive" : "h-5 w-5 text-muted-foreground"
                    }
                  />
                  <div>
                    <p className="font-medium text-sm">{alert.name}</p>
                    <p className="text-xs text-muted-foreground">
                      {alert.scope} · Seuil : ${alert.threshold.toFixed(2)}
                    </p>
                  </div>
                </div>
                <div className="flex items-center gap-2">
                  <Badge variant={isTriggered ? "destructive" : "secondary"}>
                    {isTriggered ? "Déclenchée" : "OK"}
                  </Badge>
                  <Button
                    variant="ghost"
                    size="icon"
                    onClick={() => handleDelete(alert.id)}
                  >
                    <Trash2 className="h-4 w-4 text-destructive" />
                  </Button>
                </div>
              </div>
            );
          })}
        </div>
      )}
    </div>
  );
}
