"use client";

import { useSortable } from "@dnd-kit/sortable";
import { CSS } from "@dnd-kit/utilities";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import {
  MoreVertical,
  Pencil,
  Trash2,
  ExternalLink,
  GripVertical,
} from "lucide-react";
import { cn } from "@/lib/utils";
import Link from "next/link";
import type { Account, Folder } from "@/lib/types";
import { accountTypeIcons, accountTypeLabels } from "./constants";
import { Checkbox } from "@/components/ui/checkbox";
import { getAccountBalance } from "@/lib/account-utils";
import { useIsMobile } from "@/hooks/use-mobile";

interface AccountCardProps {
  account: Account;
  folder?: Folder;
  transactionCount: number;
  onEdit: (account: Account) => void;
  onDelete: (accountId: string) => void;
  formatCurrency: (amount: number) => string;
  isSelected?: boolean;
  onSelect?: (accountId: string, selected: boolean) => void;
  draggableId?: string;
  compact?: boolean;
}

export function AccountCard({
  account,
  folder,
  transactionCount,
  onEdit,
  onDelete,
  formatCurrency,
  isSelected = false,
  onSelect,
  draggableId,
  compact = false,
}: AccountCardProps) {
  const isMobile = useIsMobile();
  const Icon = accountTypeIcons[account.type];
  const realBalance = getAccountBalance(account);

  const {
    attributes,
    listeners,
    setNodeRef,
    transform,
    transition,
    isDragging,
  } = useSortable({
    id: draggableId || `account-${account.id}`,
    disabled: !draggableId,
    data: {
      type: "account",
      account,
    },
  });

  const style = {
    transform: CSS.Transform.toString(transform),
    transition,
    opacity: isDragging ? 0.5 : 1,
  };

  const cardContent = (
    <Card
      className={cn(
        "relative group",
        isSelected && "ring-2 ring-primary shadow-lg shadow-primary/10",
        isDragging && "bg-muted/80 opacity-60",
        "hover:scale-[1.02] transition-transform duration-200",
      )}
    >
      <CardHeader className={cn("pb-0", isMobile && "px-2 pt-2")}>
        <div className="flex items-start justify-between gap-1.5">
          <div className="flex items-center gap-1.5 flex-1 min-w-0">
            {draggableId && !isMobile && (
              <button
                {...attributes}
                {...listeners}
                className="p-1 hover:bg-muted rounded cursor-grab active:cursor-grabbing shrink-0"
                onClick={(e) => e.stopPropagation()}
              >
                <GripVertical className="w-4 h-4 text-muted-foreground" />
              </button>
            )}
            {onSelect && (
              <Checkbox
                checked={isSelected}
                onCheckedChange={(checked) =>
                  onSelect(account.id, checked === true)
                }
                onClick={(e) => e.stopPropagation()}
                className="shrink-0"
              />
            )}
            <div
              className={cn(
                "rounded-full bg-primary/10 flex items-center justify-center shrink-0",
                isMobile ? "w-6 h-6" : "w-8 h-8",
              )}
            >
              <Icon
                className={cn("text-primary", isMobile ? "w-3 h-3" : "w-4 h-4")}
              />
            </div>
            <div className="min-w-0 flex-1">
              <CardTitle
                className={cn(
                  "font-semibold truncate leading-tight",
                  isMobile ? "text-[11px]" : "text-sm",
                )}
              >
                {account.name}
              </CardTitle>
              {!compact && !isMobile && (
                <>
                  <p className="text-xs text-muted-foreground">
                    {accountTypeLabels[account.type]}
                  </p>
                  {account.accountNumber && (
                    <p className="text-xs text-muted-foreground mt-0.5 truncate">
                      {account.accountNumber}
                    </p>
                  )}
                </>
              )}
            </div>
          </div>
          <DropdownMenu>
            <DropdownMenuTrigger asChild>
              <Button
                variant="ghost"
                size="icon"
                className={cn("shrink-0", isMobile ? "h-5 w-5" : "h-7 w-7")}
              >
                <MoreVertical
                  className={cn(isMobile ? "w-2.5 h-2.5" : "w-3.5 h-3.5")}
                />
              </Button>
            </DropdownMenuTrigger>
            <DropdownMenuContent align="end">
              <DropdownMenuItem onClick={() => onEdit(account)}>
                <Pencil className="w-4 h-4 mr-2" />
                Modifier
              </DropdownMenuItem>
              <DropdownMenuItem
                onClick={() => onDelete(account.id)}
                variant="destructive"
              >
                <Trash2 className="w-4 h-4 mr-2" />
                Supprimer
              </DropdownMenuItem>
            </DropdownMenuContent>
          </DropdownMenu>
        </div>
      </CardHeader>
      <CardContent
        className={cn(isMobile ? "px-2 pb-2 pt-1" : "pt-1", compact && "pt-0")}
      >
        <div className="flex items-center justify-between gap-1.5">
          <div
            className={cn(
              "font-bold truncate",
              compact
                ? isMobile
                  ? "text-sm"
                  : "text-lg"
                : isMobile
                  ? "text-base"
                  : "text-xl",
              !compact && !isMobile && "mb-1.5",
              realBalance >= 0 ? "text-emerald-600" : "text-red-600",
            )}
          >
            {formatCurrency(realBalance)}
          </div>
          {compact && (
            <Link
              href={`/transactions?accountId=${account.id}`}
              className={cn(
                "text-muted-foreground hover:text-primary hover:underline shrink-0 whitespace-nowrap",
                isMobile ? "text-[9px]" : "text-xs",
              )}
            >
              {transactionCount} txns
            </Link>
          )}
        </div>
        {!compact && (
          <>
            <div
              className={cn(
                "flex items-center justify-between gap-2 mt-1",
                isMobile ? "text-[10px]" : "text-xs",
                "text-muted-foreground",
              )}
            >
              <Link
                href={`/transactions?accountId=${account.id}`}
                className="hover:text-primary hover:underline truncate"
              >
                {transactionCount} transactions
              </Link>
              {folder && !isMobile && (
                <span className="truncate ml-2 shrink-0">{folder.name}</span>
              )}
            </div>
            {!isMobile && (
              <>
                {account.initialBalance !== undefined &&
                  account.initialBalance !== null && (
                    <p className="text-xs text-muted-foreground mt-1.5">
                      Solde initial: {formatCurrency(account.initialBalance)}
                    </p>
                  )}
                {account.lastImport && (
                  <p className="text-xs text-muted-foreground mt-1.5">
                    Dernier import:{" "}
                    {new Date(account.lastImport).toLocaleDateString("fr-FR")}
                  </p>
                )}
                {account.externalUrl && (
                  <a
                    href={account.externalUrl}
                    target="_blank"
                    rel="noopener noreferrer"
                    className="inline-flex items-center gap-1 text-xs text-primary hover:underline mt-1.5"
                  >
                    <ExternalLink className="w-3 h-3" />
                    Accéder au portail banque
                  </a>
                )}
              </>
            )}
          </>
        )}
      </CardContent>
    </Card>
  );

  if (draggableId) {
    return (
      <div ref={setNodeRef} style={style}>
        {cardContent}
      </div>
    );
  }

  return cardContent;
}
