import { Link } from '@inertiajs/react';
import {
    CalendarDays,
    Car,
    CheckCircle2,
    ExternalLink,
    MapPin,
    Sparkles,
    User,
    Wrench,
} from 'lucide-react';
import { QRCodeSVG } from 'qrcode.react';
import type { ReactNode } from 'react';
import { StatusBadge } from '@/components/status-badge';
import { useBookingDateTimeFormatters } from '@/hooks/use-booking-timezone';
import {
    formatBookingDate,
    formatBookingTime,
} from '@/lib/booking-timezones';

export type BookingDetail = {
    id: number;
    uuid: string;
    payment_status: string;
    payment_method?: string;
    service_status: string;
    service_type?: 'mobile' | 'fixed' | null;
    scheduled_at: string;
    created_at?: string | null;
    total: number;
    notes?: string | null;
    internal_notes?: string | null;
    vehicle?: {
        make: string;
        model: string;
        year: number;
        size?: string;
        color?: string | null;
    } | null;
    package?: { id: number; name: string } | null;
    location?: {
        name: string;
        address: string | null;
        city: string | null;
        state: string | null;
        zip: string | null;
    } | null;
    service_address?: string | null;
    service_city?: string | null;
    service_state?: string | null;
    service_zip?: string | null;
    customer?: { id: number; name: string; email: string } | null;
    technician?: { id: number; name: string } | null;
    addons?: Array<{ id: number; name: string; pivot: { price: number } }> | null;
};

const SERVICE_STEPS = ['Scheduled', 'In Progress', 'Completed'];
const STATUS_INDEX: Record<string, number> = {
    scheduled: 0,
    in_progress: 1,
    completed: 2,
};

export { formatBookingDate, formatBookingTime };

type BookingDetailPanelProps = {
    booking: BookingDetail;
    customerHref?: string;
    paymentActions?: ReactNode;
    footer?: ReactNode;
    showTracking?: boolean;
};

export function BookingDetailPanel({
    booking,
    customerHref,
    paymentActions,
    footer,
    showTracking = true,
}: BookingDetailPanelProps) {
    const { formatDate, formatTime } = useBookingDateTimeFormatters();
    const trackUrl =
        typeof window !== 'undefined'
            ? `${window.location.origin}/track/${booking.uuid}`
            : `/track/${booking.uuid}`;

    return (
        <div className="flex flex-col gap-4">
            <div className="flex flex-wrap items-center gap-x-8 gap-y-3 rounded-2xl border bg-muted/30 px-6 py-4 text-sm">
                <div>
                    <p className="text-xs text-muted-foreground">Status</p>
                    <StatusBadge status={booking.service_status} />
                </div>
                <div>
                    <p className="text-xs text-muted-foreground">Booking #</p>
                    <p className="font-mono font-medium">
                        {booking.uuid.slice(0, 8).toUpperCase()}
                    </p>
                </div>
                <div>
                    <p className="text-xs text-muted-foreground">Date</p>
                    <p className="font-medium">
                        {formatDate(booking.scheduled_at)}
                    </p>
                </div>
                {booking.created_at ? (
                    <div>
                        <p className="text-xs text-muted-foreground">Booked</p>
                        <p className="font-medium">
                            {new Date(booking.created_at).toLocaleString('en-US', {
                                month: 'short',
                                day: 'numeric',
                                year: 'numeric',
                                hour: 'numeric',
                                minute: '2-digit',
                            })}
                        </p>
                    </div>
                ) : null}
                {booking.vehicle ? (
                    <div>
                        <p className="text-xs text-muted-foreground">Vehicle</p>
                        <p className="font-medium capitalize">
                            {booking.vehicle.size ?? booking.vehicle.make}
                        </p>
                        <p className="text-xs text-muted-foreground">
                            {booking.vehicle.make} {booking.vehicle.model}
                        </p>
                    </div>
                ) : null}
                <div className="ml-auto">
                    <p className="text-xs text-muted-foreground">Total</p>
                    <p className="text-lg font-bold">
                        ${(booking.total / 100).toFixed(2)}
                    </p>
                </div>
            </div>

            <div className="divide-y rounded-2xl border bg-card">
                {booking.customer ? (
                    <div className="flex items-start gap-4 p-5">
                        <div className="flex size-8 shrink-0 items-center justify-center rounded-lg bg-muted">
                            <User className="size-4 text-muted-foreground" />
                        </div>
                        <div>
                            <p className="text-xs font-semibold tracking-wider text-muted-foreground uppercase">
                                Customer
                            </p>
                            {customerHref ? (
                                <Link
                                    href={customerHref}
                                    className="mt-1 block font-medium hover:underline"
                                >
                                    {booking.customer.name}
                                </Link>
                            ) : (
                                <p className="mt-1 font-medium">
                                    {booking.customer.name}
                                </p>
                            )}
                            <p className="text-sm text-muted-foreground">
                                {booking.customer.email}
                            </p>
                        </div>
                    </div>
                ) : null}

                {booking.technician ? (
                    <div className="flex items-start gap-4 p-5">
                        <div className="flex size-8 shrink-0 items-center justify-center rounded-lg bg-muted">
                            <Wrench className="size-4 text-muted-foreground" />
                        </div>
                        <div>
                            <p className="text-xs font-semibold tracking-wider text-muted-foreground uppercase">
                                Technician
                            </p>
                            <p className="mt-1 font-medium">
                                {booking.technician.name}
                            </p>
                        </div>
                    </div>
                ) : null}

                {(() => {
                    if (booking.service_type === 'fixed' && booking.location) {
                        const { name, address, city, state, zip } =
                            booking.location;
                        const full = [address, city, state, zip]
                            .filter(Boolean)
                            .join(', ');

                        return (
                            <div className="flex items-start gap-4 p-5">
                                <div className="flex size-8 shrink-0 items-center justify-center rounded-lg bg-muted">
                                    <MapPin className="size-4 text-muted-foreground" />
                                </div>
                                <div>
                                    <p className="text-xs font-semibold tracking-wider text-muted-foreground uppercase">
                                        Service
                                    </p>
                                    <p className="mt-1 font-medium">{name}</p>
                                    {full ? (
                                        <p className="text-sm text-muted-foreground">
                                            {full}
                                        </p>
                                    ) : null}
                                </div>
                            </div>
                        );
                    }

                    if (booking.service_address) {
                        const parts = [
                            booking.service_address,
                            booking.service_city,
                            booking.service_state,
                            booking.service_zip,
                        ].filter(Boolean);

                        return (
                            <div className="flex items-start gap-4 p-5">
                                <div className="flex size-8 shrink-0 items-center justify-center rounded-lg bg-muted">
                                    <MapPin className="size-4 text-muted-foreground" />
                                </div>
                                <div>
                                    <p className="text-xs font-semibold tracking-wider text-muted-foreground uppercase">
                                        Service
                                    </p>
                                    <p className="mt-1 font-medium">
                                        Mobile service
                                    </p>
                                    <p className="text-sm text-muted-foreground">
                                        {parts.join(', ')}
                                    </p>
                                </div>
                            </div>
                        );
                    }

                    return null;
                })()}

                {booking.vehicle ? (
                    <div className="flex items-start gap-4 p-5">
                        <div className="flex size-8 shrink-0 items-center justify-center rounded-lg bg-muted">
                            <Car className="size-4 text-muted-foreground" />
                        </div>
                        <div>
                            <p className="text-xs font-semibold tracking-wider text-muted-foreground uppercase">
                                Vehicle
                            </p>
                            <p className="mt-1 font-medium capitalize">
                                {booking.vehicle.size ?? booking.vehicle.make}
                            </p>
                            <p className="text-sm text-muted-foreground">
                                {booking.vehicle.make} {booking.vehicle.model}
                            </p>
                        </div>
                    </div>
                ) : null}

                <div className="flex items-start justify-between gap-4 p-5">
                    <div className="flex items-start gap-4">
                        <div className="flex size-8 shrink-0 items-center justify-center rounded-lg bg-muted">
                            <Sparkles className="size-4 text-muted-foreground" />
                        </div>
                        <div>
                            <p className="text-xs font-semibold tracking-wider text-muted-foreground uppercase">
                                Package
                            </p>
                            <p className="mt-1 font-medium">
                                {booking.package?.name ?? 'Car Wash'}
                            </p>
                            {booking.addons && booking.addons.length > 0 ? (
                                <div className="mt-2 space-y-1">
                                    {booking.addons.map((addon) => (
                                        <div key={addon.id} className="flex items-center justify-between gap-4 text-sm text-muted-foreground">
                                            <span>+ {addon.name}</span>
                                            <span className="shrink-0 font-medium text-foreground">
                                                ${(addon.pivot.price / 100).toFixed(2)}
                                            </span>
                                        </div>
                                    ))}
                                </div>
                            ) : null}
                        </div>
                    </div>
                    <p className="shrink-0 font-semibold">
                        ${(booking.total / 100).toFixed(2)}
                    </p>
                </div>

                <div className="flex items-start gap-4 p-5">
                    <div className="flex size-8 shrink-0 items-center justify-center rounded-lg bg-muted">
                        <CalendarDays className="size-4 text-muted-foreground" />
                    </div>
                    <div>
                        <p className="text-xs font-semibold tracking-wider text-muted-foreground uppercase">
                            Date & Time
                        </p>
                        <p className="mt-1 font-medium">
                            {formatDate(booking.scheduled_at)}
                        </p>
                        <p className="text-sm text-muted-foreground">
                            {formatTime(booking.scheduled_at)}
                        </p>
                    </div>
                </div>

                <div className="flex items-start gap-4 p-5">
                    <div className="flex size-8 shrink-0 items-center justify-center rounded-lg bg-muted">
                        <CheckCircle2 className="size-4 text-muted-foreground" />
                    </div>
                    <div>
                        <p className="text-xs font-semibold tracking-wider text-muted-foreground uppercase">
                            Payment
                        </p>
                        <div className="mt-1">
                            <StatusBadge status={booking.payment_status} />
                        </div>
                        {booking.payment_method === 'pay_at_service' ? (
                            <p className="mt-1 text-sm text-muted-foreground">
                                Pay at service
                            </p>
                        ) : null}
                    </div>
                </div>

                {paymentActions ? <div className="px-5 pb-5">{paymentActions}</div> : null}

                {booking.notes ? (
                    <div className="flex items-start gap-4 p-5">
                        <div className="min-w-0 flex-1">
                            <p className="text-xs font-semibold tracking-wider text-muted-foreground uppercase">
                                Special notes
                            </p>
                            <p className="mt-1 text-sm whitespace-pre-wrap">
                                {booking.notes}
                            </p>
                        </div>
                    </div>
                ) : null}

                {booking.internal_notes ? (
                    <div className="flex items-start gap-4 p-5">
                        <div className="min-w-0 flex-1">
                            <p className="text-xs font-semibold tracking-wider text-muted-foreground uppercase">
                                Internal notes
                            </p>
                            <p className="mt-1 text-sm whitespace-pre-wrap">
                                {booking.internal_notes}
                            </p>
                        </div>
                    </div>
                ) : null}
            </div>

            {showTracking ? (
                <div className="flex flex-col items-center gap-4 rounded-2xl border bg-card p-6">
                    <div className="rounded-xl border bg-white p-3 shadow-sm">
                        <QRCodeSVG
                            value={trackUrl}
                            size={160}
                            level="M"
                            marginSize={1}
                        />
                    </div>
                    <div className="text-center">
                        <p className="font-medium">Check-in QR code</p>
                        <p className="mt-0.5 text-sm text-muted-foreground">
                            Show this at the location to check in instantly
                        </p>
                    </div>
                    <a
                        href={trackUrl}
                        target="_blank"
                        rel="noopener noreferrer"
                        className="flex items-center gap-1.5 text-xs text-primary underline-offset-4 hover:underline"
                    >
                        Open tracking page
                        <ExternalLink className="size-3" />
                    </a>
                </div>
            ) : null}

            <div className="rounded-2xl border bg-card p-6">
                <div className="relative flex justify-between">
                    <div className="absolute top-3 right-0 left-0 -z-10 h-0.5 bg-muted" />
                    {SERVICE_STEPS.map((step, index) => {
                        const currentIdx =
                            STATUS_INDEX[booking.service_status] ?? -1;
                        const done = index <= currentIdx;
                        const current = index === currentIdx;

                        return (
                            <div
                                key={step}
                                className="flex flex-col items-center gap-2"
                            >
                                <div
                                    className={`flex size-6 items-center justify-center rounded-full text-xs font-bold ${done ? 'bg-primary text-primary-foreground' : 'bg-muted text-muted-foreground'}`}
                                >
                                    {done ? '✓' : index + 1}
                                </div>
                                <span
                                    className={`text-xs font-medium ${current ? 'text-foreground' : 'text-muted-foreground'}`}
                                >
                                    {step}
                                </span>
                            </div>
                        );
                    })}
                </div>
            </div>

            {footer ? <div>{footer}</div> : null}
        </div>
    );
}
