"use client";

import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Progress } from "@/components/ui/progress";
import type { BankingData } from "@/lib/types";
import { cn } from "@/lib/utils";
import { Building2 } from "lucide-react";

interface AccountsSummaryProps {
  data: BankingData;
}

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

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

  if (data.accounts.length === 0) {
    return (
      <Card>
        <CardHeader>
          <CardTitle>Mes Comptes</CardTitle>
        </CardHeader>
        <CardContent>
          <div className="flex flex-col items-center justify-center py-8 text-center">
            <Building2 className="w-12 h-12 text-muted-foreground mb-3" />
            <p className="text-muted-foreground">Aucun compte</p>
            <p className="text-sm text-muted-foreground mt-1">
              Importez un fichier OFX pour ajouter un compte
            </p>
          </div>
        </CardContent>
      </Card>
    );
  }

  return (
    <Card>
      <CardHeader>
        <CardTitle>Mes Comptes</CardTitle>
      </CardHeader>
      <CardContent>
        <div className="space-y-4">
          {data.accounts.map((account) => {
            const percentage =
              totalPositive > 0
                ? Math.max(0, (account.balance / totalPositive) * 100)
                : 0;

            return (
              <div key={account.id} className="space-y-2">
                <div className="flex items-center justify-between">
                  <div className="flex items-center gap-2">
                    <div className="w-8 h-8 rounded-full bg-primary/10 flex items-center justify-center">
                      <Building2 className="w-4 h-4 text-primary" />
                    </div>
                    <div>
                      <p className="font-medium text-sm">{account.name}</p>
                      <p className="text-xs text-muted-foreground">
                        {account.accountNumber}
                      </p>
                    </div>
                  </div>
                  <span
                    className={cn(
                      "font-semibold tabular-nums",
                      account.balance >= 0
                        ? "text-emerald-600"
                        : "text-red-600",
                    )}
                  >
                    {formatCurrency(account.balance)}
                  </span>
                </div>
                {account.balance > 0 && (
                  <Progress value={percentage} className="h-1.5" />
                )}
              </div>
            );
          })}
        </div>
      </CardContent>
    </Card>
  );
}
