"use client";

import { useState } from "react";
import { PageLayout, LoadingState, PageHeader } from "@/components/layout";
import {
  AccountCard,
  AccountEditDialog,
  AccountBulkActions,
} from "@/components/accounts";
import { useBankingData } from "@/lib/hooks";
import { updateAccount, deleteAccount } from "@/lib/store-db";
import { Card, CardContent } from "@/components/ui/card";
import { Building2, Folder } 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 [selectedAccounts, setSelectedAccounts] = useState<Set<string>>(
    new Set(),
  );
  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 handleBulkDelete = async () => {
    const count = selectedAccounts.size;
    if (
      !confirm(
        `Supprimer ${count} compte${count > 1 ? "s" : ""} et toutes leurs transactions ?`,
      )
    )
      return;

    try {
      const ids = Array.from(selectedAccounts);
      const response = await fetch(
        `/api/banking/accounts?ids=${ids.join(",")}`,
        {
          method: "DELETE",
        },
      );
      if (!response.ok) {
        throw new Error("Failed to delete accounts");
      }
      setSelectedAccounts(new Set());
      refresh();
    } catch (error) {
      console.error("Error deleting accounts:", error);
      alert("Erreur lors de la suppression des comptes");
    }
  };

  const toggleSelectAccount = (accountId: string, selected: boolean) => {
    const newSelected = new Set(selectedAccounts);
    if (selected) {
      newSelected.add(accountId);
    } else {
      newSelected.delete(accountId);
    }
    setSelectedAccounts(newSelected);
  };


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

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

  // Grouper les comptes par folder
  const accountsByFolder = data.accounts.reduce(
    (acc, account) => {
      const folderId = account.folderId || "no-folder";
      if (!acc[folderId]) {
        acc[folderId] = [];
      }
      acc[folderId].push(account);
      return acc;
    },
    {} as Record<string, Account[]>,
  );

  // Obtenir les folders racine (sans parent) et les trier par nom
  const rootFolders = data.folders
    .filter((f) => !f.parentId)
    .sort((a, b) => a.name.localeCompare(b.name));

  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>
      ) : (
        <>
          <AccountBulkActions
            selectedCount={selectedAccounts.size}
            onDelete={handleBulkDelete}
          />
          <div className="space-y-6">
            {/* Afficher d'abord les comptes sans dossier */}
            {accountsByFolder["no-folder"] &&
              accountsByFolder["no-folder"].length > 0 && (
                <div>
                  <div className="flex items-center gap-2 mb-4">
                    <Folder className="w-5 h-5 text-muted-foreground" />
                    <h2 className="text-lg font-semibold">Sans dossier</h2>
                    <span className="text-sm text-muted-foreground">
                      ({accountsByFolder["no-folder"].length})
                    </span>
                  </div>
                  <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-3">
                    {accountsByFolder["no-folder"].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}
                          isSelected={selectedAccounts.has(account.id)}
                          onSelect={toggleSelectAccount}
                        />
                      );
                    })}
                  </div>
                </div>
              )}

            {/* Afficher les comptes groupés par folder */}
            {rootFolders.map((folder) => {
              const folderAccounts = accountsByFolder[folder.id] || [];
              if (folderAccounts.length === 0) return null;

              const folderBalance = folderAccounts.reduce(
                (sum, a) => sum + a.balance,
                0,
              );

              return (
                <div key={folder.id}>
                  <div className="flex items-center gap-2 mb-4">
                    <div
                      className="w-5 h-5 rounded flex items-center justify-center"
                      style={{ backgroundColor: `${folder.color}20` }}
                    >
                      <Folder
                        className="w-4 h-4"
                        style={{ color: folder.color }}
                      />
                    </div>
                    <h2 className="text-lg font-semibold">{folder.name}</h2>
                    <span className="text-sm text-muted-foreground">
                      ({folderAccounts.length})
                    </span>
                    <span
                      className={cn(
                        "text-sm font-semibold tabular-nums ml-auto",
                        folderBalance >= 0
                          ? "text-emerald-600"
                          : "text-red-600",
                      )}
                    >
                      {formatCurrency(folderBalance)}
                    </span>
                  </div>
                  <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-3">
                    {folderAccounts.map((account) => {
                      const accountFolder = data.folders.find(
                        (f) => f.id === account.folderId,
                      );

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

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