"use client";

import { useState, useCallback, useTransition } from "react";
import { useRouter } from "next/navigation";
import { format } from "date-fns";
import { fr } from "date-fns/locale";
import {
  Plus, Search, Filter, MoreHorizontal, ChevronLeft, ChevronRight,
  CheckCircle2, XCircle, Trash2, Eye, Euro, Receipt,
} from "lucide-react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Badge } from "@/components/ui/badge";
import { Card, CardContent, CardHeader, CardTitle } 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 {
  DropdownMenu, DropdownMenuContent, DropdownMenuItem,
  DropdownMenuSeparator, DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import {
  AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent,
  AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle,
} from "@/components/ui/alert-dialog";
import { toast } from "sonner";
import { cn, formatCurrency, EXPENSE_STATUS_CONFIG } from "@/lib/utils";
import { useDebounce } from "@/hooks/use-debounce";

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

type Category = {
  id: string;
  name: string;
  color: string;
  icon?: string | null;
};

type Expense = {
  id: string;
  title: string;
  description?: string | null;
  amount: number;
  taxAmount: number;
  taxRate: number;
  currency: string;
  status: "PENDING" | "APPROVED" | "REJECTED" | "REIMBURSED";
  date: Date | string;
  paymentMethod?: string | null;
  reference?: string | null;
  category?: Category | null;
  supplier?: { id: string; name: string } | null;
};

type Props = {
  initialExpenses: Expense[];
  initialTotal: number;
  categories: Category[];
  monthlyTotal: number;
  monthlyCount: number;
};

// ─── Label méthode de paiement ────────────────────────────────
const PAYMENT_METHOD_LABELS: Record<string, string> = {
  BANK_TRANSFER: "Virement",
  CREDIT_CARD: "Carte bancaire",
  CASH: "Espèces",
  CHECK: "Chèque",
  PAYPAL: "PayPal",
  STRIPE: "Stripe",
  OTHER: "Autre",
};

// ─── Composant principal ──────────────────────────────────────
export function ExpenseListClient({
  initialExpenses,
  initialTotal,
  categories,
  monthlyTotal,
  monthlyCount,
}: Props) {
  const router = useRouter();
  const [isPending, startTransition] = useTransition();

  // État filtres
  const [search, setSearch] = useState("");
  const [categoryId, setCategoryId] = useState("all");
  const [status, setStatus] = useState("all");
  const [from, setFrom] = useState("");
  const [to, setTo] = useState("");
  const [page, setPage] = useState(1);

  // Données
  const [expenses, setExpenses] = useState<Expense[]>(initialExpenses);
  const [total, setTotal] = useState(initialTotal);

  // Suppression
  const [deleteId, setDeleteId] = useState<string | null>(null);
  const [isDeleting, setIsDeleting] = useState(false);

  const debouncedSearch = useDebounce(search, 400);
  const limit = 20;
  const totalPages = Math.ceil(total / limit);

  // ─── Fetch filtré ─────────────────────────────────────────
  const fetchExpenses = useCallback(
    async (opts: {
      page?: number;
      search?: string;
      categoryId?: string;
      status?: string;
      from?: string;
      to?: string;
    }) => {
      const params = new URLSearchParams();
      params.set("page", String(opts.page ?? 1));
      params.set("limit", String(limit));
      if (opts.search) params.set("search", opts.search);
      if (opts.categoryId && opts.categoryId !== "all") params.set("categoryId", opts.categoryId);
      if (opts.status && opts.status !== "all") params.set("status", opts.status);
      if (opts.from) params.set("from", opts.from);
      if (opts.to) params.set("to", opts.to);

      const res = await fetch(`/api/expenses?${params.toString()}`);
      const json = await res.json();
      if (json.success) {
        setExpenses(json.data);
        setTotal(json.pagination.total);
      }
    },
    []
  );

  // Déclencher fetch quand filtres changent
  const handleFilter = useCallback(
    (overrides: Partial<{
      page: number;
      search: string;
      categoryId: string;
      status: string;
      from: string;
      to: string;
    }>) => {
      startTransition(() => {
        fetchExpenses({
          page,
          search: debouncedSearch,
          categoryId,
          status,
          from,
          to,
          ...overrides,
        });
      });
    },
    [page, debouncedSearch, categoryId, status, from, to, fetchExpenses]
  );

  // Watcher search debounced
  const handleSearchChange = (value: string) => {
    setSearch(value);
    setPage(1);
    startTransition(() => {
      fetchExpenses({ page: 1, search: value, categoryId, status, from, to });
    });
  };

  const handleCategoryChange = (value: string) => {
    setCategoryId(value);
    setPage(1);
    handleFilter({ categoryId: value, page: 1 });
  };

  const handleStatusChange = (value: string) => {
    setStatus(value);
    setPage(1);
    handleFilter({ status: value, page: 1 });
  };

  const handleFromChange = (value: string) => {
    setFrom(value);
    setPage(1);
    handleFilter({ from: value, page: 1 });
  };

  const handleToChange = (value: string) => {
    setTo(value);
    setPage(1);
    handleFilter({ to: value, page: 1 });
  };

  const handlePageChange = (newPage: number) => {
    setPage(newPage);
    handleFilter({ page: newPage });
  };

  // ─── Approbation / Rejet ──────────────────────────────────
  const handleApprove = async (id: string, action: "approve" | "reject") => {
    const res = await fetch(`/api/expenses/${id}/approve`, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ action }),
    });
    const json = await res.json();
    if (json.success) {
      toast.success(json.message);
      setExpenses((prev) =>
        prev.map((e) => (e.id === id ? { ...e, status: json.data.status } : e))
      );
    } else {
      toast.error(json.error ?? "Erreur lors de l'opération");
    }
  };

  // ─── Suppression ──────────────────────────────────────────
  const handleDelete = async () => {
    if (!deleteId) return;
    setIsDeleting(true);
    try {
      const res = await fetch(`/api/expenses/${deleteId}`, { method: "DELETE" });
      const json = await res.json();
      if (json.success) {
        toast.success("Dépense supprimée");
        setExpenses((prev) => prev.filter((e) => e.id !== deleteId));
        setTotal((t) => t - 1);
      } else {
        toast.error(json.error ?? "Erreur lors de la suppression");
      }
    } finally {
      setIsDeleting(false);
      setDeleteId(null);
    }
  };

  // ─── Réinitialiser filtres ────────────────────────────────
  const resetFilters = () => {
    setSearch("");
    setCategoryId("all");
    setStatus("all");
    setFrom("");
    setTo("");
    setPage(1);
    startTransition(() => {
      fetchExpenses({ page: 1 });
    });
  };

  const hasActiveFilters =
    search || categoryId !== "all" || status !== "all" || from || to;

  return (
    <div className="space-y-6 p-6">
      {/* En-tête */}
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold tracking-tight">Dépenses</h1>
          <p className="text-sm text-muted-foreground">
            Gérez et suivez toutes vos dépenses professionnelles
          </p>
        </div>
        <Button onClick={() => router.push("/depenses/nouvelle")}>
          <Plus className="h-4 w-4 mr-2" />
          Ajouter une dépense
        </Button>
      </div>

      {/* Résumé du mois */}
      <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
        <Card>
          <CardHeader className="flex flex-row items-center justify-between pb-2 space-y-0">
            <CardTitle className="text-sm font-medium text-muted-foreground">
              Total ce mois
            </CardTitle>
            <div className="h-8 w-8 rounded-lg flex items-center justify-center bg-red-100 text-red-600 dark:bg-red-900/30 dark:text-red-400">
              <Euro className="h-4 w-4" />
            </div>
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold tracking-tight">
              {formatCurrency(monthlyTotal)}
            </div>
            <p className="text-xs text-muted-foreground mt-1">
              {monthlyCount} dépense{monthlyCount !== 1 ? "s" : ""} ce mois
            </p>
          </CardContent>
        </Card>
        <Card>
          <CardHeader className="flex flex-row items-center justify-between pb-2 space-y-0">
            <CardTitle className="text-sm font-medium text-muted-foreground">
              Total dépenses
            </CardTitle>
            <div className="h-8 w-8 rounded-lg flex items-center justify-center bg-orange-100 text-orange-600 dark:bg-orange-900/30 dark:text-orange-400">
              <Receipt className="h-4 w-4" />
            </div>
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold tracking-tight tabular-nums">{total}</div>
            <p className="text-xs text-muted-foreground mt-1">dépenses enregistrées</p>
          </CardContent>
        </Card>
      </div>

      {/* Filtres */}
      <Card>
        <CardContent className="pt-4">
          <div className="flex flex-wrap gap-3 items-end">
            {/* Recherche */}
            <div className="relative flex-1 min-w-[200px]">
              <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground pointer-events-none" />
              <Input
                placeholder="Rechercher une dépense..."
                value={search}
                onChange={(e) => handleSearchChange(e.target.value)}
                className="pl-9"
              />
            </div>

            {/* Catégorie */}
            <Select value={categoryId} onValueChange={handleCategoryChange}>
              <SelectTrigger className="w-[180px]">
                <SelectValue placeholder="Catégorie" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="all">Toutes les catégories</SelectItem>
                {categories.map((cat) => (
                  <SelectItem key={cat.id} value={cat.id}>
                    <span className="flex items-center gap-2">
                      <span
                        className="h-2.5 w-2.5 rounded-full shrink-0"
                        style={{ backgroundColor: cat.color }}
                      />
                      {cat.name}
                    </span>
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>

            {/* Statut */}
            <Select value={status} onValueChange={handleStatusChange}>
              <SelectTrigger className="w-[160px]">
                <SelectValue placeholder="Statut" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="all">Tous les statuts</SelectItem>
                <SelectItem value="PENDING">En attente</SelectItem>
                <SelectItem value="APPROVED">Approuvée</SelectItem>
                <SelectItem value="REJECTED">Refusée</SelectItem>
                <SelectItem value="REIMBURSED">Remboursée</SelectItem>
              </SelectContent>
            </Select>

            {/* Plage de dates */}
            <div className="flex items-center gap-2">
              <Input
                type="date"
                value={from}
                onChange={(e) => handleFromChange(e.target.value)}
                className="w-[150px] text-sm"
                placeholder="Du"
              />
              <span className="text-muted-foreground text-sm">—</span>
              <Input
                type="date"
                value={to}
                onChange={(e) => handleToChange(e.target.value)}
                className="w-[150px] text-sm"
                placeholder="Au"
              />
            </div>

            {/* Réinitialiser */}
            {hasActiveFilters && (
              <Button variant="ghost" size="sm" onClick={resetFilters}>
                Réinitialiser
              </Button>
            )}
          </div>
        </CardContent>
      </Card>

      {/* Tableau */}
      <Card>
        <CardContent className="p-0">
          <div className="overflow-x-auto">
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead className="w-[120px]">Date</TableHead>
                  <TableHead>Titre</TableHead>
                  <TableHead>Catégorie</TableHead>
                  <TableHead className="text-right">Montant HT</TableHead>
                  <TableHead className="text-right">TVA</TableHead>
                  <TableHead className="text-center">Statut</TableHead>
                  <TableHead className="w-[60px]" />
                </TableRow>
              </TableHeader>
              <TableBody>
                {isPending ? (
                  Array.from({ length: 5 }).map((_, i) => (
                    <TableRow key={i}>
                      {Array.from({ length: 7 }).map((_, j) => (
                        <TableCell key={j}>
                          <div className="h-4 bg-muted animate-pulse rounded" />
                        </TableCell>
                      ))}
                    </TableRow>
                  ))
                ) : expenses.length === 0 ? (
                  <TableRow>
                    <TableCell colSpan={7} className="text-center py-12 text-muted-foreground">
                      <Receipt className="h-10 w-10 mx-auto mb-3 opacity-30" />
                      <p className="font-medium">Aucune dépense trouvée</p>
                      <p className="text-sm mt-1">
                        {hasActiveFilters
                          ? "Essayez de modifier vos filtres"
                          : "Commencez par ajouter une dépense"}
                      </p>
                    </TableCell>
                  </TableRow>
                ) : (
                  expenses.map((expense) => {
                    const statusCfg =
                      EXPENSE_STATUS_CONFIG[expense.status as keyof typeof EXPENSE_STATUS_CONFIG];
                    return (
                      <TableRow key={expense.id} className="hover:bg-muted/30">
                        <TableCell className="text-sm text-muted-foreground">
                          {format(new Date(expense.date), "dd/MM/yyyy", { locale: fr })}
                        </TableCell>
                        <TableCell>
                          <div>
                            <p className="font-medium text-sm">{expense.title}</p>
                            {expense.supplier && (
                              <p className="text-xs text-muted-foreground">
                                {expense.supplier.name}
                              </p>
                            )}
                          </div>
                        </TableCell>
                        <TableCell>
                          {expense.category ? (
                            <span className="inline-flex items-center gap-1.5 text-xs font-medium">
                              <span
                                className="h-2.5 w-2.5 rounded-full shrink-0"
                                style={{ backgroundColor: expense.category.color }}
                              />
                              {expense.category.name}
                            </span>
                          ) : (
                            <span className="text-xs text-muted-foreground italic">
                              Non catégorisée
                            </span>
                          )}
                        </TableCell>
                        <TableCell className="text-right font-semibold tabular-nums text-sm">
                          {formatCurrency(expense.amount, expense.currency)}
                        </TableCell>
                        <TableCell className="text-right text-sm tabular-nums text-muted-foreground">
                          {formatCurrency(expense.taxAmount, expense.currency)}
                        </TableCell>
                        <TableCell className="text-center">
                          <span
                            className={cn(
                              "inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium",
                              statusCfg?.color
                            )}
                          >
                            {statusCfg?.label ?? expense.status}
                          </span>
                        </TableCell>
                        <TableCell>
                          <DropdownMenu>
                            <DropdownMenuTrigger asChild>
                              <Button variant="ghost" size="icon" className="h-7 w-7">
                                <MoreHorizontal className="h-4 w-4" />
                                <span className="sr-only">Actions</span>
                              </Button>
                            </DropdownMenuTrigger>
                            <DropdownMenuContent align="end">
                              <DropdownMenuItem
                                onClick={() => router.push(`/depenses/${expense.id}`)}
                              >
                                <Eye className="h-4 w-4 mr-2" />
                                Voir le détail
                              </DropdownMenuItem>
                              {expense.status === "PENDING" && (
                                <>
                                  <DropdownMenuSeparator />
                                  <DropdownMenuItem
                                    onClick={() => handleApprove(expense.id, "approve")}
                                    className="text-green-600"
                                  >
                                    <CheckCircle2 className="h-4 w-4 mr-2" />
                                    Approuver
                                  </DropdownMenuItem>
                                  <DropdownMenuItem
                                    onClick={() => handleApprove(expense.id, "reject")}
                                    className="text-red-600"
                                  >
                                    <XCircle className="h-4 w-4 mr-2" />
                                    Rejeter
                                  </DropdownMenuItem>
                                </>
                              )}
                              <DropdownMenuSeparator />
                              <DropdownMenuItem
                                onClick={() => setDeleteId(expense.id)}
                                className="text-destructive"
                              >
                                <Trash2 className="h-4 w-4 mr-2" />
                                Supprimer
                              </DropdownMenuItem>
                            </DropdownMenuContent>
                          </DropdownMenu>
                        </TableCell>
                      </TableRow>
                    );
                  })
                )}
              </TableBody>
            </Table>
          </div>

          {/* Pagination */}
          {totalPages > 1 && (
            <div className="flex items-center justify-between px-4 py-3 border-t">
              <p className="text-sm text-muted-foreground">
                {total} dépense{total !== 1 ? "s" : ""} au total
              </p>
              <div className="flex items-center gap-2">
                <Button
                  variant="outline"
                  size="icon"
                  className="h-8 w-8"
                  onClick={() => handlePageChange(page - 1)}
                  disabled={page <= 1 || isPending}
                >
                  <ChevronLeft className="h-4 w-4" />
                </Button>
                <span className="text-sm font-medium">
                  {page} / {totalPages}
                </span>
                <Button
                  variant="outline"
                  size="icon"
                  className="h-8 w-8"
                  onClick={() => handlePageChange(page + 1)}
                  disabled={page >= totalPages || isPending}
                >
                  <ChevronRight className="h-4 w-4" />
                </Button>
              </div>
            </div>
          )}
        </CardContent>
      </Card>

      {/* Confirmation suppression */}
      <AlertDialog open={!!deleteId} onOpenChange={(open) => !open && setDeleteId(null)}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>Supprimer la dépense ?</AlertDialogTitle>
            <AlertDialogDescription>
              Cette action est irréversible. La dépense sera définitivement supprimée.
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel disabled={isDeleting}>Annuler</AlertDialogCancel>
            <AlertDialogAction
              onClick={handleDelete}
              disabled={isDeleting}
              className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
            >
              {isDeleting ? "Suppression..." : "Supprimer"}
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </div>
  );
}
