import { ChevronDown, Pencil, Trash2 } from 'lucide-react';
import { ImagePreviewButton } from '@/components/dialogs';
import { RowActions } from '@/components/data-display';
import { Button } from '@/components/ui/button';
import { Card, CardContent } from '@/components/ui/card';
import { useCan } from '@/hooks/use-can';
import { formatDateTime, formatNumber } from '@/lib/format';
import { formatCurrency } from '@/lib/utils';
import type { Purchase } from './columns';

export type PurchaseCardRowParams = {
    purchase: Purchase;
    index: number;
    isExpanded: boolean;
    onToggleExpand: () => void;
    onEdit: (purchase: Purchase) => void;
    onDelete: (purchase: Purchase) => void;
};

export function PurchaseCardRow({
    purchase,
    index,
    isExpanded,
    onToggleExpand,
    onEdit,
    onDelete,
}: PurchaseCardRowParams) {
    const { can } = useCan();
    const items = purchase.purchase_items ?? [];
    const variantCount = items.length;
    const rawMaterialName =
        items[0]?.raw_material_price?.raw_material?.name ?? '-';
    const unit = items[0]?.raw_material_price?.raw_material?.unit ?? '';
    const totalQty = items.reduce(
        (sum, item) => sum + Number(item.quantity),
        0,
    );

    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="truncate font-medium">
                                    {purchase.supplier?.name ?? '-'}
                                </h3>
                            </div>

                            <div className="mt-1 text-xs text-muted-foreground">
                                {rawMaterialName}
                                {variantCount > 0 && (
                                    <span className="ml-1">
                                        ({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(purchase.created_at)}
                                </span>
                                {purchase.notes && (
                                    <span className="max-w-[200px] truncate">
                                        {purchase.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)} {unit}
                                </span>
                                <span>
                                    <span className="text-muted-foreground">
                                        Sub:{' '}
                                    </span>
                                    {formatCurrency(purchase.subtotal)}
                                </span>
                                <span>
                                    <span className="text-muted-foreground">
                                        Diskon:{' '}
                                    </span>
                                    {formatCurrency(purchase.discount)}
                                </span>
                                <span>
                                    <span className="text-muted-foreground">
                                        Ongkir:{' '}
                                    </span>
                                    {formatCurrency(purchase.shipping_cost)}
                                </span>
                                <span className="font-semibold">
                                    <span className="font-normal text-muted-foreground">
                                        Total:{' '}
                                    </span>
                                    {formatCurrency(purchase.total)}
                                </span>
                            </div>

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

                        {(can('purchases.update') || can('purchases.delete')) && (
                            <RowActions
                                actions={[
                                    {
                                        label: 'Edit',
                                        icon: <Pencil className="h-4 w-4" />,
                                        show: can('purchases.update'),
                                        onClick: () => onEdit(purchase),
                                    },
                                    {
                                        label: 'Hapus',
                                        icon: (
                                            <Trash2 className="h-4 w-4 text-destructive" />
                                        ),
                                        show: can('purchases.delete'),
                                        onClick: () => onDelete(purchase),
                                    },
                                ]}
                                wrapperClassName="flex shrink-0 items-center gap-1"
                            />
                        )}
                    </div>
                </CardContent>
            </Card>
        </>
    );
}
