import { Head, Link } from '@inertiajs/react';
import { QRCodeSVG } from 'qrcode.react';
import { CalendarCheck, CheckCircle2, ExternalLink, Home, LayoutDashboard, MapPin, Sparkles } from 'lucide-react';
import { VehicleSizeCategoryIcon } from '@/components/vehicle-size-category-icon';
import { StatusBadge } from '@/components/status-badge';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { home, dashboard } from '@/routes';

type Props = {
    bookingUuid: string | null;
    paymentStatus: string | null;
    serviceStatus: string | null;
    paymentMethod: string | null;
    total: number | null;
    scheduledAt?: string | null;
    createdAt?: string | null;
    packageName?: string | null;
    customerName?: string | null;
    vehicleSize?: string | null;
    vehicleSizeName?: string | null;
    vehicleSizeImageUrl?: string | null;
    locationName?: string | null;
};

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>
    );
}

export default function BookingComplete({
    bookingUuid,
    paymentStatus,
    serviceStatus,
    paymentMethod,
    total,
    scheduledAt,
    packageName,
    customerName,
    vehicleSize,
    vehicleSizeName,
    vehicleSizeImageUrl,
    locationName,
    createdAt,
}: Props) {
    const isPaid = paymentStatus === 'paid';
    const isPayAtService = paymentMethod === 'pay_at_service';

    const title = isPaid || isPayAtService ? 'Booking Confirmed!' : 'Payment Processing';
    const description = isPaid
        ? 'Your booking is confirmed and payment has been received.'
        : isPayAtService
          ? `Your appointment is scheduled. Payment of $${((total ?? 0) / 100).toFixed(2)} will be collected in person.`
          : 'Your payment is being finalized. This page will update automatically.';

    const trackingUrl = bookingUuid
        ? `${window.location.origin}/track/${bookingUuid}`
        : null;

    const dateStr = scheduledAt
        ? new Date(scheduledAt).toLocaleDateString('en-US', {
              weekday: 'short',
              month: 'short',
              day: 'numeric',
          })
        : null;
    const timeStr = scheduledAt
        ? new Date(scheduledAt).toLocaleTimeString('en-US', {
              hour: 'numeric',
              minute: '2-digit',
          })
        : null;

    // QR section height: pt-6(24) + QR(168) + gap-3(12) + text(16) + pb-5(20) = 240px
    const DIVIDER_TOP = 240;

    return (
        <>
            <Head title="Booking confirmed" />

            <div className="flex flex-col items-center gap-6 py-4">
                {/* Success icon */}
                <div className="relative flex size-16 items-center justify-center">
                    <div
                        className="absolute inset-0 animate-ping rounded-full bg-primary/20"
                        style={{ animationIterationCount: 2 }}
                    />
                    <div className="flex size-16 items-center justify-center rounded-full bg-primary/10">
                        <CheckCircle2 className="size-8 text-primary" strokeWidth={1.5} />
                    </div>
                </div>

                {/* Title + description */}
                <div className="text-center">
                    <h1 className="text-2xl font-bold tracking-tight">{title}</h1>
                    <p className="mt-1 text-sm text-muted-foreground">{description}</p>
                </div>

                {/* Status badges */}
                <div className="flex flex-wrap items-center justify-center gap-2">
                    {paymentStatus ? <StatusBadge status={paymentStatus} /> : null}
                    {serviceStatus ? <StatusBadge status={serviceStatus} /> : null}
                    {isPayAtService ? (
                        <Badge variant="outline" className="flex items-center gap-1">
                            <CalendarCheck className="size-3" />
                            Pay at service
                        </Badge>
                    ) : null}
                </div>

                {/* Portrait ticket */}
                <div className="relative w-full max-w-sm">
                    {/* Cutout circles at left/right of horizontal divider */}
                    <div
                        className="absolute left-0 z-10 size-5 -translate-x-1/2 -translate-y-1/2 rounded-full border border-border bg-background"
                        style={{ top: DIVIDER_TOP }}
                    />
                    <div
                        className="absolute right-0 z-10 size-5 translate-x-1/2 -translate-y-1/2 rounded-full border border-border bg-background"
                        style={{ top: DIVIDER_TOP }}
                    />

                    <div className="flex flex-col overflow-hidden rounded-2xl border bg-card">
                        {/* TOP — QR code */}
                        <div className="flex flex-col items-center gap-3 px-6 pb-5 pt-6">
                            {trackingUrl ? (
                                <QRCodeSVG
                                    value={trackingUrl}
                                    size={168}
                                    level="M"
                                    marginSize={1}
                                    className="rounded"
                                />
                            ) : (
                                <div className="size-[168px] rounded bg-muted" />
                            )}
                            <span className="text-xs text-muted-foreground">
                                Scan to track your booking
                            </span>
                        </div>

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

                        {/* BOTTOM — booking details */}
                        <div className="flex flex-col gap-4 px-5 pb-5 pt-4">
                            {/* Package + location header */}
                            <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">
                                    {packageName ?? 'Booking'}
                                </p>
                                {locationName && (
                                    <div className="mt-1 flex items-center gap-1 text-muted-foreground">
                                        <MapPin className="size-3 shrink-0" />
                                        <span className="text-xs">{locationName}</span>
                                    </div>
                                )}
                            </div>

                            {/* Detail grid */}
                            <div className="grid grid-cols-2 gap-x-4 gap-y-3">
                                {dateStr && (
                                    <DetailCell label="Date">{dateStr}</DetailCell>
                                )}
                                {timeStr && (
                                    <DetailCell label="Time">{timeStr}</DetailCell>
                                )}
                                {customerName && (
                                    <DetailCell label="Customer">{customerName}</DetailCell>
                                )}
                                {vehicleSize && (
                                    <DetailCell label="Vehicle">
                                        <span className="flex items-center gap-1.5">
                                            <VehicleSizeCategoryIcon
                                                imageUrl={vehicleSizeImageUrl ?? null}
                                                name={vehicleSizeName ?? vehicleSize}
                                                className="size-4"
                                                colorClassName="text-foreground"
                                            />
                                            {vehicleSizeName ?? vehicleSize}
                                        </span>
                                    </DetailCell>
                                )}
                                {total !== null && (
                                    <DetailCell label="Total">
                                        ${(total / 100).toFixed(2)}
                                    </DetailCell>
                                )}
                                {bookingUuid && (
                                    <DetailCell label="Ref">
                                        <span className="font-mono">
                                            {bookingUuid.slice(0, 8)}
                                        </span>
                                    </DetailCell>
                                )}
                                {createdAt && (
                                    <DetailCell label="Booked on">
                                        {new Date(createdAt).toLocaleString('en-US', {
                                            month: 'short',
                                            day: 'numeric',
                                            year: 'numeric',
                                            hour: 'numeric',
                                            minute: '2-digit',
                                        })}
                                    </DetailCell>
                                )}
                            </div>
                        </div>
                    </div>
                </div>

                {/* Tracking link */}
                {trackingUrl && (
                    <a
                        href={trackingUrl}
                        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 className="grid w-full max-w-lg grid-cols-1 gap-3 sm:grid-cols-2">
                    <Button className="w-full" asChild>
                        <Link href={dashboard.url()}>
                            <LayoutDashboard className="size-4" />
                            Dashboard
                        </Link>
                    </Button>

                    <Button variant="outline" className="w-full" asChild>
                        <Link href={home.url()}>
                            <Home className="size-4" />
                            Back to home
                        </Link>
                    </Button>
                </div>
            </div>
        </>
    );
}
