import { ClipboardCheck, ChevronDown, Pencil, Send, Trash2, XCircle } from 'lucide-react';
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 { useCan } from '@/hooks/use-can';
import { formatDateTime, formatNumber } from '@/lib/format';
import type { StokOpname, StokOpnameStatus } from './columns';

const STATUS_CONFIG: Record<StokOpnameStatus, { label: string; className: string }> = {
    draft: { label: 'Draft', className: 'bg-gray-100 text-gray-800 hover:bg-gray-100' },
    in_progress: { label: 'Diajukan', className: 'bg-blue-100 text-blue-800 hover:bg-blue-100' },
    completed: { label: 'Selesai', className: 'bg-yellow-100 text-yellow-800 hover:bg-yellow-100' },
    verified: { label: 'Terverifikasi', className: 'bg-green-100 text-green-800 hover:bg-green-100' },
    cancelled: { label: 'Dibatalkan', className: 'bg-red-100 text-red-800 hover:bg-red-100' },
};

export type StokOpnameCardRowParams = {
    stokOpname: StokOpname;
    index: number;
    isExpanded: boolean;
    onToggleExpand: () => void;
    onEdit: (stokOpname: StokOpname) => void;
    onDelete: (stokOpname: StokOpname) => void;
    onSubmit: (stokOpname: StokOpname) => void;
    onVerify: (stokOpname: StokOpname) => void;
    onReject: (stokOpname: StokOpname) => void;
    onCancel: (stokOpname: StokOpname) => void;
};

export function StokOpnameCardRow({
    stokOpname,
    index,
    isExpanded,
    onToggleExpand,
    onEdit,
    onDelete,
    onSubmit,
    onVerify,
    onReject,
    onCancel,
}: StokOpnameCardRowParams) {
    const { can } = useCan();
    const variantCount = stokOpname.items_count ?? 0;
    const totalDifference = stokOpname.total_difference ?? 0;
    const productNamesStr = stokOpname.product_names ?? '';
    const productNames = productNamesStr ? productNamesStr.split(', ') : [];
    const statusConfig = STATUS_CONFIG[stokOpname.status] ?? STATUS_CONFIG.draft;

    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>
                                {productNames.length > 0
                                    ? productNames.join(', ')
                                    : '-'}
                            </h3>
                            <Badge
                                variant="secondary"
                                className={statusConfig.className}
                            >
                                {statusConfig.label}
                            </Badge>
                        </div>

                        <div className="mt-1 text-xs text-muted-foreground">
                            {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(stokOpname.opname_date)}
                            </span>
                            <span className="text-muted-foreground">
                                Oleh:{' '}
                                <span className="font-medium text-foreground">
                                    {stokOpname.created_by?.user_profile
                                        ?.full_name ?? '-'}
                                </span>
                            </span>
                            {stokOpname.notes && (
                                <span className="max-w-[200px] truncate">
                                    {stokOpname.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">
                                    Total Selisih:{' '}
                                </span>
                                <span className={totalDifference > 0 ? 'text-green-600 font-medium' : totalDifference < 0 ? 'text-red-600 font-medium' : ''}>
                                    {totalDifference > 0 ? '+' : ''}{formatNumber(totalDifference)}
                                </span>
                            </span>
                            {stokOpname.verified_by && (
                                <span className="text-muted-foreground">
                                    Diverifikasi oleh:{' '}
                                    <span className="font-medium text-foreground">
                                        {stokOpname.verified_by?.user_profile
                                            ?.full_name ?? '-'}
                                    </span>
                                </span>
                            )}
                        </div>
                    </div>

                    <div className="flex shrink-0 items-center gap-1">
                        {can('stok_opnames.update') && stokOpname.status === 'draft' && (
                            <RowActions
                                actions={[
                                    {
                                        label: 'Edit',
                                        icon: <Pencil className="h-4 w-4" />,
                                        show: true,
                                        onClick: () => onEdit(stokOpname),
                                    },
                                    {
                                        label: 'Submit',
                                        icon: <Send className="h-4 w-4" />,
                                        show: can('stok_opnames.submit'),
                                        onClick: () => onSubmit(stokOpname),
                                    },
                                    {
                                        label: 'Hapus',
                                        icon: <Trash2 className="h-4 w-4 text-destructive" />,
                                        show: can('stok_opnames.delete'),
                                        onClick: () => onDelete(stokOpname),
                                    },
                                ]}
                            />
                        )}
                        {can('stok_opnames.submit') && stokOpname.status === 'in_progress' && (
                            <RowActions
                                actions={[
                                    {
                                        label: 'Batal',
                                        icon: <XCircle className="h-4 w-4 text-destructive" />,
                                        show: true,
                                        onClick: () => onCancel(stokOpname),
                                    },
                                ]}
                            />
                        )}
                        {can('stok_opnames.verify') && stokOpname.status === 'in_progress' && (
                            <RowActions
                                actions={[
                                    {
                                        label: 'Verifikasi',
                                        icon: <ClipboardCheck className="h-4 w-4" />,
                                        show: true,
                                        onClick: () => onVerify(stokOpname),
                                    },
                                    {
                                        label: 'Tolak',
                                        icon: <XCircle className="h-4 w-4 text-destructive" />,
                                        show: true,
                                        onClick: () => onReject(stokOpname),
                                    },
                                ]}
                            />
                        )}
                    </div>
                </div>
            </CardContent>
        </Card>
    );
}
