"use client";

import { useState } from "react";
import { useTransactions, useDeleteTransaction, type TransactionWithRelations } from "@/hooks/use-transactions";
import { useBankAccounts } from "@/hooks/use-bank-accounts";
import { useCategories } from "@/hooks/use-categories";
import { TransactionDialog } from "@/components/transactions/TransactionDialog";
import { formatCents, formatDate } from "@/lib/utils/format";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { Badge } from "@/components/ui/badge";
import { Plus, Pencil, Trash2, ArrowLeftRight, ChevronLeft, ChevronRight } from "lucide-react";
import { CategoryIcon } from "@/components/ui/category-icon";

const TYPE_COLORS = {
  INCOME: "text-emerald-400",
  EXPENSE: "text-red-400",
  TRANSFER: "text-blue-400",
};

export default function TransactionsPage() {
  const [filters, setFilters] = useState({
    bankAccountId: "",
    type: "",
    categoryId: "",
    from: "",
    to: "",
    search: "",
    page: 1,
  });
  const [dialogOpen, setDialogOpen] = useState(false);
  const [editing, setEditing] = useState<TransactionWithRelations | undefined>();

  const { data, isLoading } = useTransactions({
    bankAccountId: filters.bankAccountId || undefined,
    type: filters.type || undefined,
    categoryId: filters.categoryId || undefined,
    from: filters.from || undefined,
    to: filters.to || undefined,
    search: filters.search || undefined,
    page: filters.page,
  });

  const { data: accounts = [] } = useBankAccounts();
  const { data: categories = [] } = useCategories();
  const del = useDeleteTransaction();

  const { transactions = [], total = 0, pageSize = 25 } = data ?? {};
  const totalPages = Math.ceil(total / pageSize);

  function setFilter(key: string, value: string) {
    setFilters((f) => ({ ...f, [key]: value, page: 1 }));
  }

  function openEdit(tx: TransactionWithRelations) {
    setEditing(tx);
    setDialogOpen(true);
  }

  function openCreate() {
    setEditing(undefined);
    setDialogOpen(true);
  }

  async function handleDelete(id: string) {
    if (confirm("Delete this transaction? The account balance will be reversed.")) {
      await del.mutateAsync(id);
    }
  }

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold text-white">Transactions</h1>
          <p className="text-slate-400 mt-1">{total} transaction{total !== 1 ? "s" : ""}</p>
        </div>
        <Button onClick={openCreate} className="bg-emerald-600 hover:bg-emerald-500 text-white">
          <Plus className="h-4 w-4 mr-2" />
          Add Transaction
        </Button>
      </div>

      {/* Filters */}
      <div className="grid grid-cols-2 sm:flex sm:flex-wrap gap-2">
        <Input
          placeholder="Search..."
          value={filters.search}
          onChange={(e) => setFilter("search", e.target.value)}
          className="col-span-2 sm:w-48 bg-slate-800 border-slate-600 text-white placeholder:text-slate-500"
        />
        <Select value={filters.bankAccountId} onValueChange={(v) => setFilter("bankAccountId", v === "all" ? "" : v)}>
          <SelectTrigger className="bg-slate-800 border-slate-600 text-slate-200 sm:w-44">
            <SelectValue placeholder="All accounts" />
          </SelectTrigger>
          <SelectContent className="bg-slate-800 border-slate-600">
            <SelectItem value="all" className="text-slate-200 focus:bg-slate-700">All accounts</SelectItem>
            {accounts.map((a) => (
              <SelectItem key={a.id} value={a.id} className="text-slate-200 focus:bg-slate-700">{a.name}</SelectItem>
            ))}
          </SelectContent>
        </Select>
        <Select value={filters.type} onValueChange={(v) => setFilter("type", v === "all" ? "" : v)}>
          <SelectTrigger className="bg-slate-800 border-slate-600 text-slate-200 sm:w-36">
            <SelectValue placeholder="Type" />
          </SelectTrigger>
          <SelectContent className="bg-slate-800 border-slate-600">
            <SelectItem value="all" className="text-slate-200 focus:bg-slate-700">All types</SelectItem>
            <SelectItem value="INCOME" className="text-slate-200 focus:bg-slate-700">Income</SelectItem>
            <SelectItem value="EXPENSE" className="text-slate-200 focus:bg-slate-700">Expense</SelectItem>
            <SelectItem value="TRANSFER" className="text-slate-200 focus:bg-slate-700">Transfer</SelectItem>
          </SelectContent>
        </Select>
        <Select value={filters.categoryId} onValueChange={(v) => setFilter("categoryId", v === "all" ? "" : v)}>
          <SelectTrigger className="bg-slate-800 border-slate-600 text-slate-200 sm:w-44">
            <SelectValue placeholder="Category" />
          </SelectTrigger>
          <SelectContent className="bg-slate-800 border-slate-600">
            <SelectItem value="all" className="text-slate-200 focus:bg-slate-700">All categories</SelectItem>
            {categories.map((c) => (
              <SelectItem key={c.id} value={c.id} className="text-slate-200 focus:bg-slate-700">
                {c.icon} {c.name}
              </SelectItem>
            ))}
          </SelectContent>
        </Select>
        <Input
          type="date"
          value={filters.from}
          onChange={(e) => setFilter("from", e.target.value)}
          className="bg-slate-800 border-slate-600 text-white sm:w-40"
        />
        <Input
          type="date"
          value={filters.to}
          onChange={(e) => setFilter("to", e.target.value)}
          className="bg-slate-800 border-slate-600 text-white sm:w-40"
        />
      </div>

      {/* Table */}
      <div className="rounded-xl border border-slate-700/50 overflow-x-auto">
        <table className="w-full text-sm min-w-[480px]">
          <thead className="bg-slate-800/80">
            <tr>
              <th className="text-left px-4 py-3 text-slate-400 font-medium">Date</th>
              <th className="text-left px-4 py-3 text-slate-400 font-medium">Description</th>
              <th className="text-left px-4 py-3 text-slate-400 font-medium hidden sm:table-cell">Category</th>
              <th className="text-left px-4 py-3 text-slate-400 font-medium hidden md:table-cell">Account</th>
              <th className="text-right px-4 py-3 text-slate-400 font-medium">Amount</th>
              <th className="px-4 py-3" />
            </tr>
          </thead>
          <tbody>
            {isLoading ? (
              Array.from({ length: 8 }).map((_, i) => (
                <tr key={i} className="border-t border-slate-700/50">
                  {Array.from({ length: 4 }).map((_, j) => (
                    <td key={j} className="px-4 py-3">
                      <div className="h-4 bg-slate-700/50 rounded animate-pulse" />
                    </td>
                  ))}
                </tr>
              ))
            ) : transactions.length === 0 ? (
              <tr>
                <td colSpan={6} className="px-4 py-16 text-center text-slate-500">
                  <ArrowLeftRight className="h-8 w-8 mx-auto mb-3 opacity-30" />
                  <p>No transactions found</p>
                </td>
              </tr>
            ) : (
              transactions.map((tx) => (
                <tr
                  key={tx.id}
                  className="border-t border-slate-700/50 hover:bg-slate-800/30 group transition-colors"
                >
                  <td className="px-4 py-3 text-slate-400 whitespace-nowrap text-xs sm:text-sm">
                    {formatDate(tx.date)}
                  </td>
                  <td className="px-4 py-3 text-slate-200 max-w-[140px] sm:max-w-xs truncate">
                    {tx.description}
                  </td>
                  <td className="px-4 py-3 hidden sm:table-cell">
                    {tx.category ? (
                      <Badge
                        className="text-xs font-normal"
                        style={{
                          backgroundColor: tx.category.color ? tx.category.color + "33" : undefined,
                          color: tx.category.color ?? undefined,
                          borderColor: tx.category.color ? tx.category.color + "66" : undefined,
                        }}
                      >
                        <CategoryIcon icon={tx.category.icon} color={tx.category.color} className="h-3 w-3 shrink-0" />
                        {tx.category.name}
                      </Badge>
                    ) : (
                      <span className="text-slate-600">—</span>
                    )}
                  </td>
                  <td className="px-4 py-3 text-slate-400 whitespace-nowrap hidden md:table-cell">
                    {tx.bankAccount.name}
                  </td>
                  <td className={`px-4 py-3 text-right font-mono font-medium whitespace-nowrap text-xs sm:text-sm ${TYPE_COLORS[tx.type]}`}>
                    {tx.type === "EXPENSE" ? "−" : tx.type === "INCOME" ? "+" : ""}
                    {formatCents(tx.amountCents)}
                  </td>
                  <td className="px-4 py-3">
                    <div className="flex gap-1 opacity-100 sm:opacity-0 group-hover:opacity-100 transition-opacity justify-end">
                      <Button
                        size="icon"
                        variant="ghost"
                        className="h-7 w-7 text-slate-400 hover:text-white"
                        onClick={() => openEdit(tx)}
                      >
                        <Pencil className="h-3.5 w-3.5" />
                      </Button>
                      <Button
                        size="icon"
                        variant="ghost"
                        className="h-7 w-7 text-slate-400 hover:text-red-400"
                        onClick={() => handleDelete(tx.id)}
                      >
                        <Trash2 className="h-3.5 w-3.5" />
                      </Button>
                    </div>
                  </td>
                </tr>
              ))
            )}
          </tbody>
        </table>
      </div>

      {/* Pagination */}
      {totalPages > 1 && (
        <div className="flex items-center justify-between text-sm text-slate-400">
          <span>
            Showing {(filters.page - 1) * pageSize + 1}–
            {Math.min(filters.page * pageSize, total)} of {total}
          </span>
          <div className="flex gap-2">
            <Button
              size="sm"
              variant="outline"
              className="border-slate-600 text-slate-300"
              disabled={filters.page <= 1}
              onClick={() => setFilters((f) => ({ ...f, page: f.page - 1 }))}
            >
              <ChevronLeft className="h-4 w-4" />
            </Button>
            <Button
              size="sm"
              variant="outline"
              className="border-slate-600 text-slate-300"
              disabled={filters.page >= totalPages}
              onClick={() => setFilters((f) => ({ ...f, page: f.page + 1 }))}
            >
              <ChevronRight className="h-4 w-4" />
            </Button>
          </div>
        </div>
      )}

      <TransactionDialog
        open={dialogOpen}
        onClose={() => setDialogOpen(false)}
        existing={editing}
      />
    </div>
  );
}
