import { Head, Link, usePage } from '@inertiajs/react';
import {
    ArrowRight,
    CalendarDays,
    Check,
    CircleCheck,
    Clock3,
    Copy,
    Mail,
    MapPin,
    Navigation,
    Phone,
    Plane,
    ShieldCheck,
    UserRound,
} from 'lucide-react';
import { useState } from 'react';
import SiteFooter from '@/components/home/site-footer';
import SiteHeader from '@/components/home/site-header';
import { dashboard, home } from '@/routes';
import type { BookingSummary } from '@/types/booking';

function formatMoney(value: string): string {
    return value;
}

export default function BookingConfirmation({ booking }: { booking: BookingSummary }) {
    const { auth } = usePage().props;
    const [copied, setCopied] = useState(false);
    const pickupTime = new Date(booking.pickup_at_iso);
    const journeyDuration = booking.duration_minutes ?? (booking.hours ? booking.hours * 60 : 180);
    const isActive = booking.status === 'confirmed' && pickupTime <= new Date() && new Date() <= new Date(pickupTime.getTime() + journeyDuration * 60_000);
    const dateLabel = new Intl.DateTimeFormat('en-US', {
        weekday: 'long', month: 'short', day: 'numeric', year: 'numeric',
        timeZone: booking.timezone,
    }).format(pickupTime);
    const timeLabel = new Intl.DateTimeFormat('en-US', {
        hour: '2-digit', minute: '2-digit',
        timeZone: booking.timezone,
    }).format(pickupTime);

    const copyReference = async () => {
        await navigator.clipboard.writeText(booking.reference);
        setCopied(true);
        window.setTimeout(() => setCopied(false), 1800);
    };

    const specialRequests = booking.special_requests;
    const selectedRequests = specialRequests
        ? [
              specialRequests.quiet_ride && 'Quiet ride',
              specialRequests.temperature && `${specialRequests.temperature} cabin temperature`,
              specialRequests.wheelchair_storage && 'Wheelchair storage',
              specialRequests.assisted_boarding && 'Assisted boarding',
              specialRequests.chilled_water && 'Chilled water',
              specialRequests.fast_charging && 'Fast charging',
              specialRequests.meet_greet_name && `Meet & greet: ${specialRequests.meet_greet_name}`,
              specialRequests.directives,
          ].filter(Boolean) as string[]
        : [];

    return (
        <>
            <Head title={`Booking Confirmation · ${booking.reference}`} />
            <div className="min-h-screen bg-mist font-google text-navy dark:bg-ink dark:text-white">
                <SiteHeader variant="solid" />
                <main className="mx-auto max-w-7xl px-4 pt-10 pb-20 sm:px-6 lg:px-10 lg:pt-14">
                    <div className="flex flex-wrap items-center justify-between gap-4">
                        <Link href={auth.user ? dashboard() : home()} className="rounded-lg bg-[#f4f0e9] px-5 py-3 text-sm font-semibold transition-colors hover:bg-gold/15 dark:bg-white/10">
                            ← Go back
                        </Link>
                        <p className="text-xs text-navy/55 dark:text-white/55">Home / Booking / Confirmation</p>
                    </div>
                    <h1 className="mt-8 text-4xl font-semibold tracking-tight sm:text-6xl">Booking Confirmation</h1>

                    <section className="mt-8 flex flex-col gap-5 rounded-2xl bg-white p-6 shadow-[0_8px_30px_-16px_rgba(11,31,51,0.18)] sm:flex-row sm:items-center sm:justify-between sm:p-8 dark:bg-ocean dark:shadow-none">
                        <div className="flex items-center gap-4">
                            <span className="flex size-14 shrink-0 items-center justify-center rounded-2xl bg-green-100 text-green-700 dark:bg-green-400/15 dark:text-green-300"><CircleCheck className="size-7" /></span>
                            <div>
                                <div className="flex flex-wrap items-center gap-3"><h2 className="text-xl font-bold sm:text-2xl">Booking Confirmed</h2><span className="rounded-full bg-green-100 px-3 py-1 text-xs font-semibold text-green-800 dark:bg-green-400/15 dark:text-green-200">{booking.status_label}</span></div>
                                <p className="mt-1 flex flex-wrap items-center gap-1.5 text-sm text-navy/65 dark:text-white/65"><Mail className="size-4" />Confirmation sent to <strong className="text-navy dark:text-white">{booking.contact_email}</strong></p>
                            </div>
                        </div>
                        <div className="flex items-center justify-between gap-5 rounded-xl border border-navy/10 bg-[#f7f5f3] px-4 py-3 dark:border-white/10 dark:bg-ink">
                            <div><p className="text-[11px] font-bold tracking-wider text-navy/55 uppercase dark:text-white/55">Reservation code</p><p className="text-xl font-bold tracking-wide">{booking.reference}</p></div>
                            <button type="button" onClick={copyReference} className="inline-flex items-center gap-2 rounded-lg border border-navy/15 bg-white px-3 py-2 text-sm font-semibold dark:border-white/20 dark:bg-ocean">{copied ? <Check className="size-4 text-green-600" /> : <Copy className="size-4" />}{copied ? 'Copied' : 'Copy'}</button>
                        </div>
                    </section>

                    <div className="mt-4 grid items-start gap-4 lg:grid-cols-[minmax(0,1fr)_minmax(330px,0.48fr)]">
                        <div className="space-y-4">
                            <section className="rounded-2xl bg-white p-6 shadow-sm dark:bg-ocean">
                                <h2 className="text-lg font-bold">Chauffeur & Vehicle</h2>
                                <div className="mt-4 grid gap-3 sm:grid-cols-2">
                                    <div className="flex items-center gap-3 rounded-xl bg-[#faf8f5] p-4 dark:bg-ink"><span className="flex size-12 shrink-0 items-center justify-center rounded-xl bg-white text-blue-700 dark:bg-white/10 dark:text-blue-300"><UserRound className="size-6" /></span><div><p className="font-semibold">Chauffeur assignment</p><p className="mt-1 text-xs text-navy/65 dark:text-white/65">Your chauffeur details will appear closer to pickup.</p></div></div>
                                    <div className="flex items-center gap-3 rounded-xl bg-[#faf8f5] p-4 dark:bg-ink"><span className="size-12 shrink-0 overflow-hidden rounded-xl bg-white dark:bg-white/10"><img src={booking.vehicle_image} alt={booking.vehicle} className="size-full object-cover" /></span><div><p className="font-semibold">{booking.vehicle}</p><p className="mt-1 text-xs text-navy/65 dark:text-white/65">Selected vehicle · chauffeur service</p></div></div>
                                </div>
                            </section>

                            <section className="rounded-2xl bg-white p-6 shadow-sm dark:bg-ocean">
                                <div className="flex flex-wrap items-center justify-between gap-3"><h2 className="text-lg font-bold">Journey Itinerary</h2><span className="flex items-center gap-2 text-sm text-navy/65 dark:text-white/65"><CalendarDays className="size-4" />{dateLabel}</span></div>
                                <div className="relative mt-6 space-y-7 before:absolute before:top-2 before:bottom-2 before:left-[7px] before:w-px before:bg-navy/15 dark:before:bg-white/20">
                                    <div className="relative flex gap-4"><span className="z-10 mt-1 size-4 shrink-0 rounded-full border-4 border-white bg-navy dark:border-ocean dark:bg-white" /><div className="min-w-0 flex-1"><div className="flex flex-wrap justify-between gap-2"><p className="text-xs font-bold tracking-wide text-blue-700 uppercase dark:text-blue-300">Pickup · {timeLabel}</p>{booking.flight_details && <span className="flex items-center gap-1 text-xs text-navy/60 dark:text-white/60"><Plane className="size-3.5" />Flight {booking.flight_details}</span>}</div><p className="mt-1 font-semibold">{booking.pickup}</p><p className="mt-1 text-sm text-navy/60 dark:text-white/60">{booking.passengers} passengers · {booking.bags} checked bags</p></div></div>
                                    {booking.destination && <div className="relative flex gap-4"><span className="z-10 mt-1 size-4 shrink-0 rounded-full border-4 border-white bg-green-600 dark:border-ocean dark:bg-green-400" /><div className="min-w-0 flex-1"><p className="text-xs font-bold tracking-wide text-green-700 uppercase dark:text-green-300">Drop-off</p><p className="mt-1 font-semibold">{booking.destination}</p>{booking.duration && <p className="mt-1 text-sm text-navy/60 dark:text-white/60">Estimated journey: {booking.duration} · {booking.distance}</p>}</div></div>}
                                </div>
                                <div className="mt-6 grid gap-3 border-t border-navy/10 pt-5 text-sm sm:grid-cols-2 dark:border-white/10"><p className="flex items-center gap-2"><Clock3 className="size-4 text-blue-700" />{booking.pickup_at_label} ({booking.timezone})</p><p className="flex items-center gap-2"><MapPin className="size-4 text-blue-700" />{booking.service}{booking.hours ? ` · ${booking.hours} hours` : ''}</p></div>
                            </section>

                            <section className="rounded-2xl bg-white p-6 shadow-sm dark:bg-ocean">
                                <h2 className="text-lg font-bold">Passenger & Request Details</h2>
                                <div className="mt-4 grid gap-x-8 gap-y-4 sm:grid-cols-2">
                                    <div>
                                        <p className="text-xs text-navy/55 dark:text-white/55">Lead passenger</p>
                                        <p className="mt-1 font-medium">{booking.contact_name}</p>
                                        {booking.contact_phone ? (
                                            <a
                                                href={`tel:${booking.contact_phone}`}
                                                className="mt-2 inline-flex items-center gap-2 text-sm font-semibold text-blue-700 transition-colors hover:text-gold-dark dark:text-blue-300 dark:hover:text-gold"
                                                aria-label={`Call ${booking.contact_phone}`}
                                            >
                                                <Phone className="size-4 shrink-0" />
                                                {booking.contact_phone}
                                            </a>
                                        ) : (
                                            <p className="text-sm text-navy/65 dark:text-white/65">No phone provided</p>
                                        )}
                                    </div>
                                    <div><p className="text-xs text-navy/55 dark:text-white/55">Luggage</p><p className="mt-1 font-medium">{booking.bags} checked · {booking.carry_on_bags} carry-on{booking.oversized_luggage ? ' · oversized item' : ''}</p></div>
                                    <div><p className="text-xs text-navy/55 dark:text-white/55">Child seats</p><p className="mt-1 font-medium">{booking.child_seats || 'None requested'}</p></div>
                                    <div><p className="text-xs text-navy/55 dark:text-white/55">Flight</p><p className="mt-1 font-medium">{booking.flight_details ?? 'Not provided'}{booking.flight_origin ? ` · from ${booking.flight_origin}` : ''}</p></div>
                                </div>
                                <div className="mt-5 border-t border-navy/10 pt-4 dark:border-white/10"><p className="text-xs text-navy/55 dark:text-white/55">Special requests</p><p className="mt-1 text-sm font-medium">{selectedRequests.length ? selectedRequests.join(' · ') : 'No special requests'}</p></div>
                            </section>
                        </div>

                        <aside className="space-y-4 lg:sticky lg:top-5">
                            <section className="rounded-2xl bg-white p-6 shadow-sm dark:bg-ocean">
                                <div className="flex items-center justify-between"><h2 className="text-lg font-bold">Payment Summary</h2><span className="rounded-full bg-amber-100 px-3 py-1 text-xs font-semibold text-amber-800 dark:bg-amber-400/15 dark:text-amber-200">Due at pickup</span></div>
                                <div className="mt-5 space-y-3 border-b border-navy/10 pb-4 text-sm dark:border-white/10"><div className="flex justify-between gap-3"><span className="text-navy/65 dark:text-white/65">{booking.vehicle} fare</span><span>{formatMoney(booking.fare)}</span></div><div className="flex justify-between gap-3"><span className="text-navy/65 dark:text-white/65">Special requests</span><span className="font-medium text-green-700 dark:text-green-300">Included</span></div><div className="flex justify-between gap-3"><span className="text-navy/65 dark:text-white/65">Payment method</span><span className="text-right">{booking.payment}</span></div></div>
                                <div className="mt-4 flex items-center justify-between gap-3 text-lg font-bold"><span>Total fare</span><span className="text-2xl">{formatMoney(booking.fare)}</span></div>
                                <p className="mt-2 text-xs text-navy/55 dark:text-white/55">Final fare includes applicable taxes and tolls as shown at checkout.</p>
                            </section>
                            <section className="rounded-2xl bg-white p-5 shadow-sm dark:bg-ocean"><p className="flex items-center gap-2 text-sm font-semibold"><ShieldCheck className="size-5 text-green-600" />Your booking is protected</p><p className="mt-2 text-sm text-navy/65 dark:text-white/65">Free cancellation up to 2 hours before pickup. Contact dispatch if your plans change.</p><a href="mailto:dispatch@voyagetransit.com" className="mt-4 inline-flex items-center gap-2 text-sm font-semibold text-blue-700 dark:text-blue-300"><Phone className="size-4" />Contact dispatch support</a></section>
                            {booking.status === 'confirmed' && <Link href={`/booking/${booking.reference}/cancel`} className="inline-flex w-full items-center justify-center gap-2 rounded-xl border border-navy/15 bg-white px-5 py-3 text-sm font-semibold transition-colors hover:border-red-300 hover:text-red-700 dark:border-white/20 dark:bg-ocean dark:hover:border-red-400 dark:hover:text-red-300">Modify or cancel reservation<ArrowRight className="size-4" /></Link>}
                        </aside>
                    </div>

                    <section id="journey-tracking" className="mt-4 overflow-hidden rounded-2xl bg-white shadow-sm dark:bg-ocean">
                        <div className="flex flex-col gap-5 p-6 sm:flex-row sm:items-center sm:justify-between sm:p-8">
                            <div className="flex items-start gap-4"><span className={`flex size-12 shrink-0 items-center justify-center rounded-xl ${isActive ? 'bg-green-100 text-green-700 dark:bg-green-400/15 dark:text-green-300' : 'bg-blue-100 text-blue-700 dark:bg-blue-400/15 dark:text-blue-300'}`}><Navigation className="size-6" /></span><div><p className={`flex items-center gap-2 text-sm font-bold ${isActive ? 'text-green-700 dark:text-green-300' : 'text-blue-700 dark:text-blue-300'}`}><span className={`size-2 rounded-full ${isActive ? 'animate-pulse bg-green-500' : 'bg-blue-500'}`} />{isActive ? 'Journey in progress' : 'Journey tracking'}</p><h2 className="mt-1 text-xl font-bold">{isActive ? 'Your scheduled journey is underway' : 'Track your active journey'}</h2><p className="mt-1 max-w-2xl text-sm text-navy/65 dark:text-white/65">{isActive ? 'Your trip timeline and booking details are available here. Live vehicle location will appear when chauffeur GPS tracking is connected.' : 'Your booking and pickup schedule are confirmed. Chauffeur and live location details will be added here when tracking is connected.'}</p></div></div>
                            {booking.status === 'confirmed' ? <Link href={`/booking/${booking.reference}/tracking`} className="inline-flex shrink-0 items-center justify-center gap-2 rounded-lg bg-gold px-6 py-3 font-semibold text-white transition-colors hover:bg-gold-dark">Open live tracking<ArrowRight className="size-4" /></Link> : auth.user ? <Link href={dashboard()} className="inline-flex shrink-0 items-center justify-center gap-2 rounded-lg bg-gold px-6 py-3 font-semibold text-white transition-colors hover:bg-gold-dark">View in dashboard<ArrowRight className="size-4" /></Link> : <Link href={home()} className="inline-flex shrink-0 items-center justify-center gap-2 rounded-lg bg-gold px-6 py-3 font-semibold text-white transition-colors hover:bg-gold-dark">Book another ride<ArrowRight className="size-4" /></Link>}
                        </div>
                    </section>

                    <div className="mt-6 flex flex-wrap justify-center gap-3"><Link href={home()} className="rounded-lg bg-gold px-6 py-3 text-center font-semibold text-white">Book another ride</Link>{auth.user && <Link href={dashboard()} className="rounded-lg border border-navy/15 px-6 py-3 text-center font-semibold dark:border-white/20">Go to dashboard</Link>}</div>
                    <div className="mt-4 flex justify-center"><Link href={`/booking/${booking.reference}/guide`} className="inline-flex items-center gap-2 rounded-lg border border-navy/15 px-6 py-3 text-center text-sm font-semibold transition-colors hover:border-gold hover:text-gold-dark dark:border-white/20 dark:hover:border-gold">View trip &amp; destination guide<ArrowRight className="size-4" /></Link></div>
                </main>
                <SiteFooter className="bg-mist dark:bg-ink" />
            </div>
        </>
    );
}
