import { CheckCircle, ChevronDown, Pencil, Printer, Send, Trash2, XCircle } from 'lucide-react';
import { ImagePreviewButton } from '@/components/dialogs';
import { RowActions } from '@/components/data-display';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Card, CardContent } from '@/components/ui/card';
import {
    DropdownMenu,
    DropdownMenuContent,
    DropdownMenuItem,
    DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip';
import { useCan } from '@/hooks/use-can';
import type { PaperWidth } from '@/hooks/use-thermal-printer';
import { formatDateTime, formatNumber } from '@/lib/format';
import { formatCurrency } from '@/lib/utils';
import type { Transaction } from './columns';

const STATUS_BADGE_CLASSES: Record<string, string> = {
    pending: 'bg-yellow-100 text-yellow-800 hover:bg-yellow-100',
    processing: 'bg-blue-100 text-blue-800 hover:bg-blue-100',
    completed: 'bg-green-100 text-green-800 hover:bg-green-100',
    cancelled: 'bg-red-100 text-red-800 hover:bg-red-100',
    refunded: 'bg-purple-100 text-purple-800 hover:bg-purple-100',
};

export type TransactionCardRowParams = {
    transaction: Transaction;
    index: number;
    isExpanded: boolean;
    onToggleExpand: () => void;
    onEdit: (transaction: Transaction) => void;
    onDelete: (transaction: Transaction) => void;
    onUpdateStatus: (transaction: Transaction, status: string) => void;
    onPrint: (transaction: Transaction, paperWidth: PaperWidth) => void;
};

export function TransactionCardRow({
    transaction,
    index,
    isExpanded,
    onToggleExpand,
    onEdit,
    onDelete,
    onUpdateStatus,
    onPrint,
}: TransactionCardRowParams) {
    const { can } = useCan();
    const items = transaction.order_items ?? [];
    const variantCount = items.length;
    const productNames = [
        ...new Set(
            items
                .map((item) => item.product_variant?.product?.name)
                .filter(Boolean),
        ),
    ];
    const totalQty = items.reduce(
        (sum, item) => sum + Number(item.quantity),
        0,
    );
    const statusBadgeClass =
        STATUS_BADGE_CLASSES[transaction.status] ?? STATUS_BADGE_CLASSES.pending;

    return (
        <Card className="overflow-hidden">
            <CardContent className="p-0">
                <div className="flex items-start gap-3 p-4">
                    <Button
                        variant="ghost"
                        size="icon"
                        className="mt-0.5 h-6 w-6 shrink-0"
                        onClick={onToggleExpand}
                    >
                        <ChevronDown
                            className={`h-4 w-4 transition-transform ${isExpanded ? 'rotate-180' : ''}`}
                        />
                    </Button>

                    <div className="min-w-0 flex-1">
                        <div className="flex flex-wrap items-center gap-2">
                            <span className="text-xs text-muted-foreground">
                                {index}.
                            </span>
                            <h3 className="font-medium">
                                {transaction.order_number}
                            </h3>
                            <Badge
                                variant="secondary"
                                className={statusBadgeClass}
                            >
                                {transaction.status_label}
                            </Badge>
                            <Badge variant="outline">
                                {transaction.payment_type_label}
                            </Badge>
                            {transaction.tiktok_order_id || transaction.shopee_order_id ? (
                                <Badge variant="outline">
                                    {transaction.tiktok_order_id || transaction.shopee_order_id}
                                </Badge>
                            ) : null}
                        </div>

                        <div className="mt-1 text-xs text-muted-foreground">
                            {productNames.length > 0 && (
                                <span>{productNames.join(', ')}</span>
                            )}
                            {variantCount > 0 && (
                                <span> ({variantCount} varian)</span>
                            )}
                        </div>

                        <div className="mt-2 flex flex-wrap items-center gap-3 text-xs text-muted-foreground">
                            <span className="inline-flex items-center rounded-md bg-muted px-2 py-1 font-medium text-foreground">
                                {formatDateTime(transaction.created_at)}
                            </span>
                            <span className="text-muted-foreground">
                                Oleh:{' '}
                                <span className="font-medium text-foreground">
                                    {transaction.created_by?.user_profile
                                        ?.full_name ?? '-'}
                                </span>
                            </span>
                            {transaction.marketing && (
                                <span className="text-muted-foreground">
                                    Marketing:{' '}
                                    <span className="font-medium text-foreground">
                                        {transaction.marketing.user_profile
                                            ?.full_name ?? '-'}
                                    </span>
                                </span>
                            )}
                            {transaction.customer && (
                                <span className="text-muted-foreground">
                                    Pelanggan:{' '}
                                    <span className="font-medium text-foreground">
                                        {transaction.customer.name}
                                    </span>
                                </span>
                            )}
                            {transaction.notes && (
                                <span className="max-w-[200px]">
                                    {transaction.notes}
                                </span>
                            )}
                        </div>

                        <div className="mt-2 flex flex-wrap items-center gap-x-4 gap-y-1 text-xs">
                            <span>
                                <span className="text-muted-foreground">
                                    Qty:{' '}
                                </span>
                                {formatNumber(totalQty)}
                            </span>
                            <span>
                                <span className="text-muted-foreground">
                                    Channel:{' '}
                                </span>
                                {transaction.channel_label}
                            </span>
                            <span>
                                <span className="text-muted-foreground">
                                    Harga:{' '}
                                </span>
                                {transaction.price_type_label}
                            </span>
                            <span>
                                <span className="text-muted-foreground">
                                    Sub:{' '}
                                </span>
                                {formatCurrency(transaction.subtotal)}
                            </span>
                            {transaction.discount > 0 && (
                                <span>
                                    <span className="text-muted-foreground">
                                        Diskon:{' '}
                                    </span>
                                    {formatCurrency(transaction.discount)}
                                </span>
                            )}
                            {transaction.nego_price != null && transaction.nego_price > 0 && (
                                <span>
                                    <span className="text-muted-foreground">
                                        Nego:{' '}
                                    </span>
                                    {formatCurrency(transaction.nego_price)}
                                </span>
                            )}
                            <span className="font-semibold">
                                <span className="font-normal text-muted-foreground">
                                    Total:{' '}
                                </span>
                                {formatCurrency(transaction.total_amount)}
                            </span>
                            <span className={transaction.profit >= 0 ? 'text-green-600' : 'text-red-600'}>
                                <span className="font-normal text-muted-foreground">
                                    Laba:{' '}
                                </span>
                                {formatCurrency(transaction.profit)}
                            </span>
                            <span>
                                <span className="text-muted-foreground">
                                    HPP:{' '}
                                </span>
                                {formatCurrency(transaction.cogs)}
                            </span>
                        </div>

                        {transaction.photo_url && (
                            <div className="mt-2">
                                <ImagePreviewButton
                                    srcs={[transaction.photo_conversion_url ?? transaction.photo_url]}
                                    modalSrc={transaction.photo_url}
                                    title={transaction.customer?.name ?? transaction.order_number}
                                    description={transaction.notes ?? formatDateTime(transaction.created_at)}
                                    className="h-16 w-16"
                                />
                            </div>
                        )}
                    </div>

                    <div className="flex shrink-0 items-center gap-1">
                        <DropdownMenu>
                            <Tooltip>
                                <TooltipTrigger asChild>
                                    <DropdownMenuTrigger asChild>
                                        <Button variant="ghost" size="icon">
                                            <Printer className="h-4 w-4" />
                                        </Button>
                                    </DropdownMenuTrigger>
                                </TooltipTrigger>
                                <TooltipContent side="top">Cetak Struk</TooltipContent>
                            </Tooltip>
                            <DropdownMenuContent align="end">
                                <DropdownMenuItem
                                    onClick={() => onPrint(transaction, 58)}
                                >
                                    Struk 58mm
                                </DropdownMenuItem>
                                <DropdownMenuItem
                                    onClick={() => onPrint(transaction, 80)}
                                >
                                    Struk 80mm
                                </DropdownMenuItem>
                            </DropdownMenuContent>
                        </DropdownMenu>
                        <RowActions
                            actions={[
                                ...(transaction.status === 'pending' && can('orders.update')
                                    ? [
                                        {
                                            label: 'Kirim',
                                            icon: <Send className="h-4 w-4" />,
                                            onClick: () => onUpdateStatus(transaction, 'processing'),
                                        },
                                    ]
                                    : []),
                                ...((transaction.status === 'pending' || transaction.status === 'processing') && can('orders.update')
                                    ? [
                                        {
                                            label: 'Selesai',
                                            icon: <CheckCircle className="h-4 w-4" />,
                                            onClick: () => onUpdateStatus(transaction, 'completed'),
                                        },
                                        {
                                            label: 'Dibatalkan',
                                            icon: <XCircle className="h-4 w-4 text-destructive" />,
                                            onClick: () => onUpdateStatus(transaction, 'cancelled'),
                                        },
                                    ]
                                    : []),
                                ...(transaction.status === 'completed' && can('orders.update')
                                    ? [
                                        {
                                            label: 'Refund',
                                            icon: <XCircle className="h-4 w-4 text-destructive" />,
                                            onClick: () => onUpdateStatus(transaction, 'refunded'),
                                        },
                                    ]
                                    : []),
                                {
                                    label: 'Edit',
                                    icon: <Pencil className="h-4 w-4" />,
                                    show: can('orders.update'),
                                    onClick: () => onEdit(transaction),
                                },
                                {
                                    label: 'Hapus',
                                    icon: (
                                        <Trash2 className="h-4 w-4 text-destructive" />
                                    ),
                                    show: can('orders.delete'),
                                    onClick: () => onDelete(transaction),
                                },
                            ]}
                            wrapperClassName="flex shrink-0 items-center gap-1"
                        />
                    </div>
                </div>
            </CardContent>
        </Card>
    );
}
