import { Head, Link, useForm } from '@inertiajs/react';
import { Building2, Check, ChevronDown, Lock, MapPin, PackageCheck, Phone, ShieldCheck, ShoppingBag, Truck, WalletCards } from 'lucide-react';
import { type FormEventHandler, useState } from 'react';

import SiteHeader from '@/components/site-header';
import { LangProvider, useLang } from '@/lib/lang';

interface CartItem {
    row_id: string;
    product_id: number;
    variant_id: number | null;
    name: string;
    variant_label: string | null;
    price: number;
    qty: number;
    image: string | null;
    product_type: string;
}

interface CartTotals {
    subtotal: number;
    discount: number;
    shipping: number;
    total: number;
    coupon_code: string | null;
}

interface Courier {
    id: number;
    name: string;
    slug?: string;
}

type PaymentMethod = 'cod' | 'bkash' | 'nagad' | 'bank';

const colorHex: Record<string, string> = {
    black: '#1A1F23',
    blue: '#2A3E55',
    brown: '#7A5A3A',
    cream: '#EAE0CB',
    gray: '#6F6F6F',
    green: '#8C8042',
    grey: '#6F6F6F',
    maroon: '#6B2E2E',
    navy: '#2A3E55',
    olive: '#8C8042',
    red: '#8E3B2E',
    sage: '#A8AA8E',
    white: '#F4EEDF',
};

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


function inferUsage(item: CartItem) {
    const text = `${item.name} ${item.variant_label ?? ''}`.toLowerCase();
    if (text.includes('ready')) return 'Ready-Made';
    if (text.includes('shirt')) return 'Shirt';
    if (text.includes('kabli')) return 'Kabli';
    return 'Punjabi';
}

function inferLength(usage: string) {
    if (usage === 'Shirt') return '3 yd';
    if (usage === 'Kabli') return '4.5 yd';
    if (usage === 'Ready-Made') return 'Size selected';
    return '4 yd';
}

function inferColor(item: CartItem) {
    const text = `${item.variant_label ?? ''} ${item.name}`.toLowerCase();
    const match = Object.entries(colorHex).find(([name]) => text.includes(name));
    return match ? { name: match[0], hex: match[1] } : { name: 'olive', hex: '#8C8042' };
}

function FabricSwatch({ color }: { color: string }) {
    return (
        <div
            className="h-full w-full"
            style={{
                backgroundColor: color,
                backgroundImage:
                    'repeating-linear-gradient(45deg,rgba(0,0,0,.08) 0 2px,transparent 2px 7px),repeating-linear-gradient(-45deg,rgba(255,255,255,.08) 0 2px,transparent 2px 7px)',
            }}
        />
    );
}

function FragranceSwatch() {
    return (
        <div className="flex h-full w-full items-center justify-center" style={{ background: 'linear-gradient(145deg, #F9F4EC, #EDE5D8)' }}>
            <svg viewBox="0 0 60 100" fill="none" style={{ width: '22px', opacity: 0.45 }}>
                <rect x="25" y="1" width="10" height="13" rx="3" fill="#B8893F" />
                <rect x="22" y="12" width="16" height="5" rx="1" fill="#B8893F" opacity="0.6" />
                <path d="M18 22 C8 32 7 48 7 58 C7 78 15 94 30 96 C45 94 53 78 53 58 C53 48 52 32 42 22 Z" fill="#B8893F" opacity="0.2" stroke="#B8893F" strokeWidth="0.8" />
                <path d="M22 22 C15 32 14 46 14 55 C14 70 21 85 30 87 C39 85 46 70 46 55 C46 46 45 32 38 22 Z" fill="#B8893F" opacity="0.25" />
            </svg>
        </div>
    );
}

function Field({ label, error, children }: { label: string; error?: string; children: React.ReactNode }) {
    return (
        <label className="block">
            <span className="mb-1.5 block text-[11px] font-medium tracking-wide text-[var(--brand-muted)] uppercase">{label}</span>
            {children}
            {error && <span className="mt-1 block text-xs text-[#8E3B2E]">{error}</span>}
        </label>
    );
}

function inputCls(error?: string) {
    return `w-full border bg-white px-3 py-2.5 text-sm text-[var(--brand-ink)] outline-none transition placeholder:text-slate-400 focus:border-[var(--brand-gold)] focus:ring-2 focus:ring-[rgba(184,137,63,.15)] ${error ? 'border-[#8E3B2E]' : 'border-slate-200 hover:border-slate-300'}`;
}

function Section({ title, children }: { title: string; children: React.ReactNode }) {
    return (
        <div className="rounded-lg border border-slate-200 bg-white">
            <div className="border-b border-slate-100 px-4 py-3 sm:px-5">
                <h2 className="text-sm font-semibold text-[var(--brand-ink)]">{title}</h2>
            </div>
            <div className="px-4 py-4 sm:px-5">{children}</div>
        </div>
    );
}

function ItemsReview({ items }: { items: CartItem[] }) {
    const [guideOpen, setGuideOpen] = useState(false);
    const hasFabricItems = items.some((item) => item.product_type !== 'fragrance');

    return (
        <Section title="Review Your Items">
            <div className="space-y-3">
                {items.map((item) => {
                    const isFragrance = item.product_type === 'fragrance';
                    const usage = isFragrance ? '' : inferUsage(item);
                    const color = isFragrance ? { name: '', hex: '' } : inferColor(item);

                    const subLine = isFragrance
                        ? [item.variant_label, `qty ${item.qty}`].filter(Boolean).join(' · ')
                        : [item.variant_label ?? color.name, `As ${usage}`, inferLength(usage as any), `qty ${item.qty}`].join(' · ');

                    return (
                        <div key={item.row_id} className="flex items-center gap-3 rounded-md border border-slate-100 p-3">
                            <div className="h-14 w-11 shrink-0 overflow-hidden rounded border border-slate-200">
                                {item.image ? (
                                    <img src={`/storage/${item.image}`} alt={item.name} className="h-full w-full object-cover" />
                                ) : isFragrance ? (
                                    <FragranceSwatch />
                                ) : (
                                    <FabricSwatch color={color.hex} />
                                )}
                            </div>
                            <div className="min-w-0 flex-1">
                                <p className="truncate text-sm font-medium text-[var(--brand-ink)]">{item.name}</p>
                                <p className="mt-0.5 text-xs text-[var(--brand-muted)]">{subLine}</p>
                            </div>
                            <div className="shrink-0 text-sm font-semibold text-[var(--brand-ink)]">{formatMoney(item.price * item.qty)}</div>
                        </div>
                    );
                })}
            </div>

            {hasFabricItems && (
                <>
                    <button
                        type="button"
                        onClick={() => setGuideOpen((v) => !v)}
                        className="mt-3 flex items-center gap-1.5 text-xs text-[var(--brand-gold-dim)]"
                    >
                        <ChevronDown size={13} className={`transition ${guideOpen ? 'rotate-180' : ''}`} />
                        Fabric length guide
                    </button>

                    {guideOpen && (
                        <p className="mt-2 rounded bg-slate-50 p-3 text-xs leading-5 text-[var(--brand-muted)]">
                            Confirm final fabric length with your tailor before cutting. Body size, collar style, pockets, and trouser design may
                            change yardage. Shirt ≈ 3 yd · Punjabi ≈ 4 yd · Kabli ≈ 4.5 yd.
                        </p>
                    )}
                </>
            )}
        </Section>
    );
}

function PaymentSection({ value, onChange }: { value: PaymentMethod; onChange: (m: PaymentMethod) => void }) {
    const methods: Array<{ id: PaymentMethod; title: string; note: string; icon: React.ReactNode }> = [
        { id: 'cod', title: 'Cash on Delivery', note: 'Pay on arrival', icon: <PackageCheck size={16} /> },
        { id: 'bkash', title: 'bKash', note: 'Mobile payment', icon: <WalletCards size={16} /> },
        { id: 'nagad', title: 'Nagad', note: 'Mobile payment', icon: <Phone size={16} /> },
        { id: 'bank', title: 'Bank Transfer', note: 'Details after order', icon: <Building2 size={16} /> },
    ];

    return (
        <Section title="Payment Method">
            <div className="grid gap-2 sm:grid-cols-2">
                {methods.map((m) => {
                    const sel = value === m.id;
                    return (
                        <button
                            key={m.id}
                            type="button"
                            onClick={() => onChange(m.id)}
                            className={`flex items-center gap-3 rounded-md border-2 p-3 text-left transition ${sel ? 'border-[var(--brand-gold)] bg-amber-50' : 'border-slate-200 hover:border-slate-300'}`}
                        >
                            <span
                                className={`flex h-4 w-4 shrink-0 items-center justify-center rounded-full border-2 ${sel ? 'border-[var(--brand-gold)] bg-[var(--brand-gold)]' : 'border-slate-300'}`}
                            >
                                {sel && <span className="h-1.5 w-1.5 rounded-full bg-white" />}
                            </span>
                            <span className="text-[var(--brand-gold)]">{m.icon}</span>
                            <span>
                                <span className="block text-sm font-medium text-[var(--brand-ink)]">{m.title}</span>
                                <span className="text-xs text-[var(--brand-muted)]">{m.note}</span>
                            </span>
                        </button>
                    );
                })}
            </div>
            {value !== 'cod' && (
                <p className="mt-3 rounded bg-slate-50 p-3 text-xs leading-5 text-[var(--brand-muted)]">
                    Payment instructions will be sent after the order is placed. Your order stays pending until payment is verified.
                </p>
            )}
        </Section>
    );
}

function OrderSummary({ items, totals }: { items: CartItem[]; totals: CartTotals }) {
    return (
        <div className="rounded-lg border border-slate-200 bg-white p-4">
            <p className="mb-3 text-xs font-semibold tracking-wide text-[var(--brand-muted)] uppercase">Order Summary</p>
            <div className="space-y-3">
                {items.map((item) => {
                    const isFragrance = item.product_type === 'fragrance';
                    const color = isFragrance ? { name: '', hex: '' } : inferColor(item);
                    return (
                        <div key={item.row_id} className="flex items-center gap-3">
                            <div className="relative h-12 w-10 shrink-0 overflow-hidden rounded border border-slate-200">
                                {item.image ? (
                                    <img src={`/storage/${item.image}`} alt={item.name} className="h-full w-full object-cover" />
                                ) : isFragrance ? (
                                    <FragranceSwatch />
                                ) : (
                                    <FabricSwatch color={color.hex} />
                                )}
                                <span className="absolute -top-1 -right-1 flex h-4 w-4 items-center justify-center rounded-full bg-[var(--brand-gold)] text-[9px] font-bold text-white">
                                    {item.qty}
                                </span>
                            </div>
                            <div className="min-w-0 flex-1">
                                <p className="truncate text-xs font-medium text-[var(--brand-ink)]">{item.name}</p>
                                <p className="text-[11px] text-[var(--brand-muted)]">
                                    {isFragrance ? (item.variant_label ?? 'Fragrance') : (item.variant_label ?? color.name)}
                                </p>
                            </div>
                            <div className="shrink-0 text-xs font-semibold">{formatMoney(item.price * item.qty)}</div>
                        </div>
                    );
                })}
            </div>

            <div className="mt-4 space-y-2 border-t border-slate-100 pt-4 text-sm">
                <div className="flex justify-between text-[var(--brand-muted)]">
                    <span>Subtotal</span>
                    <span className="text-[var(--brand-ink)]">{formatMoney(totals.subtotal)}</span>
                </div>
                {totals.discount > 0 && (
                    <div className="flex justify-between text-green-700">
                        <span>Discount</span>
                        <span>-{formatMoney(totals.discount)}</span>
                    </div>
                )}
                <div className="flex justify-between text-[var(--brand-muted)]">
                    <span>Delivery</span>
                    <span className="text-[var(--brand-ink)]">{totals.shipping > 0 ? formatMoney(totals.shipping) : 'Free'}</span>
                </div>
                <div className="flex justify-between border-t border-slate-100 pt-2 font-semibold">
                    <span>Total</span>
                    <span className="text-base text-[var(--brand-ink)]">{formatMoney(totals.total)}</span>
                </div>
            </div>

            <p className="mt-3 flex items-center gap-1.5 text-[11px] text-[var(--brand-muted)]">
                <ShieldCheck size={13} className="text-[var(--brand-gold)]" />
                Secure checkout · Carefully packed before dispatch
            </p>
        </div>
    );
}

function CheckoutPage({ items, totals, couriers }: { items: CartItem[]; totals: CartTotals; couriers: Courier[] }) {
    const { t } = useLang();
    const hasFabricItems = items.some((item) => item.product_type !== 'fragrance');

    const { data, setData, post, processing, errors } = useForm({
        customer_name: '',
        customer_phone: '',
        customer_email: '',
        shipping_address: '',
        city: '',
        note: '',
        courier_id: couriers[0]?.id ? String(couriers[0].id) : '',
        payment_method: 'cod' as PaymentMethod,
    });
    const [acceptTerms, setAcceptTerms] = useState(false);
    const [checks, setChecks] = useState({
        color: false,
        delivery: false,
        length: !hasFabricItems,
        usage: !hasFabricItems,
    });
    const [mobileSummaryOpen, setMobileSummaryOpen] = useState(false);

    const canSubmit =
        Boolean(data.customer_name && data.customer_phone && data.shipping_address && data.payment_method) &&
        Object.values(checks).every(Boolean) &&
        acceptTerms &&
        !processing;

    const submit: FormEventHandler = (e) => {
        e.preventDefault();
        if (!canSubmit) return;
        post('/checkout');
    };

    if (!items.length) {
        return (
            <div className="flex min-h-[60vh] flex-col items-center justify-center px-4 text-center">
                <Head title={t.checkout.title} />
                <ShoppingBag size={40} className="mb-4 text-slate-300" />
                <p className="text-sm text-[var(--brand-muted)]">
                    {t.checkout.emptyCart}{' '}
                    <Link href="/products" className="text-[var(--brand-gold-dim)] underline underline-offset-2">
                        {t.common.continueShopping}
                    </Link>
                </p>
            </div>
        );
    }

    return (
        <div className="min-h-screen bg-slate-50">
            <Head title={t.checkout.title} />
            <SiteHeader variant="checkout" />

            {/* Mobile summary toggle */}
            <button
                type="button"
                onClick={() => setMobileSummaryOpen((v) => !v)}
                className="flex w-full items-center justify-between border-b border-slate-200 bg-white px-4 py-3 text-sm lg:hidden"
            >
                <span className="flex items-center gap-2 text-[var(--brand-gold-dim)]">
                    <ShoppingBag size={15} />
                    {mobileSummaryOpen ? 'Hide' : 'Show'} order summary
                </span>
                <span className="font-semibold text-[var(--brand-ink)]">{formatMoney(totals.total)}</span>
            </button>

            {mobileSummaryOpen && (
                <div className="border-b border-slate-200 bg-white p-4 lg:hidden">
                    <OrderSummary items={items} totals={totals} />
                </div>
            )}

            {/* Main */}
            <form onSubmit={submit} className="mx-auto grid max-w-5xl gap-6 px-4 py-6 lg:grid-cols-[1fr_320px] lg:py-10">
                {/* Left: form */}
                <div className="space-y-4">
                    {/* Contact */}
                    <Section title="Contact">
                        <div className="grid gap-3 sm:grid-cols-2">
                            <Field label="Full name" error={errors.customer_name}>
                                <input
                                    value={data.customer_name}
                                    onChange={(e) => setData('customer_name', e.target.value)}
                                    className={inputCls(errors.customer_name)}
                                    placeholder={t.checkout.fullNamePlaceholder}
                                />
                            </Field>
                            <Field label="Phone" error={errors.customer_phone}>
                                <input
                                    value={data.customer_phone}
                                    onChange={(e) => setData('customer_phone', e.target.value)}
                                    className={inputCls(errors.customer_phone)}
                                    placeholder={t.checkout.phonePlaceholder}
                                />
                            </Field>
                            <Field label="Email (optional)" error={errors.customer_email}>
                                <input
                                    type="email"
                                    value={data.customer_email}
                                    onChange={(e) => setData('customer_email', e.target.value)}
                                    className={inputCls()}
                                    placeholder={t.checkout.emailPlaceholder}
                                />
                            </Field>
                        </div>
                    </Section>

                    {/* Delivery address */}
                    <Section title="Delivery Address">
                        <div className="grid gap-3 sm:grid-cols-2">
                            <div className="sm:col-span-2">
                                <Field label="Full address" error={errors.shipping_address}>
                                    <textarea
                                        value={data.shipping_address}
                                        onChange={(e) => setData('shipping_address', e.target.value)}
                                        rows={3}
                                        className={inputCls(errors.shipping_address)}
                                        placeholder={t.checkout.addressPlaceholder}
                                    />
                                </Field>
                            </div>
                            <Field label="City">
                                <input
                                    value={data.city}
                                    onChange={(e) => setData('city', e.target.value)}
                                    className={inputCls()}
                                    placeholder={t.checkout.cityPlaceholder}
                                />
                            </Field>
                            <Field label="Country">
                                <select className={inputCls()} defaultValue="Bangladesh">
                                    <option>Bangladesh</option>
                                    <option>United Kingdom</option>
                                    <option>United States</option>
                                    <option>United Arab Emirates</option>
                                </select>
                            </Field>
                        </div>
                    </Section>

                    {/* Courier */}
                    {couriers.length > 0 && (
                        <Section title="Delivery Method">
                            <div className="space-y-2">
                                {couriers.map((courier, i) => {
                                    const sel = data.courier_id === String(courier.id);
                                    const icons = [<Truck size={16} />, <MapPin size={16} />, <PackageCheck size={16} />];
                                    return (
                                        <label
                                            key={courier.id}
                                            className={`flex cursor-pointer items-center gap-3 rounded-md border-2 p-3 transition ${sel ? 'border-[var(--brand-gold)] bg-amber-50' : 'border-slate-200 hover:border-slate-300'}`}
                                        >
                                            <input
                                                type="radio"
                                                name="courier_id"
                                                value={String(courier.id)}
                                                checked={sel}
                                                onChange={() => setData('courier_id', String(courier.id))}
                                                className="accent-[var(--brand-gold)]"
                                            />
                                            <span className="text-[var(--brand-gold)]">{icons[i] ?? icons[0]}</span>
                                            <span>
                                                <span className="block text-sm font-medium text-[var(--brand-ink)]">{courier.name}</span>
                                                <span className="text-xs text-[var(--brand-muted)]">Cost included in order total</span>
                                            </span>
                                        </label>
                                    );
                                })}
                            </div>
                        </Section>
                    )}

                    {/* Items review */}
                    <ItemsReview items={items} />

                    {/* Payment */}
                    <PaymentSection value={data.payment_method as PaymentMethod} onChange={(m) => setData('payment_method', m)} />

                    {/* Order note */}
                    <Section title="Order Note (optional)">
                        <Field label={hasFabricItems ? 'Note for tailor / delivery' : 'Note for delivery'}>
                            <textarea
                                value={data.note}
                                onChange={(e) => setData('note', e.target.value)}
                                rows={3}
                                className={inputCls()}
                                placeholder={t.checkout.notePlaceholder}
                            />
                        </Field>
                    </Section>

                    {/* Confirm checklist */}
                    <Section title="Confirm Before Placing Order">
                        <div className="space-y-2.5">
                            {(
                                [
                                    ['length', 'I confirmed fabric length or size.', hasFabricItems],
                                    ['usage', 'I confirmed usage: Punjabi, Shirt, Kabli, or ready-made.', hasFabricItems],
                                    ['color', 'I understand colour can vary by screen and lighting.', true],
                                    ['delivery', 'Delivery address and phone number are correct.', true],
                                ] as [keyof typeof checks, string, boolean][]
                            )
                                .filter(([, , visible]) => visible)
                                .map(([key, label]) => (
                                    <label key={key} className="flex cursor-pointer items-start gap-2.5">
                                        <span
                                            onClick={() => setChecks((c) => ({ ...c, [key]: !c[key] }))}
                                            className={`mt-0.5 flex h-4 w-4 shrink-0 cursor-pointer items-center justify-center rounded border-2 transition ${checks[key] ? 'border-[var(--brand-gold)] bg-[var(--brand-gold)]' : 'border-slate-300'}`}
                                        >
                                            {checks[key] && <Check size={10} className="text-white" />}
                                        </span>
                                        <span className="text-sm text-[var(--brand-ink)]">{label}</span>
                                    </label>
                                ))}
                        </div>
                    </Section>

                    {/* Submit */}
                    <div className="rounded-lg border border-slate-200 bg-white p-4">
                        <label className="flex cursor-pointer items-start gap-2.5 text-sm text-[var(--brand-muted)]">
                            <input
                                checked={acceptTerms}
                                onChange={(e) => setAcceptTerms(e.target.checked)}
                                type="checkbox"
                                className="mt-0.5 accent-[var(--brand-gold)]"
                            />
                            I agree to the terms, privacy policy, and return policy.
                        </label>
                        <button
                            type="submit"
                            disabled={!canSubmit}
                            className="mt-4 flex h-11 w-full items-center justify-center gap-2 rounded-md bg-slate-900 text-sm font-semibold text-white transition hover:bg-slate-800 disabled:cursor-not-allowed disabled:opacity-40"
                        >
                            <Lock size={14} />
                            {processing ? t.checkout.placingOrder : t.checkout.placeOrder}
                        </button>
                        {!canSubmit && (
                            <p className="mt-2 text-center text-xs text-slate-400">Complete all required fields, checklist, and terms.</p>
                        )}
                    </div>
                </div>

                {/* Right: sticky summary (desktop) */}
                <div className="hidden lg:block">
                    <div className="sticky top-6">
                        <OrderSummary items={items} totals={totals} />
                    </div>
                </div>
            </form>
        </div>
    );
}

export default function CheckoutIndex(props: { items: CartItem[]; totals: CartTotals; couriers: Courier[] }) {
    return (
        <LangProvider>
            <CheckoutPage {...props} />
        </LangProvider>
    );
}
