"use client";

import { useState, useEffect, useCallback } from "react";
import {
  Plus, Search, Filter, ChevronLeft, ChevronRight,
  BookOpen, RefreshCw, X, AlertCircle, ArrowUpDown,
} from "lucide-react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Badge } from "@/components/ui/badge";
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from "@/components/ui/card";
import {
  Select, SelectContent, SelectItem, SelectTrigger, SelectValue,
} from "@/components/ui/select";
import {
  Table, TableBody, TableCell, TableHead, TableHeader, TableRow,
} from "@/components/ui/table";
import {
  Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle,
} from "@/components/ui/dialog";
import { Separator } from "@/components/ui/separator";
import { cn, formatCurrency, formatDate } from "@/lib/utils";
import { toast } from "sonner";

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

type JournalLine = {
  id: string;
  accountCode: string;
  accountLabel: string;
  debit: number;
  credit: number;
  description?: string | null;
  order: number;
};

type JournalEntry = {
  id: string;
  number: string;
  date: string;
  type: string;
  description: string;
  reference?: string | null;
  isManual: boolean;
  lines: JournalLine[];
};

type Pagination = {
  page: number;
  limit: number;
  total: number;
  totalPages: number;
};

// ─── Config types écritures ────────────────────────────────────

const ENTRY_TYPE_CONFIG: Record<string, { label: string; color: string }> = {
  MANUAL:     { label: "Manuelle",    color: "bg-purple-100 text-purple-700 dark:bg-purple-900/30 dark:text-purple-400" },
  INVOICE:    { label: "Facture",     color: "bg-blue-100 text-blue-700 dark:bg-blue-900/30 dark:text-blue-400" },
  EXPENSE:    { label: "Dépense",     color: "bg-orange-100 text-orange-700 dark:bg-orange-900/30 dark:text-orange-400" },
  PAYMENT:    { label: "Paiement",    color: "bg-green-100 text-green-700 dark:bg-green-900/30 dark:text-green-400" },
  BANK:       { label: "Banque",      color: "bg-cyan-100 text-cyan-700 dark:bg-cyan-900/30 dark:text-cyan-400" },
  ADJUSTMENT: { label: "Ajustement", color: "bg-yellow-100 text-yellow-700 dark:bg-yellow-900/30 dark:text-yellow-400" },
  CLOSING:    { label: "Clôture",    color: "bg-gray-100 text-gray-700 dark:bg-gray-800 dark:text-gray-400" },
};

// ─── Modal nouvelle écriture ───────────────────────────────────

type NewLine = {
  accountCode: string;
  accountLabel: string;
  debit: string;
  credit: string;
  description: string;
};

const emptyLine = (): NewLine => ({
  accountCode: "",
  accountLabel: "",
  debit: "0",
  credit: "0",
  description: "",
});

function NewEntryModal({
  open,
  onClose,
  onSuccess,
}: {
  open: boolean;
  onClose: () => void;
  onSuccess: () => void;
}) {
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [date, setDate] = useState(new Date().toISOString().split("T")[0]);
  const [description, setDescription] = useState("");
  const [reference, setReference] = useState("");
  const [lines, setLines] = useState<NewLine[]>([emptyLine(), emptyLine()]);

  const totalDebit = lines.reduce((s, l) => s + (parseFloat(l.debit) || 0), 0);
  const totalCredit = lines.reduce((s, l) => s + (parseFloat(l.credit) || 0), 0);
  const isBalanced = Math.abs(totalDebit - totalCredit) < 0.01;

  const updateLine = (i: number, field: keyof NewLine, value: string) => {
    setLines((prev) => prev.map((l, idx) => idx === i ? { ...l, [field]: value } : l));
  };

  const addLine = () => setLines((prev) => [...prev, emptyLine()]);
  const removeLine = (i: number) => {
    if (lines.length <= 2) return;
    setLines((prev) => prev.filter((_, idx) => idx !== i));
  };

  const handleSubmit = async () => {
    if (!description.trim()) { toast.error("La description est requise"); return; }
    if (!isBalanced) { toast.error("L'écriture n'est pas équilibrée (débit ≠ crédit)"); return; }
    if (lines.some((l) => !l.accountCode.trim() || !l.accountLabel.trim())) {
      toast.error("Tous les codes et libellés de compte sont requis");
      return;
    }

    setIsSubmitting(true);
    try {
      const res = await fetch("/api/journal-entries", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          date: new Date(date).toISOString(),
          description,
          reference: reference || undefined,
          type: "MANUAL",
          lines: lines.map((l) => ({
            accountCode: l.accountCode,
            accountLabel: l.accountLabel,
            debit: parseFloat(l.debit) || 0,
            credit: parseFloat(l.credit) || 0,
            description: l.description || undefined,
          })),
        }),
      });
      const json = await res.json();
      if (json.success) {
        toast.success("Écriture créée avec succès");
        onSuccess();
        onClose();
        setDescription("");
        setReference("");
        setLines([emptyLine(), emptyLine()]);
      } else {
        toast.error(json.error ?? "Erreur lors de la création");
      }
    } catch {
      toast.error("Erreur réseau, veuillez réessayer");
    } finally {
      setIsSubmitting(false);
    }
  };

  return (
    <Dialog open={open} onOpenChange={onClose}>
      <DialogContent className="max-w-3xl max-h-[90vh] overflow-y-auto">
        <DialogHeader>
          <DialogTitle>Nouvelle écriture manuelle</DialogTitle>
          <DialogDescription>
            Saisissez une écriture comptable. Le total débit doit égaler le total crédit.
          </DialogDescription>
        </DialogHeader>

        <div className="space-y-4 py-2">
          {/* En-tête écriture */}
          <div className="grid gap-4 sm:grid-cols-3">
            <div className="space-y-1.5">
              <Label htmlFor="je-date">Date</Label>
              <Input
                id="je-date"
                type="date"
                value={date}
                onChange={(e) => setDate(e.target.value)}
              />
            </div>
            <div className="space-y-1.5 sm:col-span-2">
              <Label htmlFor="je-desc">Description <span className="text-destructive">*</span></Label>
              <Input
                id="je-desc"
                placeholder="Libellé de l'écriture"
                value={description}
                onChange={(e) => setDescription(e.target.value)}
              />
            </div>
            <div className="space-y-1.5 sm:col-span-3">
              <Label htmlFor="je-ref">Référence (optionnel)</Label>
              <Input
                id="je-ref"
                placeholder="N° de pièce, facture…"
                value={reference}
                onChange={(e) => setReference(e.target.value)}
              />
            </div>
          </div>

          <Separator />

          {/* Lignes */}
          <div>
            <div className="flex items-center justify-between mb-2">
              <p className="text-sm font-medium">Lignes comptables</p>
              <Button variant="ghost" size="sm" className="gap-1.5 h-7 text-xs" onClick={addLine}>
                <Plus className="h-3 w-3" />
                Ajouter une ligne
              </Button>
            </div>

            <div className="overflow-x-auto rounded-lg border">
              <table className="w-full text-sm">
                <thead className="bg-muted/50">
                  <tr>
                    <th className="text-left px-3 py-2 font-medium text-muted-foreground w-[100px]">N° compte</th>
                    <th className="text-left px-3 py-2 font-medium text-muted-foreground">Libellé compte</th>
                    <th className="text-right px-3 py-2 font-medium text-muted-foreground w-[120px]">Débit</th>
                    <th className="text-right px-3 py-2 font-medium text-muted-foreground w-[120px]">Crédit</th>
                    <th className="w-[32px]" />
                  </tr>
                </thead>
                <tbody>
                  {lines.map((line, i) => (
                    <tr key={i} className="border-t">
                      <td className="px-2 py-1.5">
                        <Input
                          placeholder="411000"
                          value={line.accountCode}
                          onChange={(e) => updateLine(i, "accountCode", e.target.value)}
                          className="h-8 font-mono text-xs"
                        />
                      </td>
                      <td className="px-2 py-1.5">
                        <Input
                          placeholder="Clients"
                          value={line.accountLabel}
                          onChange={(e) => updateLine(i, "accountLabel", e.target.value)}
                          className="h-8 text-xs"
                        />
                      </td>
                      <td className="px-2 py-1.5">
                        <Input
                          type="number"
                          min="0"
                          step="0.01"
                          placeholder="0.00"
                          value={line.debit}
                          onChange={(e) => updateLine(i, "debit", e.target.value)}
                          className="h-8 text-right tabular-nums text-xs"
                        />
                      </td>
                      <td className="px-2 py-1.5">
                        <Input
                          type="number"
                          min="0"
                          step="0.01"
                          placeholder="0.00"
                          value={line.credit}
                          onChange={(e) => updateLine(i, "credit", e.target.value)}
                          className="h-8 text-right tabular-nums text-xs"
                        />
                      </td>
                      <td className="px-1 py-1.5">
                        <Button
                          variant="ghost"
                          size="icon"
                          className="h-8 w-8 text-muted-foreground hover:text-destructive"
                          onClick={() => removeLine(i)}
                          disabled={lines.length <= 2}
                        >
                          <X className="h-3.5 w-3.5" />
                        </Button>
                      </td>
                    </tr>
                  ))}
                </tbody>
                <tfoot className="border-t bg-muted/30">
                  <tr>
                    <td colSpan={2} className="px-3 py-2 text-xs font-semibold text-muted-foreground">
                      Totaux
                    </td>
                    <td className="px-3 py-2 text-right font-bold tabular-nums text-sm">
                      {formatCurrency(totalDebit)}
                    </td>
                    <td className={cn(
                      "px-3 py-2 text-right font-bold tabular-nums text-sm",
                      !isBalanced && totalCredit > 0 && "text-destructive"
                    )}>
                      {formatCurrency(totalCredit)}
                    </td>
                    <td />
                  </tr>
                </tfoot>
              </table>
            </div>

            {/* Indicateur équilibre */}
            {totalDebit > 0 && !isBalanced && (
              <div className="flex items-center gap-2 mt-2 text-xs text-destructive">
                <AlertCircle className="h-3.5 w-3.5" />
                <span>
                  Écart de {formatCurrency(Math.abs(totalDebit - totalCredit))} —
                  l&apos;écriture doit être équilibrée
                </span>
              </div>
            )}
            {isBalanced && totalDebit > 0 && (
              <div className="flex items-center gap-2 mt-2 text-xs text-emerald-600">
                <span className="h-3.5 w-3.5 rounded-full bg-emerald-500 flex items-center justify-center">
                  <span className="text-white text-[8px]">✓</span>
                </span>
                Écriture équilibrée
              </div>
            )}
          </div>
        </div>

        <DialogFooter className="gap-2">
          <Button variant="outline" onClick={onClose} disabled={isSubmitting}>Annuler</Button>
          <Button onClick={handleSubmit} disabled={isSubmitting || !isBalanced || !description.trim()}>
            {isSubmitting ? "Enregistrement…" : "Enregistrer l'écriture"}
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}

// ─── Composant principal ───────────────────────────────────────

export default function JournalPage() {
  const [entries, setEntries] = useState<JournalEntry[]>([]);
  const [pagination, setPagination] = useState<Pagination>({
    page: 1, limit: 20, total: 0, totalPages: 1,
  });
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [showNewEntry, setShowNewEntry] = useState(false);
  const [search, setSearch] = useState("");

  // Filtres
  const [filterType, setFilterType] = useState<string>("all");
  const [filterFrom, setFilterFrom] = useState("");
  const [filterTo, setFilterTo] = useState("");
  const [page, setPage] = useState(1);

  // Détail écriture
  const [expandedId, setExpandedId] = useState<string | null>(null);

  const fetchEntries = useCallback(async () => {
    setIsLoading(true);
    setError(null);
    try {
      const params = new URLSearchParams({ page: String(page), limit: "20" });
      if (filterType !== "all") params.set("type", filterType);
      if (filterFrom) params.set("from", filterFrom);
      if (filterTo) params.set("to", filterTo);

      const res = await fetch(`/api/journal-entries?${params}`);
      const json = await res.json();
      if (json.success) {
        setEntries(json.data);
        setPagination(json.pagination);
      } else {
        throw new Error(json.error);
      }
    } catch (err) {
      setEntries([]);
      setError(err instanceof Error ? err.message : "Impossible de charger les écritures");
    } finally {
      setIsLoading(false);
    }
  }, [page, filterType, filterFrom, filterTo, search]);

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

  const resetFilters = () => {
    setFilterType("all");
    setFilterFrom("");
    setFilterTo("");
    setSearch("");
    setPage(1);
  };

  const hasFilters = filterType !== "all" || filterFrom || filterTo || search;

  return (
    <div className="space-y-6">
      {/* En-tête */}
      <div className="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
        <div>
          <h1 className="text-2xl font-bold tracking-tight flex items-center gap-2">
            <BookOpen className="h-6 w-6 text-muted-foreground" />
            Journal comptable
          </h1>
          <p className="text-sm text-muted-foreground mt-0.5">
            {pagination.total} écriture{pagination.total !== 1 ? "s" : ""} au total
          </p>
        </div>
        <div className="flex items-center gap-2">
          <Button
            variant="outline"
            size="sm"
            onClick={fetchEntries}
            disabled={isLoading}
            className="gap-1.5"
          >
            <RefreshCw className={cn("h-3.5 w-3.5", isLoading && "animate-spin")} />
            Actualiser
          </Button>
          <Button size="sm" className="gap-1.5" onClick={() => setShowNewEntry(true)}>
            <Plus className="h-4 w-4" />
            Nouvelle écriture manuelle
          </Button>
        </div>
      </div>

      {/* Filtres */}
      <Card className="bg-muted/20 border-dashed">
        <CardContent className="py-3">
          <div className="flex flex-wrap items-center gap-3">
            {/* Recherche */}
            <div className="relative flex-1 min-w-[200px]">
              <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-muted-foreground" />
              <Input
                placeholder="Rechercher par n° ou description…"
                value={search}
                onChange={(e) => { setSearch(e.target.value); setPage(1); }}
                className="pl-9 h-8 bg-background text-sm"
              />
            </div>

            {/* Type */}
            <Select value={filterType} onValueChange={(v) => { setFilterType(v); setPage(1); }}>
              <SelectTrigger className="w-[160px] h-8 bg-background text-sm">
                <Filter className="h-3.5 w-3.5 mr-1.5 text-muted-foreground" />
                <SelectValue placeholder="Type" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="all">Tous les types</SelectItem>
                {Object.entries(ENTRY_TYPE_CONFIG).map(([key, cfg]) => (
                  <SelectItem key={key} value={key}>{cfg.label}</SelectItem>
                ))}
              </SelectContent>
            </Select>

            {/* Date de/à */}
            <div className="flex items-center gap-1.5">
              <Label className="text-xs text-muted-foreground whitespace-nowrap">Du</Label>
              <Input
                type="date"
                value={filterFrom}
                onChange={(e) => { setFilterFrom(e.target.value); setPage(1); }}
                className="w-[140px] h-8 bg-background text-sm"
              />
            </div>
            <div className="flex items-center gap-1.5">
              <Label className="text-xs text-muted-foreground whitespace-nowrap">Au</Label>
              <Input
                type="date"
                value={filterTo}
                onChange={(e) => { setFilterTo(e.target.value); setPage(1); }}
                className="w-[140px] h-8 bg-background text-sm"
              />
            </div>

            {hasFilters && (
              <Button variant="ghost" size="sm" onClick={resetFilters} className="gap-1.5 text-muted-foreground h-8">
                <X className="h-3.5 w-3.5" />
                Effacer
              </Button>
            )}
          </div>
        </CardContent>
      </Card>

      {/* Tableau */}
      <Card>
        <CardContent className="p-0">
          {isLoading ? (
            <div className="flex items-center justify-center py-16">
              <RefreshCw className="h-6 w-6 animate-spin text-muted-foreground" />
            </div>
          ) : error ? (
            <div className="flex flex-col items-center justify-center py-16 gap-3">
              <AlertCircle className="h-8 w-8 text-destructive" />
              <p className="text-sm font-medium">Erreur de chargement</p>
              <p className="text-xs text-muted-foreground">{error}</p>
              <Button size="sm" variant="outline" onClick={fetchEntries} className="gap-1.5">
                <RefreshCw className="h-3.5 w-3.5" />
                Réessayer
              </Button>
            </div>
          ) : entries.length === 0 ? (
            <div className="flex flex-col items-center justify-center py-16 gap-3">
              <BookOpen className="h-8 w-8 text-muted-foreground/40" />
              <p className="text-sm text-muted-foreground">Aucune écriture trouvée</p>
              <Button size="sm" onClick={() => setShowNewEntry(true)} className="gap-1.5">
                <Plus className="h-3.5 w-3.5" />
                Créer une écriture
              </Button>
            </div>
          ) : (
            <div className="overflow-x-auto">
              <Table>
                <TableHeader>
                  <TableRow className="bg-muted/30 hover:bg-muted/30">
                    <TableHead className="font-semibold text-foreground w-8" />
                    <TableHead className="font-semibold text-foreground">Date</TableHead>
                    <TableHead className="font-semibold text-foreground">N° écriture</TableHead>
                    <TableHead className="font-semibold text-foreground">Type</TableHead>
                    <TableHead className="font-semibold text-foreground">Description</TableHead>
                    <TableHead className="font-semibold text-foreground text-right">Débit</TableHead>
                    <TableHead className="font-semibold text-foreground text-right">Crédit</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {entries.map((entry) => {
                    const totalDebit = entry.lines.reduce((s, l) => s + l.debit, 0);
                    const totalCredit = entry.lines.reduce((s, l) => s + l.credit, 0);
                    const cfg = ENTRY_TYPE_CONFIG[entry.type] ?? ENTRY_TYPE_CONFIG.MANUAL;
                    const isExpanded = expandedId === entry.id;

                    return (
                      <>
                        <TableRow
                          key={entry.id}
                          className={cn(
                            "cursor-pointer transition-colors",
                            isExpanded && "bg-muted/30"
                          )}
                          onClick={() => setExpandedId(isExpanded ? null : entry.id)}
                        >
                          <TableCell className="w-8 text-center text-muted-foreground">
                            <ArrowUpDown className={cn(
                              "h-3.5 w-3.5 transition-transform",
                              isExpanded && "rotate-180"
                            )} />
                          </TableCell>
                          <TableCell className="text-sm tabular-nums text-muted-foreground">
                            {formatDate(entry.date)}
                          </TableCell>
                          <TableCell>
                            <span className="font-mono text-xs font-semibold">
                              {entry.number}
                            </span>
                            {entry.isManual && (
                              <Badge variant="outline" className="ml-2 text-[10px] py-0 h-4">M</Badge>
                            )}
                          </TableCell>
                          <TableCell>
                            <span className={cn(
                              "inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium",
                              cfg.color
                            )}>
                              {cfg.label}
                            </span>
                          </TableCell>
                          <TableCell className="max-w-[280px]">
                            <p className="truncate text-sm">{entry.description}</p>
                            {entry.reference && (
                              <p className="text-xs text-muted-foreground font-mono">{entry.reference}</p>
                            )}
                          </TableCell>
                          <TableCell className="text-right tabular-nums font-semibold text-sm">
                            {formatCurrency(totalDebit)}
                          </TableCell>
                          <TableCell className="text-right tabular-nums font-semibold text-sm">
                            {formatCurrency(totalCredit)}
                          </TableCell>
                        </TableRow>

                        {/* Lignes détail */}
                        {isExpanded && (
                          <TableRow key={`${entry.id}-detail`} className="bg-muted/10 hover:bg-muted/10">
                            <TableCell colSpan={7} className="p-0">
                              <div className="px-10 py-3">
                                <p className="text-xs font-semibold text-muted-foreground mb-2 uppercase tracking-wide">
                                  Détail des lignes
                                </p>
                                <table className="w-full text-xs">
                                  <thead>
                                    <tr className="text-muted-foreground border-b">
                                      <th className="text-left pb-1.5 font-medium w-[100px]">N° compte</th>
                                      <th className="text-left pb-1.5 font-medium">Libellé</th>
                                      <th className="text-right pb-1.5 font-medium w-[120px]">Débit</th>
                                      <th className="text-right pb-1.5 font-medium w-[120px]">Crédit</th>
                                    </tr>
                                  </thead>
                                  <tbody>
                                    {entry.lines.map((line) => (
                                      <tr key={line.id} className="border-b last:border-0">
                                        <td className="py-1.5 font-mono">{line.accountCode}</td>
                                        <td className="py-1.5 text-muted-foreground">{line.accountLabel}</td>
                                        <td className="py-1.5 text-right tabular-nums">
                                          {line.debit > 0 ? formatCurrency(line.debit) : "—"}
                                        </td>
                                        <td className="py-1.5 text-right tabular-nums">
                                          {line.credit > 0 ? formatCurrency(line.credit) : "—"}
                                        </td>
                                      </tr>
                                    ))}
                                  </tbody>
                                </table>
                              </div>
                            </TableCell>
                          </TableRow>
                        )}
                      </>
                    );
                  })}
                </TableBody>
              </Table>
            </div>
          )}
        </CardContent>
      </Card>

      {/* Pagination */}
      {pagination.totalPages > 1 && (
        <div className="flex items-center justify-between">
          <p className="text-sm text-muted-foreground">
            Page {pagination.page} sur {pagination.totalPages} ·{" "}
            {pagination.total} écriture{pagination.total !== 1 ? "s" : ""}
          </p>
          <div className="flex items-center gap-2">
            <Button
              variant="outline"
              size="sm"
              onClick={() => setPage((p) => Math.max(1, p - 1))}
              disabled={page === 1}
            >
              <ChevronLeft className="h-4 w-4" />
            </Button>
            <Button
              variant="outline"
              size="sm"
              onClick={() => setPage((p) => Math.min(pagination.totalPages, p + 1))}
              disabled={page === pagination.totalPages}
            >
              <ChevronRight className="h-4 w-4" />
            </Button>
          </div>
        </div>
      )}

      {/* Modal nouvelle écriture */}
      <NewEntryModal
        open={showNewEntry}
        onClose={() => setShowNewEntry(false)}
        onSuccess={fetchEntries}
      />
    </div>
  );
}
