import { Head, Link } from '@inertiajs/react';
import { ArrowLeft, CarFront, CheckCircle2, Clock3, Copy, MessageCircle, Navigation, Phone, RefreshCw, ShieldCheck } from 'lucide-react';
import { useState } from 'react';
import SiteFooter from '@/components/home/site-footer';
import SiteHeader from '@/components/home/site-header';
import RouteMap, { type MapPoint } from '@/components/booking/route-map';
import type { BookingSummary } from '@/types/booking';

type Props = { booking: BookingSummary };

export default function Tracking({ booking }: Props) {
    const [copied, setCopied] = useState(false);
    const hasCoordinates = booking.pickup_lat !== null && booking.pickup_lng !== null;
    const points: MapPoint[] = [
        ...(hasCoordinates ? [{ label: 'P', lat: booking.pickup_lat!, lng: booking.pickup_lng!, color: '#0b1f33' }] : []),
        ...(booking.destination_lat !== null && booking.destination_lng !== null ? [{ label: 'D', lat: booking.destination_lat, lng: booking.destination_lng, color: '#059669' }] : []),
    ];
    const shareTrip = async () => {
        const url = window.location.href;
        if (navigator.share) {
            await navigator.share({ title: `ZozTrip ${booking.reference}`, url });
        } else {
            await navigator.clipboard.writeText(url);
            setCopied(true);
            window.setTimeout(() => setCopied(false), 1800);
        }
    };

    return (
        <>
            <Head title={`Live Tracking · ${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">
                    <Link href={`/booking/${booking.reference}/guide`} className="inline-flex items-center gap-2 rounded-lg bg-sand px-5 py-3 text-sm font-semibold hover:bg-gold/20 dark:bg-ocean"><ArrowLeft className="size-4" /> Go back</Link>

                    <div className="mt-10 grid items-stretch gap-4 lg:grid-cols-[405px_minmax(0,1fr)]">
                        <aside className="flex flex-col overflow-hidden rounded-2xl bg-white shadow-sm dark:bg-ocean">
                            <div className="bg-ocean p-6 text-white"><div className="flex items-center justify-between gap-3"><p className="text-xs font-bold uppercase tracking-wide text-white/70">Booking #{booking.reference}</p><span className="rounded-full bg-emerald-500 px-3 py-1 text-xs font-bold"><span className="mr-1.5 inline-block size-2 rounded-full bg-white" /> Tracking active</span></div><h1 className="mt-5 text-2xl font-semibold">{booking.service}</h1><p className="mt-1 text-sm text-blue-200">{booking.pickup.split(',')[0]} → {booking.destination?.split(',')[0] ?? 'Destination'}</p></div>
                            <div className="flex-1 space-y-4 p-5"><div className="rounded-xl bg-mist p-4 dark:bg-ink"><div className="flex items-center gap-3"><span className="flex size-12 items-center justify-center rounded-xl bg-white dark:bg-ocean"><CarFront className="size-6 text-blue-700" /></span><div><h2 className="font-semibold">Marcus Vance</h2><p className="text-sm text-navy/60 dark:text-white/60">{booking.vehicle}</p><p className="mt-1 text-xs font-semibold text-amber-600">★ 4.98 · Executive fleet</p></div></div>{booking.contact_phone && <div className="mt-4"><p className="text-xs font-semibold text-navy/55 dark:text-white/55">Contact</p><a href={`tel:${booking.contact_phone}`} className="mt-1 inline-flex items-center gap-2 text-sm font-bold 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" />{booking.contact_phone}</a></div>}<div className="mt-4 grid grid-cols-2 gap-2"><a href={`tel:${booking.contact_phone ?? ''}`} className="inline-flex items-center justify-center gap-2 rounded-lg bg-gold px-3 py-2.5 text-sm font-semibold text-white"><Phone className="size-4" /> Call</a><a href={`sms:${booking.contact_phone ?? ''}`} className="inline-flex items-center justify-center gap-2 rounded-lg bg-white px-3 py-2.5 text-sm font-semibold dark:bg-ocean"><MessageCircle className="size-4" /> Message</a></div></div>
                                <div className="rounded-xl bg-mist p-4 dark:bg-ink"><div className="flex items-center justify-between"><h2 className="text-sm font-bold uppercase tracking-wide">Live journey progress</h2><RefreshCw className="size-4 text-navy/45 dark:text-white/45" /></div><TimelineItem color="green" title={booking.pickup} time={booking.pickup_at_label} /><TimelineItem color="blue" title={booking.destination ?? 'Destination'} time={booking.destination ? `ETA based on ${booking.duration ?? 'route estimate'}` : 'Destination details pending'} last /></div>
                                <div className="flex items-center justify-between rounded-xl bg-mist px-4 py-3 text-sm dark:bg-ink"><span className="flex items-center gap-2 font-semibold"><ShieldCheck className="size-4 text-blue-700" /> 24/7 Priority Concierge</span><a href={`tel:${booking.contact_phone ?? ''}`} className="font-semibold text-blue-700 dark:text-blue-300">Call</a></div>
                            </div><div className="border-t border-navy/10 p-5 dark:border-white/10"><div className="flex items-end justify-between"><div><p className="text-xs text-navy/55 dark:text-white/55">Fare estimate</p><p className="text-2xl font-bold">{booking.fare}</p></div><Link href={`/booking/${booking.reference}/confirmation`} className="rounded-lg bg-mist px-4 py-2.5 text-sm font-semibold dark:bg-ink">Trip receipt</Link></div></div>
                        </aside>

                        <section className="flex min-h-[660px] flex-col overflow-hidden rounded-2xl bg-white shadow-sm dark:bg-ocean"><div className="flex flex-wrap items-center justify-between gap-4 p-5 sm:p-6"><div><div className="inline-flex items-center gap-2 rounded-full bg-amber-50 px-3 py-1.5 text-xs font-bold uppercase tracking-wide text-amber-900 dark:bg-amber-400/15 dark:text-amber-200"><span className="size-2 rounded-full bg-amber-600" /> Route overview · On schedule</div><div className="mt-3 flex flex-wrap items-baseline gap-3"><h2 className="text-2xl font-semibold">{booking.status === 'confirmed' ? 'Journey scheduled' : booking.status_label}</h2><span className="text-sm text-navy/60 dark:text-white/60"><Clock3 className="mr-1 inline size-4" /> {booking.pickup_at_label}</span></div><p className="mt-1 text-sm text-navy/60 dark:text-white/60">Route preview is based on your confirmed pickup and destination.</p></div><button type="button" onClick={shareTrip} className="inline-flex items-center gap-2 rounded-lg bg-mist px-4 py-2.5 text-sm font-semibold dark:bg-ink"><Copy className="size-4" /> {copied ? 'Copied' : 'Share trip'}</button></div><div className="relative min-h-[500px] flex-1 overflow-hidden bg-[#e8f0f4] dark:bg-ink">{hasCoordinates ? <RouteMap points={points} className="absolute inset-0 size-full" /> : <div className="flex h-full min-h-[500px] flex-col items-center justify-center gap-3 bg-[linear-gradient(#dce8ee_1px,transparent_1px),linear-gradient(90deg,#dce8ee_1px,transparent_1px)] bg-[size:40px_40px] p-8 text-center dark:bg-ink"><Navigation className="size-12 text-gold-dark" /><h3 className="text-lg font-semibold">Live map is waiting for route coordinates</h3><p className="max-w-md text-sm text-navy/60 dark:text-white/60">This booking does not have verified map coordinates yet. Location sharing will appear here once the pickup and destination are confirmed.</p></div>}<div className="absolute top-5 left-5 rounded-xl bg-white/95 px-4 py-3 shadow-lg dark:bg-ocean/95"><p className="flex items-center gap-2 text-sm font-semibold"><span className="size-2 rounded-full bg-emerald-500" /> {hasCoordinates ? 'Route coordinates verified' : 'Waiting for GPS signal'}</p><p className="mt-1 text-xs text-navy/60 dark:text-white/60">{hasCoordinates ? 'Pickup and destination mapped from your booking' : 'No fake vehicle position is shown'}</p></div></div></section>
                    </div>
                </main>
                <SiteFooter className="bg-mist dark:bg-ink" />
            </div>
        </>
    );
}

function TimelineItem({ color, title, time, last = false }: { color: 'green' | 'blue'; title: string; time: string; last?: boolean }) {
    return <div className="relative mt-5 flex gap-3 pl-1"><span className={`z-10 mt-1 size-3 shrink-0 rounded-full ${color === 'green' ? 'bg-emerald-600' : 'bg-blue-600'} ${last ? '' : 'ring-4 ring-emerald-100 dark:ring-emerald-400/15'}`} />{!last && <span className="absolute top-4 left-[6px] h-9 border-l border-dashed border-navy/20 dark:border-white/20" />}<div className="min-w-0"><p className="truncate text-sm font-semibold">{title}</p><p className="mt-1 text-xs text-navy/55 dark:text-white/55">{time}</p></div></div>;
}
