import { Head, router } from '@inertiajs/react';
import { CheckCircle2, Clock, MapPin, Package, Phone, Search, ShoppingBag, Truck, XCircle } from 'lucide-react';
import { useRef, useState } from 'react';

import FrontendLayout from '@/layouts/frontend-layout';

function formatMoney(value: number) {
    return `Tk ${Number(value || 0).toLocaleString()}`;
}

interface TimelineStep {
    status: string;
    label: string;
    done: boolean;
    time: string | null;
}

interface OrderItem {
    product_name: string;
    sku: string;
    qty: number;
    price: number;
    subtotal: number;
}

interface TrackOrder {
    invoice_no: string;
    customer_name: string;
    customer_phone: string;
    shipping_address: string;
    order_status: string;
    payment_method: string;
    payment_status: string;
    subtotal: number;
    discount_amount: number;
    shipping_charge: number;
    total_amount: number;
    ordered_at: string | null;
    timeline: TimelineStep[];
    items: OrderItem[];
}

interface Props {
    order: TrackOrder | null;
    query: string | null;
}

const STATUS_ICON: Record<string, React.ElementType> = {
    new: ShoppingBag,
    confirmed: CheckCircle2,
    packed: Package,
    shipped: Truck,
    delivered: CheckCircle2,
    cancelled: XCircle,
    returned: XCircle,
};

const CANCELLED_STATUSES = ['cancelled', 'returned'];

function StatusBadge({ status }: { status: string }) {
    const isBad = CANCELLED_STATUSES.includes(status);
    const isGood = status === 'delivered';
    const label = status.charAt(0).toUpperCase() + status.slice(1);
    const cls = isBad
        ? 'border-red-300 bg-red-50 text-red-700'
        : isGood
          ? 'border-green-300 bg-green-50 text-green-700'
          : 'border-[var(--brand-gold)] bg-[var(--brand-cream)] text-[var(--brand-gold-dim)]';

    return (
        <span className={`inline-flex items-center gap-1.5 border px-3 py-1 text-xs font-medium tracking-[0.12em] uppercase ${cls}`}>
            <span className={`h-1.5 w-1.5 rounded-full ${isBad ? 'bg-red-500' : isGood ? 'bg-green-500' : 'bg-[var(--brand-gold)]'}`} />
            {label}
        </span>
    );
}

function PaymentBadge({ status }: { status: string }) {
    const label = status.charAt(0).toUpperCase() + status.slice(1);
    const cls =
        status === 'paid'
            ? 'border-green-300 bg-green-50 text-green-700'
            : status === 'refunded'
              ? 'border-blue-300 bg-blue-50 text-blue-700'
              : 'border-yellow-300 bg-yellow-50 text-yellow-700';
    return (
        <span className={`inline-flex items-center gap-1.5 border px-3 py-1 text-xs font-medium tracking-[0.12em] uppercase ${cls}`}>
            {label}
        </span>
    );
}

// ─── Timeline ─────────────────────────────────────────────────────────────────

function OrderTimeline({ timeline, orderStatus }: { timeline: TimelineStep[]; orderStatus: string }) {
    const isCancelled = CANCELLED_STATUSES.includes(orderStatus);

    return (
        <div className="relative">
            {/* vertical line */}
            <div className="absolute top-0 bottom-0 left-5 w-px bg-[var(--brand-line)]" />

            <ol className="space-y-6">
                {timeline.map((step, idx) => {
                    const Icon = STATUS_ICON[step.status] ?? Clock;
                    const isLast = idx === timeline.length - 1;
                    const isCancelStep = CANCELLED_STATUSES.includes(step.status);
                    const circleClass = step.done
                        ? isCancelStep
                            ? 'bg-red-500 border-red-500 text-white'
                            : isLast && step.status === 'delivered'
                              ? 'bg-green-500 border-green-500 text-white'
                              : 'bg-[var(--brand-gold)] border-[var(--brand-gold)] text-white'
                        : 'bg-white border-[var(--brand-line)] text-[var(--brand-muted)]';

                    return (
                        <li key={step.status} className="flex items-start gap-4 pl-0">
                            <div
                                className={`relative z-10 flex h-10 w-10 shrink-0 items-center justify-center rounded-full border-2 ${circleClass}`}
                            >
                                <Icon size={16} />
                            </div>
                            <div className="pt-1.5">
                                <p
                                    className={`text-sm font-semibold ${step.done ? (isCancelStep ? 'text-red-600' : 'text-[var(--brand-ink)]') : 'text-[var(--brand-muted)]'}`}
                                >
                                    {step.label}
                                </p>
                                {step.time && <p className="mt-0.5 font-mono text-xs text-[var(--brand-muted)]">{step.time}</p>}
                                {!step.done && !isCancelled && (
                                    <p className="mt-0.5 text-xs text-[var(--brand-muted)] italic">Pending</p>
                                )}
                            </div>
                        </li>
                    );
                })}
            </ol>
        </div>
    );
}

// ─── Search Form ──────────────────────────────────────────────────────────────

function SearchForm({ defaultQuery }: { defaultQuery: string }) {
    const [value, setValue] = useState(defaultQuery);
    const inputRef = useRef<HTMLInputElement>(null);

    function handleSubmit(e: React.FormEvent) {
        e.preventDefault();
        const q = value.trim();
        if (!q) return;
        router.get(route('track-order'), { query: q }, { preserveScroll: false });
    }

    return (
        <form onSubmit={handleSubmit} className="flex w-full flex-col gap-3 sm:flex-row">
            <div className="relative flex-1">
                <Search size={16} className="pointer-events-none absolute top-1/2 left-4 -translate-y-1/2 text-[var(--brand-muted)]" />
                <input
                    ref={inputRef}
                    type="text"
                    value={value}
                    onChange={(e) => setValue(e.target.value)}
                    placeholder="Enter Invoice No or Phone Number"
                    className="h-12 w-full border border-[var(--brand-line)] bg-white pl-11 pr-4 text-sm text-[var(--brand-ink)] placeholder-[var(--brand-muted)] outline-none focus:border-[var(--brand-gold)] focus:ring-1 focus:ring-[var(--brand-gold)]"
                />
            </div>
            <button
                type="submit"
                className="h-12 shrink-0 bg-[var(--brand-gold)] px-8 text-sm font-semibold tracking-[0.1em] uppercase text-white transition-opacity hover:opacity-90"
            >
                Track Order
            </button>
        </form>
    );
}

// ─── Order Result ─────────────────────────────────────────────────────────────

function OrderResult({ order }: { order: TrackOrder }) {
    return (
        <div className="mt-8 space-y-6">
            {/* Header */}
            <div className="border border-[var(--brand-line)] bg-white p-5 sm:p-6">
                <div className="flex flex-wrap items-start justify-between gap-3">
                    <div>
                        <p className="eyebrow text-[var(--brand-muted)]">Invoice</p>
                        <p className="mt-1 font-mono text-lg font-bold text-[var(--brand-ink)]">{order.invoice_no}</p>
                    </div>
                    <div className="flex flex-wrap gap-2">
                        <StatusBadge status={order.order_status} />
                        <PaymentBadge status={order.payment_status} />
                    </div>
                </div>

                <div className="mt-4 grid grid-cols-1 gap-3 sm:grid-cols-2 lg:grid-cols-4">
                    <InfoTile icon={<ShoppingBag size={14} />} label="Customer" value={order.customer_name} />
                    <InfoTile icon={<Phone size={14} />} label="Phone" value={order.customer_phone} />
                    <InfoTile icon={<MapPin size={14} />} label="Delivery Address" value={order.shipping_address} />
                    <InfoTile icon={<Clock size={14} />} label="Order Date" value={order.ordered_at ?? '—'} />
                </div>
            </div>

            <div className="grid grid-cols-1 gap-6 lg:grid-cols-3">
                {/* Timeline */}
                <div className="border border-[var(--brand-line)] bg-white p-5 sm:p-6 lg:col-span-1">
                    <h2 className="eyebrow mb-5 text-[var(--brand-muted)]">Order Progress</h2>
                    <OrderTimeline timeline={order.timeline} orderStatus={order.order_status} />
                </div>

                {/* Items + Summary */}
                <div className="space-y-6 lg:col-span-2">
                    {/* Items */}
                    <div className="border border-[var(--brand-line)] bg-white">
                        <div className="border-b border-[var(--brand-line)] px-5 py-4 sm:px-6">
                            <h2 className="eyebrow text-[var(--brand-muted)]">Order Items</h2>
                        </div>

                        {/* Mobile */}
                        <div className="divide-y divide-[var(--brand-line)] md:hidden">
                            {order.items.map((item, idx) => (
                                <div key={idx} className="flex items-start gap-3 p-4">
                                    <span className="flex h-10 w-10 shrink-0 items-center justify-center border border-[var(--brand-line)] bg-white text-[var(--brand-gold)]">
                                        <Package size={16} />
                                    </span>
                                    <div className="min-w-0 flex-1">
                                        <p className="text-sm font-medium leading-snug text-[var(--brand-ink)]">{item.product_name}</p>
                                        <p className="mt-0.5 font-mono text-[10px] text-[var(--brand-muted)]">{item.sku || '—'}</p>
                                        <div className="mt-2 flex items-center justify-between">
                                            <span className="text-xs text-[var(--brand-muted)]">Qty: {item.qty}</span>
                                            <span className="text-sm font-semibold text-[var(--brand-ink)]">{formatMoney(item.subtotal)}</span>
                                        </div>
                                    </div>
                                </div>
                            ))}
                        </div>

                        {/* Desktop */}
                        <div className="hidden overflow-x-auto md:block">
                            <table className="w-full border-collapse text-left text-sm">
                                <thead>
                                    <tr className="border-b border-[var(--brand-line)] text-xs tracking-[0.14em] uppercase text-[var(--brand-muted)]">
                                        <th className="px-6 py-3 font-medium">Product</th>
                                        <th className="px-4 py-3 font-medium">SKU</th>
                                        <th className="px-4 py-3 font-medium text-center">Qty</th>
                                        <th className="px-6 py-3 text-right font-medium">Total</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    {order.items.map((item, idx) => (
                                        <tr key={idx} className="border-b border-[var(--brand-line)] last:border-0">
                                            <td className="px-6 py-4">
                                                <div className="flex items-center gap-3">
                                                    <span className="flex h-10 w-10 shrink-0 items-center justify-center border border-[var(--brand-line)] bg-white text-[var(--brand-gold)]">
                                                        <Package size={16} />
                                                    </span>
                                                    <span className="font-medium text-[var(--brand-ink)]">{item.product_name}</span>
                                                </div>
                                            </td>
                                            <td className="px-4 py-4 font-mono text-xs text-[var(--brand-muted)]">{item.sku || '—'}</td>
                                            <td className="px-4 py-4 text-center text-[var(--brand-ink)]">{item.qty}</td>
                                            <td className="px-6 py-4 text-right font-semibold text-[var(--brand-ink)]">
                                                {formatMoney(item.subtotal)}
                                            </td>
                                        </tr>
                                    ))}
                                </tbody>
                            </table>
                        </div>
                    </div>

                    {/* Summary */}
                    <div className="border border-[var(--brand-line)] bg-white p-5 sm:p-6">
                        <h2 className="eyebrow mb-4 text-[var(--brand-muted)]">Price Summary</h2>
                        <div className="space-y-2.5 text-sm">
                            <div className="flex justify-between text-[var(--brand-muted)]">
                                <span>Subtotal</span>
                                <span>{formatMoney(order.subtotal)}</span>
                            </div>
                            {order.discount_amount > 0 && (
                                <div className="flex justify-between text-green-600">
                                    <span>Discount</span>
                                    <span>- {formatMoney(order.discount_amount)}</span>
                                </div>
                            )}
                            <div className="flex justify-between text-[var(--brand-muted)]">
                                <span>Shipping</span>
                                <span>{order.shipping_charge === 0 ? 'Free' : formatMoney(order.shipping_charge)}</span>
                            </div>
                            <div className="flex justify-between border-t border-[var(--brand-line)] pt-3 text-base font-bold text-[var(--brand-ink)]">
                                <span>Total</span>
                                <span>{formatMoney(order.total_amount)}</span>
                            </div>
                            <div className="flex justify-between text-xs text-[var(--brand-muted)]">
                                <span>Payment</span>
                                <span className="uppercase">{order.payment_method}</span>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    );
}

function InfoTile({ icon, label, value }: { icon: React.ReactNode; label: string; value: string }) {
    return (
        <div className="border border-[var(--brand-line)] bg-[var(--brand-ivory)] p-3.5">
            <div className="mb-1 flex items-center gap-1.5 text-[var(--brand-muted)]">
                {icon}
                <p className="eyebrow text-[10px]">{label}</p>
            </div>
            <p className="text-sm font-medium leading-snug text-[var(--brand-ink)]">{value}</p>
        </div>
    );
}

// ─── Page ─────────────────────────────────────────────────────────────────────

export default function TrackOrderPage({ order, query }: Props) {
    const notFound = query && !order;

    return (
        <FrontendLayout>
            <Head title="Track Order" />

            {/* Hero */}
            <section className="ornament-bg border-b border-[var(--brand-line)] bg-[var(--brand-ivory)]">
                <div className="mx-auto max-w-[1500px] px-4 py-10 sm:px-6 lg:px-10">
                    <p className="eyebrow mb-2 text-[var(--brand-gold-dim)]">Real-time updates</p>
                    <h1 className="font-serif text-2xl font-bold tracking-tight text-[var(--brand-ink)] sm:text-3xl">Track Your Order</h1>
                    <p className="mt-2 text-sm text-[var(--brand-muted)]">Enter your invoice number or phone number to check your order status.</p>
                </div>
            </section>

            <div className="mx-auto max-w-[1500px] px-4 py-8 sm:px-6 lg:px-10">
                <SearchForm defaultQuery={query ?? ''} />

                {notFound && (
                    <div className="mt-8 border border-red-200 bg-red-50 p-6 text-center">
                        <XCircle size={32} className="mx-auto mb-3 text-red-400" />
                        <p className="font-medium text-red-700">No order found</p>
                        <p className="mt-1 text-sm text-red-500">
                            No order matched <span className="font-mono font-semibold">"{query}"</span>. Check the invoice number or phone number and try again.
                        </p>
                    </div>
                )}

                {order && <OrderResult order={order} />}

                {!query && (
                    <div className="mt-12 grid grid-cols-1 gap-4 sm:grid-cols-3">
                        {[
                            { icon: <Search size={20} />, title: 'Search by Invoice', desc: 'Enter your invoice number from the order confirmation.' },
                            { icon: <Phone size={20} />, title: 'Search by Phone', desc: 'Use the phone number you placed the order with.' },
                            { icon: <Truck size={20} />, title: 'Live Status', desc: 'See real-time order progress from placement to delivery.' },
                        ].map((item) => (
                            <div key={item.title} className="border border-[var(--brand-line)] bg-white p-5">
                                <div className="mb-3 flex h-10 w-10 items-center justify-center bg-[var(--brand-ivory)] text-[var(--brand-gold)]">
                                    {item.icon}
                                </div>
                                <p className="text-sm font-semibold text-[var(--brand-ink)]">{item.title}</p>
                                <p className="mt-1 text-xs text-[var(--brand-muted)]">{item.desc}</p>
                            </div>
                        ))}
                    </div>
                )}
            </div>
        </FrontendLayout>
    );
}
