"use client";

import { useEffect, useRef, useState, useCallback } from "react";
import { Button } from "@/components/ui/button";
import { Card, CardContent } from "@/components/ui/card";
import { Checkbox } from "@/components/ui/checkbox";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { CategoryCombobox } from "@/components/ui/category-combobox";
import {
  CheckCircle2,
  Circle,
  MoreVertical,
  ArrowUpDown,
  Wand2,
} from "lucide-react";
import { DropdownMenuSeparator } from "@/components/ui/dropdown-menu";
import { cn } from "@/lib/utils";
import type { Transaction, Account, Category } from "@/lib/types";

type SortField = "date" | "amount" | "description";
type SortOrder = "asc" | "desc";

interface TransactionTableProps {
  transactions: Transaction[];
  accounts: Account[];
  categories: Category[];
  selectedTransactions: Set<string>;
  sortField: SortField;
  sortOrder: SortOrder;
  onSortChange: (field: SortField) => void;
  onToggleSelectAll: () => void;
  onToggleSelectTransaction: (id: string) => void;
  onToggleReconciled: (id: string) => void;
  onMarkReconciled: (id: string) => void;
  onSetCategory: (transactionId: string, categoryId: string | null) => void;
  onCreateRule: (transaction: Transaction) => void;
  formatCurrency: (amount: number) => string;
  formatDate: (dateStr: string) => string;
}

export function TransactionTable({
  transactions,
  accounts,
  categories,
  selectedTransactions,
  sortField,
  sortOrder,
  onSortChange,
  onToggleSelectAll,
  onToggleSelectTransaction,
  onToggleReconciled,
  onMarkReconciled,
  onSetCategory,
  onCreateRule,
  formatCurrency,
  formatDate,
}: TransactionTableProps) {
  const [focusedIndex, setFocusedIndex] = useState<number | null>(null);
  const rowRefs = useRef<(HTMLTableRowElement | null)[]>([]);

  const handleRowClick = useCallback(
    (index: number, transactionId: string) => {
      setFocusedIndex(index);
      onMarkReconciled(transactionId);
    },
    [onMarkReconciled]
  );

  const handleKeyDown = useCallback(
    (e: KeyboardEvent) => {
      if (focusedIndex === null || transactions.length === 0) return;

      if (e.key === "ArrowDown") {
        e.preventDefault();
        const newIndex = Math.min(focusedIndex + 1, transactions.length - 1);
        if (newIndex !== focusedIndex) {
          setFocusedIndex(newIndex);
          onMarkReconciled(transactions[newIndex].id);
          rowRefs.current[newIndex]?.scrollIntoView({
            behavior: "smooth",
            block: "nearest",
          });
        }
      } else if (e.key === "ArrowUp") {
        e.preventDefault();
        const newIndex = Math.max(focusedIndex - 1, 0);
        if (newIndex !== focusedIndex) {
          setFocusedIndex(newIndex);
          onMarkReconciled(transactions[newIndex].id);
          rowRefs.current[newIndex]?.scrollIntoView({
            behavior: "smooth",
            block: "nearest",
          });
        }
      }
    },
    [focusedIndex, transactions, onMarkReconciled]
  );

  useEffect(() => {
    document.addEventListener("keydown", handleKeyDown);
    return () => document.removeEventListener("keydown", handleKeyDown);
  }, [handleKeyDown]);

  // Reset focused index when transactions change
  useEffect(() => {
    setFocusedIndex(null);
  }, [transactions.length]);
  const getAccount = (accountId: string) => {
    return accounts.find((a) => a.id === accountId);
  };

  return (
    <Card>
      <CardContent className="p-0">
        {transactions.length === 0 ? (
          <div className="flex flex-col items-center justify-center py-12">
            <p className="text-muted-foreground">Aucune transaction trouvée</p>
          </div>
        ) : (
          <div className="overflow-x-auto">
            <table className="w-full">
              <thead>
                <tr className="border-b border-border">
                  <th className="p-3 text-left">
                    <Checkbox
                      checked={
                        selectedTransactions.size === transactions.length &&
                        transactions.length > 0
                      }
                      onCheckedChange={onToggleSelectAll}
                    />
                  </th>
                  <th className="p-3 text-left">
                    <button
                      onClick={() => onSortChange("date")}
                      className="flex items-center gap-1 text-sm font-medium text-muted-foreground hover:text-foreground"
                    >
                      Date
                      <ArrowUpDown className="w-3 h-3" />
                    </button>
                  </th>
                  <th className="p-3 text-left">
                    <button
                      onClick={() => onSortChange("description")}
                      className="flex items-center gap-1 text-sm font-medium text-muted-foreground hover:text-foreground"
                    >
                      Description
                      <ArrowUpDown className="w-3 h-3" />
                    </button>
                  </th>
                  <th className="p-3 text-left text-sm font-medium text-muted-foreground">
                    Compte
                  </th>
                  <th className="p-3 text-left text-sm font-medium text-muted-foreground">
                    Catégorie
                  </th>
                  <th className="p-3 text-right">
                    <button
                      onClick={() => onSortChange("amount")}
                      className="flex items-center gap-1 text-sm font-medium text-muted-foreground hover:text-foreground ml-auto"
                    >
                      Montant
                      <ArrowUpDown className="w-3 h-3" />
                    </button>
                  </th>
                  <th className="p-3 text-center text-sm font-medium text-muted-foreground">
                    Pointé
                  </th>
                  <th className="p-3"></th>
                </tr>
              </thead>
              <tbody>
                {transactions.map((transaction, index) => {
                  const account = getAccount(transaction.accountId);
                  const isFocused = focusedIndex === index;

                  return (
                    <tr
                      key={transaction.id}
                      ref={(el) => {
                        rowRefs.current[index] = el;
                      }}
                      onClick={() => handleRowClick(index, transaction.id)}
                      className={cn(
                        "border-b border-border last:border-0 hover:bg-muted/50 cursor-pointer",
                        transaction.isReconciled && "bg-emerald-500/5",
                        isFocused && "bg-primary/10 ring-1 ring-primary/30"
                      )}
                    >
                      <td className="p-3">
                        <Checkbox
                          checked={selectedTransactions.has(transaction.id)}
                          onCheckedChange={() =>
                            onToggleSelectTransaction(transaction.id)
                          }
                        />
                      </td>
                      <td className="p-3 text-sm text-muted-foreground whitespace-nowrap">
                        {formatDate(transaction.date)}
                      </td>
                      <td className="p-3">
                        <p className="font-medium text-sm">
                          {transaction.description}
                        </p>
                        {transaction.memo && (
                          <p className="text-xs text-muted-foreground truncate max-w-[300px]">
                            {transaction.memo}
                          </p>
                        )}
                      </td>
                      <td className="p-3 text-sm text-muted-foreground">
                        {account?.name || "-"}
                      </td>
                      <td className="p-3" onClick={(e) => e.stopPropagation()}>
                        <CategoryCombobox
                          categories={categories}
                          value={transaction.categoryId}
                          onChange={(categoryId) =>
                            onSetCategory(transaction.id, categoryId)
                          }
                          showBadge
                          align="start"
                        />
                      </td>
                      <td
                        className={cn(
                          "p-3 text-right font-semibold tabular-nums",
                          transaction.amount >= 0
                            ? "text-emerald-600"
                            : "text-red-600"
                        )}
                      >
                        {transaction.amount >= 0 ? "+" : ""}
                        {formatCurrency(transaction.amount)}
                      </td>
                      <td className="p-3 text-center">
                        <button
                          onClick={() => onToggleReconciled(transaction.id)}
                          className="p-1 hover:bg-muted rounded"
                        >
                          {transaction.isReconciled ? (
                            <CheckCircle2 className="w-5 h-5 text-emerald-600" />
                          ) : (
                            <Circle className="w-5 h-5 text-muted-foreground" />
                          )}
                        </button>
                      </td>
                      <td className="p-3">
                        <DropdownMenu>
                          <DropdownMenuTrigger asChild>
                            <Button
                              variant="ghost"
                              size="icon"
                              className="h-8 w-8"
                            >
                              <MoreVertical className="w-4 h-4" />
                            </Button>
                          </DropdownMenuTrigger>
                          <DropdownMenuContent align="end">
                            <DropdownMenuItem
                              onClick={() => onToggleReconciled(transaction.id)}
                            >
                              {transaction.isReconciled
                                ? "Dépointer"
                                : "Pointer"}
                            </DropdownMenuItem>
                            <DropdownMenuSeparator />
                            <DropdownMenuItem
                              onClick={() => onCreateRule(transaction)}
                            >
                              <Wand2 className="w-4 h-4 mr-2" />
                              Créer une règle
                            </DropdownMenuItem>
                          </DropdownMenuContent>
                        </DropdownMenu>
                      </td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </div>
        )}
      </CardContent>
    </Card>
  );
}

