"use client";

import { useState } from "react";
import { Button } from "@/components/ui/button";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import {
  MoreVertical,
  Pencil,
  Trash2,
  Folder,
  FolderOpen,
  ChevronRight,
  ChevronDown,
  Building2,
} from "lucide-react";
import { cn } from "@/lib/utils";
import Link from "next/link";
import type { Folder as FolderType, Account } from "@/lib/types";

interface FolderTreeItemProps {
  folder: FolderType;
  accounts: Account[];
  allFolders: FolderType[];
  level: number;
  onEdit: (folder: FolderType) => void;
  onDelete: (folderId: string) => void;
  onEditAccount: (account: Account) => void;
  formatCurrency: (amount: number) => string;
}

export function FolderTreeItem({
  folder,
  accounts,
  allFolders,
  level,
  onEdit,
  onDelete,
  onEditAccount,
  formatCurrency,
}: FolderTreeItemProps) {
  const [isExpanded, setIsExpanded] = useState(true);

  // Pour le dossier "Mes Comptes" (folder-root), inclure aussi les comptes sans dossier
  const folderAccounts = accounts.filter(
    (a) =>
      a.folderId === folder.id ||
      (folder.id === "folder-root" && a.folderId === null)
  );
  const childFolders = allFolders.filter((f) => f.parentId === folder.id);
  const hasChildren = childFolders.length > 0 || folderAccounts.length > 0;

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

  return (
    <div>
      <div
        className={cn(
          "flex items-center gap-2 p-2 rounded-lg hover:bg-muted/50 group",
          level > 0 && "ml-6"
        )}
      >
        <button
          onClick={() => setIsExpanded(!isExpanded)}
          className="p-1 hover:bg-muted rounded"
          disabled={!hasChildren}
        >
          {hasChildren ? (
            isExpanded ? (
              <ChevronDown className="w-4 h-4 text-muted-foreground" />
            ) : (
              <ChevronRight className="w-4 h-4 text-muted-foreground" />
            )
          ) : (
            <div className="w-4 h-4" />
          )}
        </button>

        <div
          className="w-6 h-6 rounded flex items-center justify-center"
          style={{ backgroundColor: `${folder.color}20` }}
        >
          {isExpanded ? (
            <FolderOpen className="w-4 h-4" style={{ color: folder.color }} />
          ) : (
            <Folder className="w-4 h-4" style={{ color: folder.color }} />
          )}
        </div>

        <span className="flex-1 font-medium text-sm">{folder.name}</span>

        {folderAccounts.length > 0 && (
          <span
            className={cn(
              "text-sm font-semibold tabular-nums",
              folderTotal >= 0 ? "text-emerald-600" : "text-red-600"
            )}
          >
            {formatCurrency(folderTotal)}
          </span>
        )}

        <DropdownMenu>
          <DropdownMenuTrigger asChild>
            <Button
              variant="ghost"
              size="icon"
              className="h-7 w-7 opacity-0 group-hover:opacity-100"
            >
              <MoreVertical className="w-4 h-4" />
            </Button>
          </DropdownMenuTrigger>
          <DropdownMenuContent align="end">
            <DropdownMenuItem onClick={() => onEdit(folder)}>
              <Pencil className="w-4 h-4 mr-2" />
              Modifier
            </DropdownMenuItem>
            {folder.id !== "folder-root" && (
              <DropdownMenuItem
                onClick={() => onDelete(folder.id)}
                className="text-red-600"
              >
                <Trash2 className="w-4 h-4 mr-2" />
                Supprimer
              </DropdownMenuItem>
            )}
          </DropdownMenuContent>
        </DropdownMenu>
      </div>

      {isExpanded && (
        <div>
          {folderAccounts.map((account) => (
            <div
              key={account.id}
              className={cn(
                "flex items-center gap-2 p-2 rounded-lg hover:bg-muted/50 group",
                "ml-12"
              )}
            >
              <Building2 className="w-4 h-4 text-muted-foreground" />
              <Link
                href={`/transactions?accountId=${account.id}`}
                className="flex-1 text-sm hover:text-primary hover:underline"
              >
                {account.name}
              </Link>
              <span
                className={cn(
                  "text-sm tabular-nums",
                  account.balance >= 0 ? "text-emerald-600" : "text-red-600"
                )}
              >
                {formatCurrency(account.balance)}
              </span>
              <Button
                variant="ghost"
                size="icon"
                className="h-7 w-7 opacity-0 group-hover:opacity-100"
                onClick={() => onEditAccount(account)}
              >
                <Pencil className="w-4 h-4" />
              </Button>
            </div>
          ))}

          {childFolders.map((child) => (
            <FolderTreeItem
              key={child.id}
              folder={child}
              accounts={accounts}
              allFolders={allFolders}
              level={level + 1}
              onEdit={onEdit}
              onDelete={onDelete}
              onEditAccount={onEditAccount}
              formatCurrency={formatCurrency}
            />
          ))}
        </div>
      )}
    </div>
  );
}

