"use client";

import { MoreHorizontal, ArrowUpDown, CheckCircle, XCircle, Clock, AlertCircle } from "lucide-react";

import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import {
    DropdownMenu,
    DropdownMenuContent,
    DropdownMenuItem,
    DropdownMenuSeparator,
    DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { TableCell, TableRow } from "@/components/ui/table";
import { formatCurrency, cn } from "@/lib/utils";
import { BankingTransaction, TransactionType, TransactionStatus } from "@/types/banking";

interface TransactionRowProps {
    transaction: BankingTransaction;
    onViewDetails?: (transactionId: string) => void;
    onEditTransaction?: (transactionId: string) => void;
    onDeleteTransaction?: (transactionId: string) => void;
    className?: string;
}

const typeConfig = {
    deposit: {
        label: "Dépôt",
        color: "bg-green-100 text-green-700",
        icon: "⬇️",
    },
    withdrawal: {
        label: "Retrait",
        color: "bg-red-100 text-red-700",
        icon: "⬆️",
    },
    transfer: {
        label: "Transfert",
        color: "bg-blue-100 text-blue-700",
        icon: "↔️",
    },
    interest: {
        label: "Intérêts",
        color: "bg-purple-100 text-purple-700",
        icon: "📈",
    },
    fee: {
        label: "Frais",
        color: "bg-orange-100 text-orange-700",
        icon: "💰",
    },
    loan_payment: {
        label: "Remb. Prêt",
        color: "bg-indigo-100 text-indigo-700",
        icon: "🏠",
    },
    adjustment: {
        label: "Ajustement",
        color: "bg-gray-100 text-gray-700",
        icon: "⚖️",
    },
} as const;

const statusConfig = {
    pending: {
        label: "En attente",
        color: "bg-yellow-100 text-yellow-700",
        icon: Clock,
    },
    completed: {
        label: "Terminé",
        color: "bg-green-100 text-green-700",
        icon: CheckCircle,
    },
    failed: {
        label: "Échoué",
        color: "bg-red-100 text-red-700",
        icon: XCircle,
    },
    cancelled: {
        label: "Annulé",
        color: "bg-gray-100 text-gray-700",
        icon: AlertCircle,
    },
} as const;

export function TransactionRow({
    transaction,
    onViewDetails,
    onEditTransaction,
    onDeleteTransaction,
    className,
}: TransactionRowProps) {
    const typeInfo = typeConfig[transaction.transaction_type as TransactionType];
    const statusInfo = statusConfig[transaction.status as TransactionStatus];
    const StatusIcon = statusInfo.icon;

    // Déterminer si c'est un crédit ou un débit
    const isCredit = ['deposit', 'interest'].includes(transaction.transaction_type);
    const isDebit = ['withdrawal', 'fee', 'loan_payment'].includes(transaction.transaction_type);

    const getAmountColor = () => {
        if (isCredit) return "text-green-600";
        if (isDebit) return "text-red-600";
        return "text-foreground";
    };

    const getAmountPrefix = () => {
        if (isCredit) return "+";
        if (isDebit) return "-";
        return "";
    };

    return (
        <TableRow className={cn("hover:bg-muted/50", className)}>
            {/* Date et heure */}
            <TableCell className="font-medium">
                <div className="space-y-1">
                    <div className="text-sm">
                        {new Date(transaction.transaction_date).toLocaleDateString('fr-FR')}
                    </div>
                    <div className="text-xs text-muted-foreground">
                        {new Date(transaction.transaction_date).toLocaleTimeString('fr-FR', {
                            hour: '2-digit',
                            minute: '2-digit',
                        })}
                    </div>
                </div>
            </TableCell>

            {/* Type de transaction avec icône */}
            <TableCell>
                <div className="flex items-center gap-2">
                    <span className="text-base">{typeInfo.icon}</span>
                    <Badge variant="secondary" className={cn("text-xs", typeInfo.color)}>
                        {typeInfo.label}
                    </Badge>
                </div>
            </TableCell>

            {/* Description */}
            <TableCell>
                <div className="space-y-1">
                    <div className="font-medium">{transaction.description}</div>
                    {transaction.reference && (
                        <div className="text-xs text-muted-foreground">
                            Réf: {transaction.reference}
                        </div>
                    )}
                </div>
            </TableCell>

            {/* Compte */}
            <TableCell>
                <div className="space-y-1">
                    <div className="text-sm font-medium">{transaction.account_name}</div>
                    <div className="text-xs text-muted-foreground">{transaction.account_number}</div>
                </div>
            </TableCell>

            {/* Montant */}
            <TableCell className="text-right">
                <div className={cn("text-base font-bold tabular-nums", getAmountColor())}>
                    {getAmountPrefix()}{formatCurrency(Math.abs(transaction.amount))}
                </div>
            </TableCell>

            {/* Statut */}
            <TableCell>
                <div className="flex items-center gap-2">
                    <StatusIcon className="h-4 w-4" />
                    <Badge variant="outline" className={cn("text-xs", statusInfo.color)}>
                        {statusInfo.label}
                    </Badge>
                </div>
            </TableCell>

            {/* Actions */}
            <TableCell>
                <DropdownMenu>
                    <DropdownMenuTrigger asChild>
                        <Button variant="ghost" size="icon" className="h-8 w-8">
                            <MoreHorizontal className="h-4 w-4" />
                            <span className="sr-only">Options de transaction</span>
                        </Button>
                    </DropdownMenuTrigger>
                    <DropdownMenuContent align="end">
                        <DropdownMenuItem onClick={() => onViewDetails?.(transaction.id)}>
                            <ArrowUpDown className="mr-2 h-4 w-4" />
                            Voir les détails
                        </DropdownMenuItem>
                        {transaction.status === 'pending' && (
                            <>
                                <DropdownMenuItem onClick={() => onEditTransaction?.(transaction.id)}>
                                    Modifier
                                </DropdownMenuItem>
                                <DropdownMenuSeparator />
                                <DropdownMenuItem
                                    onClick={() => onDeleteTransaction?.(transaction.id)}
                                    className="text-red-600"
                                >
                                    Annuler la transaction
                                </DropdownMenuItem>
                            </>
                        )}
                    </DropdownMenuContent>
                </DropdownMenu>
            </TableCell>
        </TableRow>
    );
}
