"use client";

import { useState, useEffect, useCallback } from "react";
import { toast } from "sonner";
import {
  Landmark, Plus, Loader2, Trash2, ArrowUpRight, ArrowDownRight,
  AlertCircle, X,
} from "lucide-react";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from "@/components/ui/card";
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { formatCurrency, formatDate } from "@/lib/utils";

// ─── Types ─────────────────────────────────────────────────────

type Transaction = {
  id: string;
  description: string;
  amount: number;
  type: "INCOME" | "EXPENSE";
  date: string;
};

type BankAccount = {
  id: string;
  name: string;
  bankName: string | null;
  iban: string | null;
  currency: string;
  balance: number;
  _count: { transactions: number };
  transactions: Transaction[];
};

// ─── Component ─────────────────────────────────────────────────

export default function BanquePage() {
  const [accounts, setAccounts] = useState<BankAccount[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [dialogOpen, setDialogOpen] = useState(false);
  const [saving, setSaving] = useState(false);
  const [deleting, setDeleting] = useState<string | null>(null);

  // Form state
  const [form, setForm] = useState({
    name: "",
    bankName: "",
    iban: "",
    bic: "",
    currency: "XOF",
    balance: "0",
  });

  const fetchAccounts = useCallback(async () => {
    setLoading(true);
    setError(null);
    try {
      const res = await fetch("/api/bank");
      const json = await res.json();
      if (!json.success) throw new Error(json.error ?? "Erreur serveur");
      setAccounts(json.data ?? []);
    } catch (e) {
      setError(e instanceof Error ? e.message : "Erreur inconnue");
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => { fetchAccounts(); }, [fetchAccounts]);

  const totalBalance = accounts.reduce((sum, a) => sum + Number(a.balance), 0);

  function resetForm() {
    setForm({ name: "", bankName: "", iban: "", bic: "", currency: "XOF", balance: "0" });
  }

  async function handleCreate(e: React.FormEvent) {
    e.preventDefault();
    if (!form.name.trim()) { toast.error("Nom du compte requis"); return; }
    setSaving(true);
    try {
      const res = await fetch("/api/bank", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          name: form.name,
          bankName: form.bankName || undefined,
          iban: form.iban || undefined,
          bic: form.bic || undefined,
          currency: form.currency,
          balance: parseFloat(form.balance) || 0,
        }),
      });
      const json = await res.json();
      if (!json.success) throw new Error(json.error ?? "Erreur");
      toast.success("Compte créé");
      setDialogOpen(false);
      resetForm();
      fetchAccounts();
    } catch (e) {
      toast.error(e instanceof Error ? e.message : "Erreur");
    } finally {
      setSaving(false);
    }
  }

  async function handleDelete(id: string, name: string) {
    if (!confirm(`Supprimer le compte "${name}" ?`)) return;
    setDeleting(id);
    try {
      const res = await fetch(`/api/bank/${id}`, { method: "DELETE" });
      const json = await res.json();
      if (!json.success) throw new Error(json.error ?? "Erreur");
      toast.success("Compte supprimé");
      fetchAccounts();
    } catch (e) {
      toast.error(e instanceof Error ? e.message : "Erreur");
    } finally {
      setDeleting(null);
    }
  }

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold tracking-tight">Banque</h1>
          <p className="text-sm text-muted-foreground">Vos comptes bancaires et mouvements</p>
        </div>
        <Button onClick={() => setDialogOpen(true)}>
          <Plus className="mr-2 h-4 w-4" />
          Ajouter un compte
        </Button>
      </div>

      {/* Solde total */}
      {!loading && accounts.length > 0 && (
        <Card className="bg-primary text-primary-foreground">
          <CardHeader>
            <CardDescription className="text-primary-foreground/70">Solde total consolidé</CardDescription>
            <CardTitle className="text-3xl font-bold tabular-nums">{formatCurrency(totalBalance)}</CardTitle>
          </CardHeader>
          <CardContent>
            <p className="text-sm text-primary-foreground/70">{accounts.length} compte{accounts.length > 1 ? "s" : ""}</p>
          </CardContent>
        </Card>
      )}

      {/* Content */}
      {loading ? (
        <div className="flex justify-center py-24">
          <Loader2 className="h-6 w-6 animate-spin text-muted-foreground" />
        </div>
      ) : error ? (
        <Card>
          <CardContent className="flex flex-col items-center gap-3 py-16">
            <AlertCircle className="h-8 w-8 text-destructive" />
            <p className="text-sm text-muted-foreground">{error}</p>
            <Button variant="outline" size="sm" onClick={fetchAccounts}>Réessayer</Button>
          </CardContent>
        </Card>
      ) : accounts.length === 0 ? (
        <Card>
          <CardContent className="flex flex-col items-center justify-center py-16 gap-4">
            <Landmark className="h-12 w-12 text-muted-foreground/30" />
            <p className="text-muted-foreground text-sm">Aucun compte bancaire configuré</p>
            <p className="text-xs text-muted-foreground">Ajoutez un compte pour commencer le suivi de trésorerie</p>
            <Button onClick={() => setDialogOpen(true)}>
              <Plus className="mr-2 h-4 w-4" />
              Ajouter un compte
            </Button>
          </CardContent>
        </Card>
      ) : (
        <div className="grid gap-6 md:grid-cols-2">
          {accounts.map((account) => (
            <Card key={account.id} className="flex flex-col">
              <CardHeader className="pb-3">
                <div className="flex items-start justify-between">
                  <div className="flex items-center gap-2">
                    <div className="h-9 w-9 rounded-lg bg-primary/10 flex items-center justify-center shrink-0">
                      <Landmark className="h-5 w-5 text-primary" />
                    </div>
                    <div>
                      <CardTitle className="text-sm leading-tight">{account.name}</CardTitle>
                      {account.bankName && (
                        <CardDescription className="text-xs">{account.bankName}</CardDescription>
                      )}
                    </div>
                  </div>
                  <div className="flex items-center gap-2">
                    <span className="text-lg font-bold tabular-nums">
                      {formatCurrency(Number(account.balance), account.currency)}
                    </span>
                    <Button
                      variant="ghost"
                      size="icon"
                      className="h-7 w-7 text-muted-foreground hover:text-destructive"
                      disabled={deleting === account.id}
                      onClick={() => handleDelete(account.id, account.name)}
                    >
                      {deleting === account.id
                        ? <Loader2 className="h-3.5 w-3.5 animate-spin" />
                        : <Trash2 className="h-3.5 w-3.5" />}
                    </Button>
                  </div>
                </div>
                {account.iban && (
                  <p className="text-xs text-muted-foreground font-mono mt-2 truncate">{account.iban}</p>
                )}
              </CardHeader>

              {/* Dernières transactions */}
              <CardContent className="flex-1 pt-0">
                <p className="text-xs font-semibold text-muted-foreground uppercase tracking-wide mb-2">
                  Derniers mouvements ({account._count.transactions} au total)
                </p>
                {account.transactions.length === 0 ? (
                  <p className="text-xs text-muted-foreground py-3 text-center">Aucune transaction</p>
                ) : (
                  <div className="space-y-1.5">
                    {account.transactions.map((tx) => (
                      <div key={tx.id} className="flex items-center justify-between">
                        <div className="flex items-center gap-2 min-w-0">
                          <div className={`h-6 w-6 rounded-full flex items-center justify-center shrink-0 ${
                            tx.type === "INCOME"
                              ? "bg-green-100 text-green-600 dark:bg-green-900/30"
                              : "bg-red-100 text-red-600 dark:bg-red-900/30"
                          }`}>
                            {tx.type === "INCOME"
                              ? <ArrowUpRight className="h-3 w-3" />
                              : <ArrowDownRight className="h-3 w-3" />}
                          </div>
                          <div className="min-w-0">
                            <p className="text-xs font-medium truncate">{tx.description}</p>
                            <p className="text-[10px] text-muted-foreground">{formatDate(tx.date)}</p>
                          </div>
                        </div>
                        <span className={`text-xs font-semibold tabular-nums shrink-0 ml-2 ${
                          tx.type === "INCOME" ? "text-green-600" : "text-red-500"
                        }`}>
                          {tx.type === "INCOME" ? "+" : "-"}{formatCurrency(Number(tx.amount), account.currency)}
                        </span>
                      </div>
                    ))}
                  </div>
                )}
              </CardContent>
            </Card>
          ))}
        </div>
      )}

      {/* Dialog: ajouter un compte */}
      <Dialog open={dialogOpen} onOpenChange={(open) => { setDialogOpen(open); if (!open) resetForm(); }}>
        <DialogContent className="sm:max-w-md">
          <DialogHeader>
            <DialogTitle>Ajouter un compte bancaire</DialogTitle>
          </DialogHeader>
          <form onSubmit={handleCreate} className="space-y-4">
            <div className="grid grid-cols-2 gap-3">
              <div className="col-span-2 space-y-1.5">
                <Label htmlFor="bname">Nom du compte <span className="text-destructive">*</span></Label>
                <Input
                  id="bname"
                  placeholder="Compte courant FCFA"
                  value={form.name}
                  onChange={(e) => setForm((f) => ({ ...f, name: e.target.value }))}
                  required
                />
              </div>
              <div className="col-span-2 space-y-1.5">
                <Label htmlFor="bankName">Banque</Label>
                <Input
                  id="bankName"
                  placeholder="Ecobank, CBAO, Wave…"
                  value={form.bankName}
                  onChange={(e) => setForm((f) => ({ ...f, bankName: e.target.value }))}
                />
              </div>
              <div className="space-y-1.5">
                <Label htmlFor="currency">Devise</Label>
                <Select value={form.currency} onValueChange={(v) => setForm((f) => ({ ...f, currency: v }))}>
                  <SelectTrigger id="currency">
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="XOF">XOF — Franc CFA (UEMOA)</SelectItem>
                    <SelectItem value="XAF">XAF — Franc CFA (CEMAC)</SelectItem>
                    <SelectItem value="EUR">EUR — Euro</SelectItem>
                    <SelectItem value="USD">USD — Dollar</SelectItem>
                    <SelectItem value="GBP">GBP — Livre sterling</SelectItem>
                  </SelectContent>
                </Select>
              </div>
              <div className="space-y-1.5">
                <Label htmlFor="balance">Solde initial</Label>
                <Input
                  id="balance"
                  type="number"
                  step="1"
                  value={form.balance}
                  onChange={(e) => setForm((f) => ({ ...f, balance: e.target.value }))}
                />
              </div>
              <div className="space-y-1.5">
                <Label htmlFor="iban">IBAN / N° de compte</Label>
                <Input
                  id="iban"
                  placeholder="SN28 0001 …"
                  value={form.iban}
                  onChange={(e) => setForm((f) => ({ ...f, iban: e.target.value }))}
                />
              </div>
              <div className="space-y-1.5">
                <Label htmlFor="bic">BIC / SWIFT</Label>
                <Input
                  id="bic"
                  placeholder="ECOCSNDA"
                  value={form.bic}
                  onChange={(e) => setForm((f) => ({ ...f, bic: e.target.value }))}
                />
              </div>
            </div>
            <DialogFooter>
              <Button type="button" variant="outline" onClick={() => setDialogOpen(false)} disabled={saving}>
                <X className="mr-2 h-4 w-4" />
                Annuler
              </Button>
              <Button type="submit" disabled={saving}>
                {saving && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
                Créer le compte
              </Button>
            </DialogFooter>
          </form>
        </DialogContent>
      </Dialog>
    </div>
  );
}
