"use client";

import { useState } from "react";
import { useBankAccounts, useDeleteBankAccount } from "@/hooks/use-bank-accounts";
import { BankAccountDialog } from "@/components/bank-accounts/BankAccountDialog";
import { TransactionDialog } from "@/components/transactions/TransactionDialog";
import { formatCents } from "@/lib/utils/format";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Plus, Pencil, Trash2, Wallet, ArrowLeftRight } from "lucide-react";
import type { BankAccount } from "@prisma/client";

const TYPE_LABELS: Record<string, string> = {
  CHECKING: "Checking",
  SAVINGS: "Savings",
  CASH: "Cash",
  WALLET: "Wallet",
  INVESTMENT: "Investment",
  OTHER: "Other",
};

export default function BankAccountsPage() {
  const { data: accounts = [], isLoading } = useBankAccounts();
  const del = useDeleteBankAccount();
  const [dialogOpen,    setDialogOpen]    = useState(false);
  const [transferOpen,  setTransferOpen]  = useState(false);
  const [transferAccId, setTransferAccId] = useState<string | undefined>();
  const [editing, setEditing] = useState<BankAccount | undefined>();

  const totalCents = accounts.reduce((s, a) => s + a.balanceCents, 0);

  function openEdit(account: BankAccount) {
    setEditing(account);
    setDialogOpen(true);
  }

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

  async function handleDelete(id: string) {
    if (confirm("Archive this account? Transactions will be preserved.")) {
      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">Bank Accounts</h1>
          <p className="text-slate-400 mt-1">
            Total balance:{" "}
            <span className={totalCents >= 0 ? "text-emerald-400" : "text-red-400"}>
              {formatCents(totalCents)}
            </span>
          </p>
        </div>
        <div className="flex gap-2">
          <Button
            onClick={() => { setTransferAccId(undefined); setTransferOpen(true); }}
            variant="outline"
            className="border-blue-500/40 text-blue-300 hover:bg-blue-500/10"
          >
            <ArrowLeftRight className="h-4 w-4 mr-2" />
            Transfer
          </Button>
          <Button onClick={openCreate} className="bg-emerald-600 hover:bg-emerald-500 text-white">
            <Plus className="h-4 w-4 mr-2" />
            Add Account
          </Button>
        </div>
      </div>

      {isLoading ? (
        <div className="grid grid-cols-1 sm:grid-cols-2 xl:grid-cols-3 gap-4">
          {[1, 2, 3].map((i) => (
            <div key={i} className="h-40 rounded-xl bg-slate-800/50 animate-pulse" />
          ))}
        </div>
      ) : accounts.length === 0 ? (
        <div className="flex flex-col items-center justify-center h-64 rounded-xl border border-dashed border-slate-700 text-slate-500 space-y-4">
          <Wallet className="h-10 w-10 opacity-30" />
          <p>No accounts yet. Add your first bank account to get started.</p>
          <Button onClick={openCreate} variant="outline" className="border-slate-600 text-slate-300">
            <Plus className="h-4 w-4 mr-2" /> Add Account
          </Button>
        </div>
      ) : (
        <div className="grid grid-cols-1 sm:grid-cols-2 xl:grid-cols-3 gap-4">
          {accounts.map((account) => (
            <Card key={account.id} className="bg-slate-800/50 border-slate-700/50 relative group">
              <div
                className="absolute left-0 top-0 bottom-0 w-1 rounded-l-xl"
                style={{ backgroundColor: account.color ?? "#10b981" }}
              />
              <CardHeader className="pb-2 pl-5">
                <div className="flex items-start justify-between">
                  <div>
                    <CardTitle className="text-white text-base">{account.name}</CardTitle>
                    <div className="flex items-center gap-2 mt-1">
                      <Badge variant="secondary" className="text-xs bg-slate-700 text-slate-300">
                        {TYPE_LABELS[account.type]}
                      </Badge>
                      {account.institutionName && (
                        <span className="text-xs text-slate-500">{account.institutionName}</span>
                      )}
                    </div>
                  </div>
                  <div className="flex gap-1 opacity-0 group-hover:opacity-100 transition-opacity">
                    <Button
                      size="icon"
                      variant="ghost"
                      className="h-7 w-7 text-slate-400 hover:text-white"
                      onClick={() => openEdit(account)}
                    >
                      <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(account.id)}
                    >
                      <Trash2 className="h-3.5 w-3.5" />
                    </Button>
                  </div>
                </div>
              </CardHeader>
              <CardContent className="pl-5">
                <p
                  className={`text-2xl font-bold ${
                    account.balanceCents >= 0 ? "text-white" : "text-red-400"
                  }`}
                >
                  {formatCents(account.balanceCents, account.currency)}
                </p>
                {account.lastFourDigits && (
                  <p className="text-xs text-slate-500 mt-1">•••• {account.lastFourDigits}</p>
                )}
                <button
                  onClick={() => { setTransferAccId(account.id); setTransferOpen(true); }}
                  className="mt-3 flex items-center gap-1.5 text-xs text-blue-400 hover:text-blue-300 transition-colors"
                >
                  <ArrowLeftRight className="h-3 w-3" />
                  Transfer from this account
                </button>
              </CardContent>
            </Card>
          ))}
        </div>
      )}

      <BankAccountDialog
        open={dialogOpen}
        onClose={() => setDialogOpen(false)}
        existing={editing}
      />

      <TransactionDialog
        open={transferOpen}
        onClose={() => setTransferOpen(false)}
        defaultType="TRANSFER"
        defaultFromAccountId={transferAccId}
      />
    </div>
  );
}
