"use client";

import { useState } from "react";
import { PageLayout, LoadingState, PageHeader } from "@/components/layout";
import { AccountCard, AccountEditDialog } from "@/components/accounts";
import { useBankingData } from "@/lib/hooks";
import { updateAccount, deleteAccount } from "@/lib/store-db";
import { Card, CardContent } from "@/components/ui/card";
import { Building2 } from "lucide-react";
import type { Account } from "@/lib/types";
import { cn } from "@/lib/utils";

export default function AccountsPage() {
  const { data, isLoading, refresh } = useBankingData();
  const [editingAccount, setEditingAccount] = useState<Account | null>(null);
  const [isDialogOpen, setIsDialogOpen] = useState(false);
  const [formData, setFormData] = useState({
    name: "",
    type: "CHECKING" as Account["type"],
    folderId: "folder-root",
    externalUrl: "",
  });

  if (isLoading || !data) {
    return <LoadingState />;
  }

  const formatCurrency = (amount: number) => {
    return new Intl.NumberFormat("fr-FR", {
      style: "currency",
      currency: "EUR",
    }).format(amount);
  };

  const handleEdit = (account: Account) => {
    setEditingAccount(account);
    setFormData({
      name: account.name,
      type: account.type,
      folderId: account.folderId || "folder-root",
      externalUrl: account.externalUrl || "",
    });
    setIsDialogOpen(true);
  };

  const handleSave = async () => {
    if (!editingAccount) return;

    try {
      const updatedAccount = {
        ...editingAccount,
        name: formData.name,
        type: formData.type,
        folderId: formData.folderId,
        externalUrl: formData.externalUrl || null,
      };
      await updateAccount(updatedAccount);
      refresh();
      setIsDialogOpen(false);
      setEditingAccount(null);
    } catch (error) {
      console.error("Error updating account:", error);
      alert("Erreur lors de la mise à jour du compte");
    }
  };

  const handleDelete = async (accountId: string) => {
    if (!confirm("Supprimer ce compte et toutes ses transactions ?")) return;

    try {
      await deleteAccount(accountId);
      refresh();
    } catch (error) {
      console.error("Error deleting account:", error);
      alert("Erreur lors de la suppression du compte");
    }
  };

  const getTransactionCount = (accountId: string) => {
    return data.transactions.filter((t) => t.accountId === accountId).length;
  };

  const totalBalance = data.accounts.reduce((sum, a) => sum + a.balance, 0);

  return (
    <PageLayout>
      <PageHeader
        title="Comptes"
        description="Gérez vos comptes bancaires"
        rightContent={
          <div className="text-right">
            <p className="text-sm text-muted-foreground">Solde total</p>
            <p
              className={cn(
                "text-2xl font-bold",
                totalBalance >= 0 ? "text-emerald-600" : "text-red-600"
              )}
            >
              {formatCurrency(totalBalance)}
            </p>
          </div>
        }
      />

      {data.accounts.length === 0 ? (
        <Card>
          <CardContent className="flex flex-col items-center justify-center py-12">
            <Building2 className="w-16 h-16 text-muted-foreground mb-4" />
            <h3 className="text-lg font-semibold mb-2">Aucun compte</h3>
            <p className="text-muted-foreground text-center mb-4">
              Importez un fichier OFX depuis le tableau de bord pour ajouter
              votre premier compte.
            </p>
          </CardContent>
        </Card>
      ) : (
        <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-3">
          {data.accounts.map((account) => {
            const folder = data.folders.find((f) => f.id === account.folderId);

            return (
              <AccountCard
                key={account.id}
                account={account}
                folder={folder}
                transactionCount={getTransactionCount(account.id)}
                onEdit={handleEdit}
                onDelete={handleDelete}
                formatCurrency={formatCurrency}
              />
            );
          })}
        </div>
      )}

      <AccountEditDialog
        open={isDialogOpen}
        onOpenChange={setIsDialogOpen}
        formData={formData}
        onFormDataChange={setFormData}
        folders={data.folders}
        onSave={handleSave}
      />
    </PageLayout>
  );
}
