import { ChevronDown } from 'lucide-react';
import { useState, type ReactNode } from 'react';
import type { BookingDetail } from '@/components/booking/booking-detail-panel';
import { StatusBadge } from '@/components/status-badge';
import { useBookingDateTimeFormatters } from '@/hooks/use-booking-timezone';
import { serviceStatusBorderClass } from '@/lib/service-status-border';
import { cn } from '@/lib/utils';

export type BookingListCardData = {
    uuid: string;
    service_status: string;
    scheduled_at: string;
    created_at?: string | null;
    total: number;
    package?: { name: string } | null;
    package_name?: string | null;
    vehicle?: {
        make: string;
        model: string;
        size?: string | null;
    } | null;
    vehicle_label?: string | null;
    payment_status?: string;
    addons?: Array<{ id: number; name: string; pivot: { price: number } }> | null;
};

type BookingListCardProps = {
    booking: BookingListCardData;
    highlight?: boolean;
    defaultOpen?: boolean;
    onViewDetails?: () => void;
    onEditBooking?: () => void;
    editBookingLabel?: string;
    footer?: ReactNode;
};

function packageName(booking: BookingListCardData): string {
    return booking.package?.name ?? booking.package_name ?? 'Car Wash';
}

function fmtBooked(iso: string) {
    const d = new Date(iso);
    const m = String(d.getMonth() + 1).padStart(2, '0');
    const day = String(d.getDate()).padStart(2, '0');
    const y = String(d.getFullYear()).slice(-2);
    const raw = d.getHours();
    const ampm = raw >= 12 ? 'pm' : 'am';
    const h = raw % 12 || 12;
    const min = String(d.getMinutes()).padStart(2, '0');

    return `${m}-${day}-${y} ${h}:${min}${ampm}`;
}

export function BookingListCard({
    booking,
    highlight = false,
    defaultOpen = false,
    onViewDetails,
    onEditBooking,
    editBookingLabel = 'Edit booking',
    footer,
}: BookingListCardProps) {
    const [open, setOpen] = useState(defaultOpen);
    const { formatDate, formatTime } = useBookingDateTimeFormatters();

    const vehicleSize = booking.vehicle?.size ?? booking.vehicle?.make ?? null;
    const vehicleLabel = booking.vehicle
        ? `${booking.vehicle.make} ${booking.vehicle.model}`
        : booking.vehicle_label ?? null;

    const addonTotal = (booking.addons ?? []).reduce((sum, a) => sum + a.pivot.price, 0);
    const packagePrice = booking.total - addonTotal;

    return (
        <div
            className={cn(
                'overflow-hidden rounded-2xl border border-border border-l-[3px] bg-card shadow-sm',
                serviceStatusBorderClass(booking.service_status),
            )}
        >
            {/* ── Collapsed header ── */}
            <button
                type="button"
                onClick={() => setOpen((v) => !v)}
                className="w-full bg-muted/40 px-4 py-3 text-sm transition-colors hover:bg-muted/60"
            >
                {/* Row 1: status + total + chevron */}
                <div className="flex items-start justify-between gap-2">
                    <div className="flex flex-col items-start gap-1">
                        <StatusBadge status={booking.service_status} />
                        <p className="font-mono text-xs text-muted-foreground">
                            #{booking.uuid.slice(0, 8).toUpperCase()}
                        </p>
                    </div>
                    <div className="flex items-center gap-2">
                        <p className={cn('font-bold', highlight ? 'text-primary' : 'text-foreground')}>
                            ${(booking.total / 100).toFixed(2)}
                        </p>
                        <ChevronDown
                            className={cn(
                                'size-4 shrink-0 text-muted-foreground transition-transform duration-200',
                                open && 'rotate-180',
                            )}
                        />
                    </div>
                </div>

                {/* Row 2: 2×2 grid — Package | Vehicle, Date | Time */}
                <div className="mt-3 grid grid-cols-2 gap-2 text-left">
                    <div>
                        <p className="text-xs text-muted-foreground">Package</p>
                        <p className="truncate text-sm font-medium">{packageName(booking)}</p>
                    </div>
                    <div>
                        <p className="text-xs text-muted-foreground">Vehicle</p>
                        {vehicleSize ? (
                            <>
                                <p className="text-sm font-medium capitalize">{vehicleSize}</p>
                                {vehicleLabel ? (
                                    <p className="truncate text-xs text-muted-foreground">{vehicleLabel}</p>
                                ) : null}
                            </>
                        ) : (
                            <p className="text-sm font-medium text-muted-foreground">—</p>
                        )}
                    </div>
                    <div>
                        <p className="text-xs text-muted-foreground">Date</p>
                        <p className="text-sm font-medium">{formatDate(booking.scheduled_at)}</p>
                    </div>
                    <div>
                        <p className="text-xs text-muted-foreground">Time</p>
                        <p className="text-sm font-medium">{formatTime(booking.scheduled_at)}</p>
                    </div>
                </div>
            </button>

            {/* ── Expanded body ── */}
            {open ? (
                <div className="border-t px-4 py-3">
                    {/* Package + add-ons breakdown */}
                    <div className="space-y-1">
                        <div className="flex items-start justify-between gap-2">
                            <div>
                                <p className="text-xs font-medium uppercase tracking-wide text-muted-foreground">Package</p>
                                <p className="font-semibold">{packageName(booking)}</p>
                            </div>
                            <p className="shrink-0 font-medium">${(packagePrice / 100).toFixed(2)}</p>
                        </div>
                        {(booking.addons ?? []).map((addon) => (
                            <div key={addon.id} className="flex items-center justify-between gap-2">
                                <p className="text-sm text-muted-foreground">+ {addon.name}</p>
                                <p className="shrink-0 text-sm text-muted-foreground">
                                    ${(addon.pivot.price / 100).toFixed(2)}
                                </p>
                            </div>
                        ))}
                    </div>

                    {/* Booked + payment status */}
                    {(booking.created_at || booking.payment_status) ? (
                        <div className="mt-3 flex flex-wrap items-center justify-between gap-2 border-t pt-3">
                            {booking.created_at ? (
                                <p className="text-xs text-muted-foreground">
                                    Booked {fmtBooked(booking.created_at)}
                                </p>
                            ) : null}
                            {booking.payment_status ? (
                                <StatusBadge status={booking.payment_status} />
                            ) : null}
                        </div>
                    ) : null}

                    {/* Action buttons */}
                    {(onEditBooking || onViewDetails) ? (
                        <div className="mt-3 flex flex-col gap-2">
                            {onEditBooking ? (
                                <button
                                    type="button"
                                    onClick={onEditBooking}
                                    className="w-full rounded-lg bg-primary px-3 py-2 text-sm font-semibold text-primary-foreground transition-colors hover:bg-primary/90"
                                >
                                    {editBookingLabel}
                                </button>
                            ) : null}
                            {onViewDetails ? (
                                <button
                                    type="button"
                                    onClick={onViewDetails}
                                    className="w-full rounded-lg border px-3 py-2 text-sm font-medium transition-colors hover:bg-muted"
                                >
                                    View details
                                </button>
                            ) : null}
                        </div>
                    ) : null}

                    {footer ? (
                        <div className="mt-3 flex flex-wrap gap-2 border-t border-border pt-3">
                            {footer}
                        </div>
                    ) : null}
                </div>
            ) : null}
        </div>
    );
}
