import { Head, router } from '@inertiajs/react';
import { CalendarDays, MapPin, RefreshCw, Sparkles, User, Wrench } from 'lucide-react';
import { useEffect } from 'react';
import { StatusBadge } from '@/components/status-badge';
import { VehicleSizeCategoryIcon } from '@/components/vehicle-size-category-icon';
import { useBookingDateTimeFormatters } from '@/hooks/use-booking-timezone';

type StatusLog = {
    status: string;
    note: string | null;
    created_at: string;
};

type BookingTrack = {
    uuid: string;
    payment_status: string;
    service_status: string;
    scheduled_at: string;
    service_type: string;
    technician_name: string | null;
    package_name: string | null;
    customer_name: string | null;
    location_name: string | null;
    total: number | null;
    vehicle_size: string | null;
    vehicle_size_name: string | null;
    vehicle_size_image_url: string | null;
    status_logs: StatusLog[];
};

type Props = {
    booking: BookingTrack;
};

function DetailCell({ label, children }: { label: string; children: React.ReactNode }) {
    return (
        <div className="flex flex-col gap-0.5">
            <span className="text-[10px] font-semibold uppercase tracking-widest text-muted-foreground">
                {label}
            </span>
            <span className="text-xs font-semibold leading-tight">{children}</span>
        </div>
    );
}

const SERVICE_STATUS_ORDER = [
    'scheduled',
    'confirmed',
    'en_route',
    'arrived',
    'in_progress',
    'completed',
    'cancelled',
];

function serviceStatusStep(status: string): number {
    const idx = SERVICE_STATUS_ORDER.indexOf(status);

    return idx === -1 ? 0 : idx;
}

function ServiceProgressBar({ status }: { status: string }) {
    const step = serviceStatusStep(status);
    const isCancelled = status === 'cancelled';
    const totalSteps = 5; // scheduled → completed (0–5)
    const pct = isCancelled ? 100 : Math.round((step / totalSteps) * 100);
    const labels = ['Scheduled', 'Confirmed', 'En Route', 'Arrived', 'In Progress', 'Done'];

    return (
        <div className="flex flex-col gap-2">
            <div className="h-1.5 w-full overflow-hidden rounded-full bg-muted">
                <div
                    className={`h-full rounded-full transition-all duration-700 ${isCancelled ? 'bg-destructive' : 'bg-primary'}`}
                    style={{ width: `${pct}%` }}
                />
            </div>
            <div className="flex justify-between">
                {labels.map((label, i) => (
                    <span
                        key={label}
                        className={`text-[9px] font-medium uppercase tracking-wide ${
                            i <= step && !isCancelled
                                ? 'text-primary'
                                : 'text-muted-foreground/50'
                        }`}
                    >
                        {label}
                    </span>
                ))}
            </div>
        </div>
    );
}

export default function TrackShow({ booking }: Props) {
    const { formatDate, formatTime } = useBookingDateTimeFormatters();

    useEffect(() => {
        const id = window.setInterval(() => {
            router.reload({ only: ['booking'] });
        }, 15000);

        return () => window.clearInterval(id);
    }, []);

    const dateStr = formatDate(booking.scheduled_at);
    const timeStr = formatTime(booking.scheduled_at);

    return (
        <>
            <Head title="Track booking" />

            <div className="flex flex-col items-center gap-6 py-4">

                {/* Header — mirrors complete.tsx style */}
                <div className="relative flex size-16 items-center justify-center">
                    <div className="absolute inset-0 animate-ping rounded-full bg-primary/20"
                        style={{ animationDuration: '2s' }} />
                    <div className="flex size-16 items-center justify-center rounded-full bg-primary/10">
                        <RefreshCw className="size-8 text-primary" strokeWidth={1.5} />
                    </div>
                </div>

                <div className="text-center">
                    <h1 className="text-2xl font-bold tracking-tight">Track Booking</h1>
                    <p className="mt-1 text-sm text-muted-foreground">
                        Live updates every 15 seconds
                    </p>
                    <p className="mt-0.5 font-mono text-xs text-muted-foreground">
                        #{booking.uuid.slice(0, 8)}
                    </p>
                </div>

                <div className="flex flex-wrap items-center justify-center gap-2">
                    <StatusBadge status={booking.payment_status} />
                    <StatusBadge status={booking.service_status} />
                </div>

                {/* Ticket */}
                <div className="relative w-full">
                    <div className="flex flex-col overflow-hidden rounded-2xl border bg-card">

                        {/* TOP — package + progress */}
                        <div className="flex flex-col gap-4 px-5 pb-5 pt-5">
                            <div className="flex items-start justify-between">
                                <div>
                                    <div className="flex items-center gap-1.5 text-primary">
                                        <Sparkles className="size-3.5 shrink-0" />
                                        <span className="text-[11px] font-semibold uppercase tracking-widest">
                                            Car Wash
                                        </span>
                                    </div>
                                    <p className="mt-0.5 text-xl font-bold leading-tight tracking-tight">
                                        {booking.package_name ?? booking.service_type}
                                    </p>
                                    {booking.location_name && (
                                        <div className="mt-1 flex items-center gap-1 text-muted-foreground">
                                            <MapPin className="size-3 shrink-0" />
                                            <span className="text-xs">{booking.location_name}</span>
                                        </div>
                                    )}
                                </div>
                                {booking.technician_name && (
                                    <div className="flex shrink-0 flex-col items-end gap-0.5">
                                        <span className="text-[10px] font-semibold uppercase tracking-widest text-muted-foreground">
                                            Technician
                                        </span>
                                        <div className="flex items-center gap-1">
                                            <Wrench className="size-3 text-muted-foreground" />
                                            <span className="text-xs font-semibold">
                                                {booking.technician_name}
                                            </span>
                                        </div>
                                    </div>
                                )}
                            </div>

                            <ServiceProgressBar status={booking.service_status} />
                        </div>

                        {/* Dashed divider */}
                        <div className="mx-5 border-t-2 border-dashed border-border/60" />

                        {/* BOTTOM — booking details grid */}
                        <div className="grid grid-cols-2 gap-x-4 gap-y-3 px-5 pb-5 pt-4">
                            <DetailCell label="Date">{dateStr}</DetailCell>
                            <DetailCell label="Time">{timeStr}</DetailCell>

                            {booking.customer_name && (
                                <DetailCell label="Customer">
                                    <span className="flex items-center gap-1">
                                        <User className="size-3 shrink-0 text-muted-foreground" />
                                        {booking.customer_name}
                                    </span>
                                </DetailCell>
                            )}

                            {booking.vehicle_size && (
                                <DetailCell label="Vehicle">
                                    <span className="flex items-center gap-1.5">
                                        <VehicleSizeCategoryIcon
                                            imageUrl={booking.vehicle_size_image_url ?? null}
                                            name={booking.vehicle_size_name ?? booking.vehicle_size}
                                            className="size-4"
                                            colorClassName="text-foreground"
                                        />
                                        {booking.vehicle_size_name ?? booking.vehicle_size}
                                    </span>
                                </DetailCell>
                            )}

                            {booking.total !== null && (
                                <DetailCell label="Total">
                                    ${((booking.total ?? 0) / 100).toFixed(2)}
                                </DetailCell>
                            )}

                            <DetailCell label="Ref">
                                <span className="font-mono">{booking.uuid.slice(0, 8)}</span>
                            </DetailCell>
                        </div>
                    </div>
                </div>

                {/* Timeline */}
                {booking.status_logs.length > 0 ? (
                    <div className="w-full">
                        <div className="mb-3 flex items-center gap-2">
                            <CalendarDays className="size-4 shrink-0 text-muted-foreground" />
                            <h2 className="text-sm font-semibold uppercase tracking-widest text-muted-foreground">
                                Timeline
                            </h2>
                        </div>

                        <div className="relative flex flex-col">
                            {/* Vertical connecting line */}
                            <div className="absolute bottom-2 left-[6px] top-2 w-px bg-border" />

                            {booking.status_logs.map((log, index) => (
                                <div
                                    key={`${log.status}-${log.created_at}-${index}`}
                                    className="relative flex gap-4 pb-5 last:pb-0"
                                >
                                    <div
                                        className={`relative z-10 mt-1 size-3 shrink-0 rounded-full border-2 ${
                                            index === 0
                                                ? 'border-primary bg-primary'
                                                : 'border-border bg-background'
                                        }`}
                                    />
                                    <div className="flex flex-col gap-1">
                                        <div className="flex flex-wrap items-center gap-2">
                                            <StatusBadge status={log.status} />
                                            <span className="text-[11px] text-muted-foreground">
                                                {new Date(log.created_at).toLocaleString('en-US', {
                                                    month: 'short',
                                                    day: 'numeric',
                                                    hour: 'numeric',
                                                    minute: '2-digit',
                                                })}
                                            </span>
                                        </div>
                                        {log.note && (
                                            <p className="text-xs text-muted-foreground">
                                                {log.note}
                                            </p>
                                        )}
                                    </div>
                                </div>
                            ))}
                        </div>
                    </div>
                ) : (
                    <div className="w-full rounded-2xl border border-dashed p-6 text-center">
                        <p className="text-sm text-muted-foreground">No status updates yet.</p>
                    </div>
                )}

            </div>
        </>
    );
}
