import { MessageCircle, ShoppingCart, X } from 'lucide-react';
import { useEffect, useState } from 'react';

import type { Product } from '@/types';

// ─── Config ───────────────────────────────────────────────────────────────────
// Change WHATSAPP_NUMBER to your number (digits only, include country code, no + or spaces)
// Example: '8801712345678' for Bangladesh
const WHATSAPP_NUMBER = '8801XXXXXXXXX';

// ─── Types ────────────────────────────────────────────────────────────────────
type GarmentType = 'panjabi' | 'shirt' | 'kabli';

interface Garment {
    type: GarmentType;
    label: string;
    labelBn: string;
    viewBox: string;
    // fill-rule="evenodd": outer silhouette + neck hole subpath combined
    path: string;
}

// ─── Garment SVG path definitions ─────────────────────────────────────────────
// Each path = outer garment silhouette (CW) + neck opening hole (CW, evenodd creates transparent hole)
// To customize shapes, edit the 'd' strings below.
const GARMENTS: Garment[] = [
    {
        type: 'panjabi',
        label: 'Panjabi',
        labelBn: 'পাঞ্জাবি',
        viewBox: '0 0 280 480',
        // Long kurta: long sleeves, long body to knee, round neck
        path:
            'M 140,22 L 105,40 Q 60,52 35,72 L 20,85 L 4,195 L 38,207 L 45,230 L 42,458 L 238,458 L 235,230 L 242,207 L 276,195 L 260,85 Q 220,52 175,40 L 140,22 Z' +
            ' M 140,40 Q 162,46 170,62 Q 160,84 140,90 Q 120,84 110,62 Q 118,46 140,40 Z',
    },
    {
        type: 'shirt',
        label: 'Shirt',
        labelBn: 'শার্ট',
        viewBox: '0 0 280 410',
        // Regular dress shirt: long sleeves, hip-length, V-neck opening
        path:
            'M 140,22 L 106,40 Q 62,52 38,72 L 22,84 L 5,192 L 40,204 L 48,228 L 46,388 L 234,388 L 232,228 L 240,204 L 275,192 L 258,84 Q 218,52 174,40 L 140,22 Z' +
            ' M 115,45 L 140,80 L 165,45 Z',
    },
    {
        type: 'kabli',
        label: 'Kabli',
        labelBn: 'কাবলি',
        viewBox: '0 0 280 430',
        // Sleeveless vest: curved armholes, hip-length, V-neck opening
        path:
            'M 140,22 L 108,40 Q 72,50 52,68 L 36,90 Q 22,140 28,190 L 34,215 L 32,408 L 248,408 L 246,215 L 252,190 Q 258,140 244,90 L 228,68 Q 208,50 172,40 L 140,22 Z' +
            ' M 112,45 L 140,86 L 168,45 Z',
    },
];

// ─── WhatsApp SVG icon ────────────────────────────────────────────────────────
function WhatsAppIcon() {
    return (
        <svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true">
            <path d="M17.472 14.382c-.297-.149-1.758-.867-2.03-.967-.273-.099-.471-.148-.67.15-.197.297-.767.966-.94 1.164-.173.199-.347.223-.644.075-.297-.15-1.255-.463-2.39-1.475-.883-.788-1.48-1.761-1.653-2.059-.173-.297-.018-.458.13-.606.134-.133.298-.347.446-.52.149-.174.198-.298.298-.497.099-.198.05-.371-.025-.52-.075-.149-.669-1.612-.916-2.207-.242-.579-.487-.5-.669-.51-.173-.008-.371-.01-.57-.01-.198 0-.52.074-.792.372-.272.297-1.04 1.016-1.04 2.479 0 1.462 1.065 2.875 1.213 3.074.149.198 2.096 3.2 5.077 4.487.709.306 1.262.489 1.694.625.712.227 1.36.195 1.871.118.571-.085 1.758-.719 2.006-1.413.248-.694.248-1.289.173-1.413-.074-.124-.272-.198-.57-.347m-5.421 7.403h-.004a9.87 9.87 0 01-5.031-1.378l-.361-.214-3.741.982.998-3.648-.235-.374a9.86 9.86 0 01-1.51-5.26c.001-5.45 4.436-9.884 9.888-9.884 2.64 0 5.122 1.03 6.988 2.898a9.825 9.825 0 012.893 6.994c-.003 5.45-4.437 9.884-9.885 9.884m8.413-18.297A11.815 11.815 0 0012.05 0C5.495 0 .16 5.335.157 11.892c0 2.096.547 4.142 1.588 5.945L.057 24l6.305-1.654a11.882 11.882 0 005.683 1.448h.005c6.554 0 11.89-5.335 11.893-11.893a11.821 11.821 0 00-3.48-8.413z" />
        </svg>
    );
}

// ─── Garment SVG renderer ─────────────────────────────────────────────────────
function GarmentSVG({
    garment,
    fabricUrl,
    productName,
}: {
    garment: Garment;
    fabricUrl: string;
    productName: string;
}) {
    const id = `fp-${garment.type}`;
    const [, , vwStr, vhStr] = garment.viewBox.split(' ');
    const vw = Number(vwStr);
    const vh = Number(vhStr);

    return (
        <svg
            viewBox={garment.viewBox}
            xmlns="http://www.w3.org/2000/svg"
            className="h-full w-full"
            aria-label={`${productName} previewed as ${garment.label}`}
        >
            <defs>
                {/* Fabric image fills the full garment area without tiling */}
                <pattern id={`${id}-tex`} patternUnits="userSpaceOnUse" width={vw} height={vh} x="0" y="0">
                    <image href={fabricUrl} x="0" y="0" width={vw} height={vh} preserveAspectRatio="xMidYMid slice" />
                </pattern>

                {/* Left-to-right fold shading for depth */}
                <linearGradient id={`${id}-fold`} x1="0%" y1="0%" x2="100%" y2="0%">
                    <stop offset="0%" stopColor="rgba(0,0,0,0.20)" />
                    <stop offset="14%" stopColor="rgba(0,0,0,0)" />
                    <stop offset="50%" stopColor="rgba(255,255,255,0.05)" />
                    <stop offset="86%" stopColor="rgba(0,0,0,0)" />
                    <stop offset="100%" stopColor="rgba(0,0,0,0.20)" />
                </linearGradient>

                {/* Top-to-bottom lighting */}
                <linearGradient id={`${id}-light`} x1="0%" y1="0%" x2="0%" y2="100%">
                    <stop offset="0%" stopColor="rgba(255,255,255,0.14)" />
                    <stop offset="55%" stopColor="rgba(0,0,0,0)" />
                    <stop offset="100%" stopColor="rgba(0,0,0,0.12)" />
                </linearGradient>

                {/* Drop shadow */}
                <filter id={`${id}-shadow`} x="-10%" y="-4%" width="120%" height="112%">
                    <feDropShadow dx="0" dy="8" stdDeviation="12" floodColor="rgba(31,42,48,0.28)" />
                </filter>
            </defs>

            {/* Fabric fill layer */}
            <path d={garment.path} fillRule="evenodd" fill={`url(#${id}-tex)`} filter={`url(#${id}-shadow)`} />

            {/* Fold shading overlay */}
            <path d={garment.path} fillRule="evenodd" fill={`url(#${id}-fold)`} />

            {/* Top-bottom light overlay */}
            <path d={garment.path} fillRule="evenodd" fill={`url(#${id}-light)`} />

            {/* Garment outline */}
            <path d={garment.path} fillRule="evenodd" fill="none" stroke="rgba(31,42,48,0.22)" strokeWidth="1.2" />

            {/* Panjabi: center seam */}
            {garment.type === 'panjabi' && (
                <line x1="140" y1="92" x2="140" y2="458" stroke="rgba(0,0,0,0.10)" strokeWidth="0.9" strokeDasharray="5,8" />
            )}

            {/* Shirt: button placket + buttons */}
            {garment.type === 'shirt' && (
                <>
                    <line x1="140" y1="82" x2="140" y2="388" stroke="rgba(0,0,0,0.12)" strokeWidth="0.9" />
                    {[108, 140, 172, 204, 236, 268, 300, 332, 364].filter((y) => y > 82 && y < 388).map((y) => (
                        <circle key={y} cx="140" cy={y} r="3" fill="rgba(0,0,0,0.18)" />
                    ))}
                </>
            )}

            {/* Kabli: center line + buttons */}
            {garment.type === 'kabli' && (
                <>
                    <line x1="140" y1="88" x2="140" y2="408" stroke="rgba(0,0,0,0.10)" strokeWidth="0.9" />
                    {[110, 150, 190, 230, 270, 310, 350, 390].filter((y) => y > 88 && y < 408).map((y) => (
                        <circle key={y} cx="140" cy={y} r="3" fill="rgba(0,0,0,0.18)" />
                    ))}
                </>
            )}
        </svg>
    );
}

// ─── Main Modal ───────────────────────────────────────────────────────────────
export default function FabricPreviewModal({
    product,
    onClose,
}: {
    product: Product | null;
    onClose: () => void;
}) {
    const [garmentType, setGarmentType] = useState<GarmentType>('panjabi');
    const garment = GARMENTS.find((g) => g.type === garmentType)!;

    // Lock scroll & handle Escape key
    useEffect(() => {
        if (!product) return;
        document.body.style.overflow = 'hidden';
        const onKey = (e: KeyboardEvent) => { if (e.key === 'Escape') onClose(); };
        document.addEventListener('keydown', onKey);
        return () => {
            document.body.style.overflow = '';
            document.removeEventListener('keydown', onKey);
        };
    }, [product, onClose]);

    // Reset to panjabi whenever a new product is opened
    useEffect(() => {
        setGarmentType('panjabi');
    }, [product?.id]);

    if (!product) return null;

    const img = product.images?.find((i) => i.is_primary) ?? product.images?.[0];
    const fabricUrl = img ? `/storage/${img.image}` : '';

    const garmentLabel = GARMENTS.find((g) => g.type === garmentType)?.label ?? 'Panjabi';
    const waMsg = encodeURIComponent(
        `Hello! I am interested in *${product.name}*.\n\nI previewed it as a *${garmentLabel}* on your website and would like to discuss ordering or custom stitching. Please share details and pricing.`,
    );
    const waUrl = `https://wa.me/${WHATSAPP_NUMBER}?text=${waMsg}`;

    return (
        <div
            className="fixed inset-0 z-50 flex items-end sm:items-center justify-center"
            style={{ backgroundColor: 'rgba(26,31,35,0.72)', backdropFilter: 'blur(5px)' }}
            role="dialog"
            aria-modal="true"
            aria-label="Fabric outfit preview"
        >
            {/* Backdrop click to close */}
            <div className="absolute inset-0" onClick={onClose} aria-hidden="true" />

            {/* Modal panel */}
            <div
                className="relative z-10 flex w-full flex-col overflow-hidden rounded-t-3xl sm:mx-4 sm:max-w-4xl sm:rounded-2xl"
                style={{ backgroundColor: 'var(--brand-ivory)', maxHeight: '92dvh' }}
            >
                {/* ── Header ── */}
                <div
                    className="flex flex-shrink-0 items-center justify-between px-5 py-4 sm:px-7"
                    style={{ borderBottom: '1px solid var(--brand-line)' }}
                >
                    <div>
                        <div className="eyebrow text-[10px]" style={{ color: 'var(--brand-gold)' }}>
                            ♦ Fabric Preview
                        </div>
                        <h2
                            className="font-display mt-0.5 line-clamp-1 text-[18px] leading-snug sm:text-[22px]"
                            style={{ color: 'var(--brand-ink)' }}
                        >
                            See This Fabric as Panjabi, Shirt or Kabli
                        </h2>
                    </div>
                    <button
                        onClick={onClose}
                        aria-label="Close preview"
                        className="ml-4 flex h-10 w-10 flex-shrink-0 items-center justify-center rounded-full transition hover:bg-black/8"
                        style={{ color: 'var(--brand-slate)' }}
                    >
                        <X size={18} />
                    </button>
                </div>

                {/* ── Body ── */}
                <div className="flex-1 overflow-y-auto">
                    <div className="flex flex-col md:flex-row">

                        {/* Left: garment preview area */}
                        <div
                            className="flex flex-col items-center justify-start px-6 py-8 md:flex-1 md:py-10"
                            style={{ backgroundColor: 'var(--brand-cream)' }}
                        >
                            {/* Garment type tabs */}
                            <div
                                className="mb-7 flex gap-1 rounded-full p-1"
                                style={{ backgroundColor: 'rgba(31,42,48,0.08)' }}
                                role="group"
                                aria-label="Select garment type"
                            >
                                {GARMENTS.map((g) => (
                                    <button
                                        key={g.type}
                                        onClick={() => setGarmentType(g.type)}
                                        aria-pressed={garmentType === g.type}
                                        className="rounded-full px-5 py-2 text-[13px] font-medium transition-all duration-200"
                                        style={{
                                            backgroundColor: garmentType === g.type ? 'var(--brand-slate)' : 'transparent',
                                            color: garmentType === g.type ? 'var(--brand-ivory)' : 'var(--brand-muted)',
                                        }}
                                    >
                                        {g.label}
                                    </button>
                                ))}
                            </div>

                            {/* SVG garment with fabric texture */}
                            <div className="w-full" style={{ maxWidth: '200px' }}>
                                {fabricUrl ? (
                                    <GarmentSVG garment={garment} fabricUrl={fabricUrl} productName={product.name} />
                                ) : (
                                    <div
                                        className="flex items-center justify-center ph-stripe"
                                        style={{ aspectRatio: '3/5' }}
                                    >
                                        <span style={{ color: 'var(--brand-muted)', fontSize: 12 }}>No image</span>
                                    </div>
                                )}
                            </div>

                            {/* Garment name below mockup */}
                            <div className="mt-5 text-center">
                                <div className="font-display text-[24px]" style={{ color: 'var(--brand-ink)' }}>
                                    {garment.label}
                                </div>
                                <div className="mt-0.5 text-[14px]" style={{ color: 'var(--brand-muted)' }}>
                                    {garment.labelBn}
                                </div>
                            </div>
                        </div>

                        {/* Right: product info + CTAs */}
                        <div className="flex flex-col gap-5 p-6 md:w-[290px] md:p-8">

                            {/* Selected fabric swatch */}
                            <div>
                                <div className="eyebrow mb-2 text-[10px]" style={{ color: 'var(--brand-muted)' }}>
                                    Selected Fabric
                                </div>
                                <div className="flex items-center gap-3">
                                    {img && (
                                        <div
                                            className="h-14 w-14 flex-shrink-0 overflow-hidden"
                                            style={{ border: '2px solid var(--brand-line)' }}
                                        >
                                            <img
                                                src={`/storage/${img.image}`}
                                                alt={product.name}
                                                className="h-full w-full object-cover"
                                            />
                                        </div>
                                    )}
                                    <div>
                                        <div
                                            className="line-clamp-2 text-[15px] font-medium leading-snug"
                                            style={{ color: 'var(--brand-ink)' }}
                                        >
                                            {product.name}
                                        </div>
                                        <div className="mt-1 text-[14px]" style={{ color: 'var(--brand-gold)' }}>
                                            ৳ {Number(product.price).toLocaleString()}
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <div className="h-px" style={{ backgroundColor: 'var(--brand-line)' }} />

                            {/* Previewing as label */}
                            <div>
                                <div className="eyebrow mb-1 text-[10px]" style={{ color: 'var(--brand-muted)' }}>
                                    Previewing As
                                </div>
                                <div className="font-display text-[22px]" style={{ color: 'var(--brand-ink)' }}>
                                    {garment.label}
                                    <span className="ml-2 font-sans text-[15px]" style={{ color: 'var(--brand-muted)' }}>
                                        {garment.labelBn}
                                    </span>
                                </div>
                            </div>

                            {/* CTA buttons */}
                            <div className="flex flex-col gap-2.5">
                                <a
                                    href={`/products/${product.slug}`}
                                    className="flex h-12 items-center justify-center gap-2.5 eyebrow text-[11px] tracking-[0.14em] transition-opacity hover:opacity-85"
                                    style={{ backgroundColor: 'var(--brand-slate)', color: 'var(--brand-ivory)' }}
                                >
                                    <ShoppingCart size={15} />
                                    Buy This Fabric
                                </a>

                                <a
                                    href={waUrl}
                                    target="_blank"
                                    rel="noopener noreferrer"
                                    className="flex h-12 items-center justify-center gap-2.5 eyebrow text-[11px] tracking-[0.14em] transition-opacity hover:opacity-90"
                                    style={{ backgroundColor: '#25D366', color: '#fff' }}
                                >
                                    <WhatsAppIcon />
                                    Order Custom Stitching
                                </a>

                                <a
                                    href={waUrl}
                                    target="_blank"
                                    rel="noopener noreferrer"
                                    className="flex h-12 items-center justify-center gap-2.5 border eyebrow text-[11px] tracking-[0.14em] transition-colors"
                                    style={{ borderColor: 'var(--brand-line)', color: 'var(--brand-muted)' }}
                                    onMouseEnter={(e) => (e.currentTarget.style.borderColor = 'var(--brand-gold)')}
                                    onMouseLeave={(e) => (e.currentTarget.style.borderColor = 'var(--brand-line)')}
                                >
                                    <MessageCircle size={15} style={{ color: 'var(--brand-gold)' }} />
                                    Contact on WhatsApp
                                </a>
                            </div>

                            {/* Disclaimer */}
                            <p
                                className="rounded p-3 text-[11px] leading-relaxed"
                                style={{
                                    backgroundColor: 'rgba(184,137,63,0.06)',
                                    color: 'var(--brand-muted)',
                                    border: '1px solid rgba(184,137,63,0.14)',
                                }}
                            >
                                This preview is for visual guidance only. Actual stitched product may vary depending on cutting, lighting, fabric texture, and tailoring.
                            </p>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    );
}
