import React, { useState, useEffect } from 'react';
import { useParams, useSearchParams, Link } from 'react-router-dom';
import { shipmentApi } from '../api/shipmentApi';
import IconTruck from '../components/Icon/IconTruck';
import IconCopy from '../components/Icon/IconCopy';
import IconSearch from '../components/Icon/IconSearch';
import IconRefresh from '../components/Icon/IconRefresh';
import IconMapPin from '../components/Icon/IconMapPin';
import IconCalendar from '../components/Icon/IconCalendar';
import IconPhone from '../components/Icon/IconPhone';
import IconMail from '../components/Icon/IconMail';
import IconWhatsapp from '../components/Icon/IconWhatsapp';
import IconLink from '../components/Icon/IconLink';
import IconChecks from '../components/Icon/IconChecks';
import Swal from 'sweetalert2';

const PublicTrackOrder: React.FC = () => {
    const { trackingId } = useParams<{ trackingId?: string }>();
    const [searchParams, setSearchParams] = useSearchParams();
    const queryParamId = searchParams.get('id') || searchParams.get('awb') || searchParams.get('order');

    const activeId = trackingId || queryParamId || '';

    const [searchInput, setSearchInput] = useState(activeId);
    const [loading, setLoading] = useState(false);
    const [error, setError] = useState<string | null>(null);
    const [trackingData, setTrackingData] = useState<any>(null);
    const [copiedAwb, setCopiedAwb] = useState(false);

    const fetchTracking = async (idToFetch: string) => {
        if (!idToFetch.trim()) return;
        setLoading(true);
        setError(null);
        try {
            const res = await shipmentApi.getPublicTracking(idToFetch.trim());
            if (res.success && res.data) {
                setTrackingData(res.data);
            } else {
                setError(res.message || 'No tracking information found for this shipment.');
                setTrackingData(null);
            }
        } catch (err: any) {
            console.error('Tracking fetch error:', err);
            setError(err.response?.data?.message || 'Unable to locate shipment. Please check your AWB number or Order ID.');
            setTrackingData(null);
        } finally {
            setLoading(false);
        }
    };

    useEffect(() => {
        if (activeId) {
            setSearchInput(activeId);
            fetchTracking(activeId);
        }
    }, [activeId]);

    const handleSearch = (e: React.FormEvent) => {
        e.preventDefault();
        if (searchInput.trim()) {
            setSearchParams({ id: searchInput.trim() });
            fetchTracking(searchInput.trim());
        }
    };

    const handleCopyAwb = () => {
        if (!trackingData?.awb_code) return;
        navigator.clipboard.writeText(trackingData.awb_code);
        setCopiedAwb(true);
        setTimeout(() => setCopiedAwb(false), 2000);
    };

    // Calculate progress step
    const currentStep = (() => {
        const st = (trackingData?.status || '').toUpperCase();
        if (st === 'DELIVERED') return 4;
        if (st === 'OUT FOR DELIVERY') return 3;
        if (st === 'IN TRANSIT') return 2;
        return 1;
    })();

    const activities = Array.isArray(trackingData?.tracking_data) ? trackingData.tracking_data : [];

    return (
        <div className="min-h-screen bg-[#FDFBF9] text-slate-800 font-sans flex flex-col justify-between selection:bg-[#990000] selection:text-white">
            {/* TOP HEADER */}
            <header className="bg-white border-b border-[#ECE2D2]/80 sticky top-0 z-30 shadow-2xs backdrop-blur-md bg-white/95">
                <div className="max-w-4xl mx-auto px-4 py-3.5 flex items-center justify-between">
                    <div className="flex items-center gap-3">
                        <img
                            src="/assets/images/shas-Logo.png"
                            alt="Sha's Jewellery"
                            className="h-10 md:h-12 w-auto object-contain"
                            onError={(e: any) => {
                                e.target.src = '/assets/images/auth/shas-Logo.png';
                            }}
                        />
                        <div className="border-l border-slate-200 pl-3">
                            <span className="text-xs md:text-sm font-black text-[#461901] tracking-tight block">
                                Consignment &amp; Order Tracking
                            </span>
                            <span className="text-[10px] md:text-[11px] font-semibold text-[#8C5839]">
                                Official Customer Portal • Sha's Jewellery
                            </span>
                        </div>
                    </div>

                    <a
                        href={`https://wa.me/919840012345?text=${encodeURIComponent(`Hello Sha's Jewellery, I would like an update on my shipment ${activeId || ''}`)}`}
                        target="_blank"
                        rel="noreferrer"
                        className="hidden sm:inline-flex items-center gap-1.5 px-3 py-1.5 rounded-full bg-emerald-50 text-emerald-700 border border-emerald-200 text-xs font-bold hover:bg-emerald-100 transition shadow-2xs"
                    >
                        <IconWhatsapp className="w-3.5 h-3.5" />
                        <span>Support WhatsApp</span>
                    </a>
                </div>
            </header>

            {/* MAIN CONTENT AREA */}
            <main className="flex-1 max-w-4xl w-full mx-auto px-4 py-6 md:py-8 space-y-6">
                {/* SEARCH INPUT BAR */}
                <div className="bg-white border border-[#E9DDC9] rounded-2xl p-4 md:p-5 shadow-xs">
                    <form onSubmit={handleSearch} className="flex flex-col sm:flex-row items-center gap-2.5">
                        <div className="relative flex-1 w-full">
                            <div className="absolute inset-y-0 left-0 pl-3.5 flex items-center pointer-events-none text-slate-400">
                                <IconSearch className="w-4 h-4" />
                            </div>
                            <input
                                type="text"
                                required
                                value={searchInput}
                                onChange={(e) => setSearchInput(e.target.value)}
                                placeholder="Enter India Post Barcode (e.g. SP...IN, CT...IN) or Order #..."
                                className="w-full text-xs md:text-sm font-semibold pl-10 pr-4 py-2.5 rounded-xl border border-slate-200 focus:outline-none focus:ring-2 focus:ring-[#990000] focus:border-transparent transition placeholder:font-normal placeholder:text-slate-400"
                            />
                        </div>

                        <button
                            type="submit"
                            disabled={loading}
                            className="w-full sm:w-auto px-5 py-2.5 rounded-xl text-xs font-bold text-white bg-[#990000] hover:bg-[#800000] active:scale-95 transition shadow-sm flex items-center justify-center gap-2 cursor-pointer disabled:opacity-60 shrink-0"
                        >
                            {loading ? (
                                <>
                                    <IconRefresh className="w-4 h-4 animate-spin" />
                                    <span>Tracking...</span>
                                </>
                            ) : (
                                <>
                                    <IconTruck className="w-4 h-4" />
                                    <span>Track Parcel</span>
                                </>
                            )}
                        </button>
                    </form>
                </div>

                {/* ERROR STATE */}
                {error && !loading && (
                    <div className="p-5 rounded-2xl border border-rose-200 bg-rose-50/70 text-rose-900 space-y-2 text-center">
                        <p className="text-sm font-extrabold">{error}</p>
                        <p className="text-xs text-rose-700">
                            Please check if your AWB tracking code or order number was entered correctly, or contact our customer support for help.
                        </p>
                    </div>
                )}

                {/* LOADING STATE */}
                {loading && (
                    <div className="py-16 text-center space-y-3">
                        <div className="w-12 h-12 mx-auto rounded-full border-3 border-[#990000]/20 border-t-[#990000] animate-spin"></div>
                        <p className="text-xs font-bold text-slate-600">
                            Fetching real-time tracking details from India Post...
                        </p>
                    </div>
                )}

                {/* TRACKING DETAILS VIEW */}
                {trackingData && !loading && (
                    <div className="space-y-6">
                        {/* HERO SHIPMENT CARD */}
                        <div className="bg-white rounded-3xl border border-[#E9DDC9] shadow-sm overflow-hidden">
                            {/* Card Header Banner */}
                            <div className="bg-gradient-to-r from-[#5B1F00] via-[#7B2E05] to-[#8C3A0C] text-white p-5 md:p-6 flex flex-col md:flex-row md:items-center justify-between gap-4">
                                <div className="space-y-1">
                                    <span className="text-[11px] font-extrabold uppercase tracking-widest text-amber-200 block">
                                        {trackingData.courier_name || 'India Speed Post'}
                                    </span>
                                    <h1 className="text-xl md:text-2xl font-black text-white flex items-center gap-2 font-mono">
                                        AWB: {trackingData.awb_code || 'Pending'}
                                    </h1>
                                    <p className="text-xs text-amber-100/90">
                                        Order <strong>{trackingData.order_no}</strong> • For <strong>{trackingData.customer_name}</strong>
                                    </p>
                                </div>

                                <div className="flex flex-wrap items-center gap-2 self-start md:self-center">
                                    <span className={`px-3 py-1.5 rounded-full text-xs font-black uppercase tracking-wider border shadow-xs ${
                                        trackingData.status === 'DELIVERED'
                                            ? 'bg-emerald-500 text-white border-emerald-400'
                                            : 'bg-amber-400 text-amber-950 border-amber-300'
                                    }`}>
                                        ● {trackingData.status || 'IN TRANSIT'}
                                    </span>

                                    {trackingData.awb_code && (
                                        <button
                                            type="button"
                                            onClick={handleCopyAwb}
                                            className="px-3 py-1.5 rounded-full bg-white/15 hover:bg-white/25 text-white text-xs font-bold transition flex items-center gap-1.5 border border-white/20 cursor-pointer"
                                        >
                                            <IconCopy className="w-3.5 h-3.5" />
                                            <span>{copiedAwb ? 'Copied!' : 'Copy AWB'}</span>
                                        </button>
                                    )}
                                </div>
                            </div>

                            {/* Key Shipment Metas */}
                            <div className="grid grid-cols-2 md:grid-cols-3 divide-x divide-y md:divide-y-0 divide-slate-100 border-b border-slate-100 bg-[#FAF7F2]">
                                <div className="p-4 space-y-1">
                                    <span className="text-[10px] font-bold uppercase tracking-wider text-slate-400 flex items-center gap-1">
                                        <IconCalendar className="w-3.5 h-3.5" />
                                        Estimated Delivery
                                    </span>
                                    <p className="text-sm font-extrabold text-slate-800">
                                        {trackingData.estimated_delivery || 'In 2-4 Days'}
                                    </p>
                                </div>

                                <div className="p-4 space-y-1">
                                    <span className="text-[10px] font-bold uppercase tracking-wider text-slate-400 flex items-center gap-1">
                                        <IconMapPin className="w-3.5 h-3.5" />
                                        Destination
                                    </span>
                                    <p className="text-sm font-extrabold text-slate-800 truncate">
                                        {trackingData.city || 'Tamil Nadu'}{trackingData.pincode ? ` (${trackingData.pincode})` : ''}
                                    </p>
                                </div>

                                <div className="col-span-2 md:col-span-1 p-4 space-y-1">
                                    <span className="text-[10px] font-bold uppercase tracking-wider text-slate-400 flex items-center gap-1">
                                        <IconTruck className="w-3.5 h-3.5" />
                                        Booking Facility
                                    </span>
                                    <p className="text-sm font-extrabold text-slate-800">
                                        Madurai Palace SO (625001)
                                    </p>
                                </div>
                            </div>

                            {/* VISUAL 4-STEP PROGRESS BAR */}
                            <div className="p-5 md:p-6 border-b border-slate-100 space-y-4">
                                <h3 className="text-xs font-extrabold uppercase text-slate-700 tracking-wider">
                                    Delivery Journey
                                </h3>

                                <div className="grid grid-cols-4 gap-2 text-center relative">
                                    {/* Line connecting */}
                                    <div className="absolute top-4 left-6 right-6 h-0.5 bg-slate-200 -z-0">
                                        <div
                                            className="h-full bg-emerald-600 transition-all duration-500"
                                            style={{ width: `${((currentStep - 1) / 3) * 100}%` }}
                                        />
                                    </div>

                                    {[
                                        { label: 'Booked', desc: 'Madurai SO' },
                                        { label: 'In Transit', desc: 'Sorting Hub' },
                                        { label: 'Out for Delivery', desc: 'Local Postman' },
                                        { label: 'Delivered', desc: 'Package Received' },
                                    ].map((step, idx) => {
                                        const isDone = currentStep >= idx + 1;
                                        const isCurrent = currentStep === idx + 1;
                                        return (
                                            <div key={idx} className="relative z-10 flex flex-col items-center space-y-1.5">
                                                <div
                                                    className={`w-8 h-8 rounded-full border-2 flex items-center justify-center font-bold text-xs transition-all ${
                                                        isDone
                                                            ? 'bg-emerald-600 border-emerald-600 text-white shadow-xs'
                                                            : 'bg-white border-slate-300 text-slate-400'
                                                    } ${isCurrent ? 'ring-4 ring-emerald-100 scale-105' : ''}`}
                                                >
                                                    {isDone ? '✓' : idx + 1}
                                                </div>
                                                <span className={`text-[11px] md:text-xs font-extrabold ${isDone ? 'text-slate-900' : 'text-slate-400'}`}>
                                                    {step.label}
                                                </span>
                                                <span className="text-[10px] text-slate-400 hidden sm:block">
                                                    {step.desc}
                                                </span>
                                            </div>
                                        );
                                    })}
                                </div>
                            </div>

                            {/* DETAILED POSTAL SCAN LOG */}
                            <div className="p-5 md:p-6 space-y-4">
                                <div className="flex items-center justify-between">
                                    <h3 className="text-xs font-black uppercase text-slate-800 tracking-wider flex items-center gap-2">
                                        <span className="w-2 h-2 rounded-full bg-emerald-500 animate-pulse"></span>
                                        Live India Post Scan Milestones
                                    </h3>
                                    <span className="text-[10px] font-mono text-slate-500 font-bold bg-slate-100 px-2 py-0.5 rounded">
                                        {activities.length} Scans Recorded
                                    </span>
                                </div>

                                {activities.length > 0 ? (
                                    <div className="relative pl-6 space-y-4 before:content-[''] before:absolute before:left-2.5 before:top-2 before:bottom-2 before:w-0.5 before:bg-slate-200">
                                        {activities.map((act: any, idx: number) => {
                                            const isLatest = idx === activities.length - 1;
                                            return (
                                                <div key={idx} className="relative group">
                                                    <div
                                                        className={`absolute -left-6 top-1 w-3.5 h-3.5 rounded-full border-2 flex items-center justify-center transition ${
                                                            isLatest
                                                                ? 'bg-[#990000] border-red-200 shadow-xs ring-4 ring-red-100'
                                                                : 'bg-emerald-500 border-white shadow-2xs'
                                                        }`}
                                                    />

                                                    <div className="bg-slate-50 border border-slate-200/80 rounded-xl p-3.5 space-y-1 transition hover:bg-white hover:shadow-xs">
                                                        <div className="flex items-center justify-between gap-2 flex-wrap">
                                                            {act.location ? (
                                                                <span className="inline-flex items-center gap-1 text-[11px] font-extrabold text-[#990000] bg-red-100/70 px-2.5 py-0.5 rounded-md font-mono">
                                                                    📍 {act.location}
                                                                </span>
                                                            ) : (
                                                                <span className="text-[11px] font-bold text-slate-700">Postal Center</span>
                                                            )}

                                                            <span className="text-[10px] font-mono text-slate-500 font-semibold">
                                                                {act.date}
                                                            </span>
                                                        </div>

                                                        <p className="text-xs font-bold text-slate-900 pt-0.5">
                                                            {act.status}
                                                        </p>

                                                        {act.activity && (
                                                            <p className="text-[11px] text-slate-600 leading-relaxed">
                                                                {act.activity}
                                                            </p>
                                                        )}
                                                    </div>
                                                </div>
                                            );
                                        })}
                                    </div>
                                ) : (
                                    <div className="p-6 text-center bg-slate-50 border border-dashed border-slate-200 rounded-2xl space-y-2">
                                        <div className="w-8 h-8 rounded-full bg-red-100 text-[#990000] flex items-center justify-center mx-auto text-sm font-bold">
                                            📮
                                        </div>
                                        <p className="text-xs font-bold text-slate-800">
                                            Awaiting First Post Office Scan
                                        </p>
                                        <p className="text-[11px] text-slate-500 max-w-sm mx-auto">
                                            Package registered in ERP. Real-time post office checkpoints will appear here as soon as scanned at the counter.
                                        </p>
                                    </div>
                                )}
                            </div>

                            {/* OFFICIAL GOV VERIFICATION LINK */}
                            <div className="p-4 bg-[#FAF7F2] border-t border-slate-100 flex flex-col sm:flex-row items-center justify-between gap-3 text-xs">
                                <span className="text-slate-600 font-medium text-[11px]">
                                    Want to verify directly on the Department of Posts website?
                                </span>

                                <a
                                    href="https://www.indiapost.gov.in/_layouts/15/dop.portal.tracking/trackconsignment.aspx"
                                    target="_blank"
                                    rel="noreferrer"
                                    onClick={() => {
                                        if (trackingData.awb_code) {
                                            navigator.clipboard.writeText(trackingData.awb_code);
                                        }
                                    }}
                                    className="inline-flex items-center gap-1.5 font-bold text-[#990000] hover:text-red-900 hover:underline cursor-pointer"
                                >
                                    <span>Verify on indiapost.gov.in ↗</span>
                                </a>
                            </div>
                        </div>

                        {/* CUSTOMER SUPPORT CARD */}
                        <div className="bg-gradient-to-r from-red-50/60 via-white to-amber-50/50 border border-[#E9DDC9] rounded-2xl p-5 md:p-6 space-y-3">
                            <div className="flex items-center gap-2">
                                <span className="p-1 rounded-lg bg-[#990000] text-white">
                                    <IconPhone className="w-4 h-4" />
                                </span>
                                <h3 className="text-xs font-extrabold uppercase text-slate-900 tracking-wider">
                                    Need Assistance with Your Jewellery Delivery?
                                </h3>
                            </div>

                            <p className="text-xs text-slate-600 leading-relaxed">
                                Our support team is here to help you track your precious delivery. Contact us directly via phone, WhatsApp, or email.
                            </p>

                            <div className="grid grid-cols-1 sm:grid-cols-3 gap-2.5 pt-1">
                                <a
                                    href="tel:9840012345"
                                    className="flex items-center justify-center gap-1.5 py-2 px-3 rounded-xl bg-white border border-slate-200 text-xs font-bold text-slate-700 hover:bg-slate-50 transition shadow-2xs"
                                >
                                    <IconPhone className="w-3.5 h-3.5 text-[#990000]" />
                                    <span>+91 98400 12345</span>
                                </a>

                                <a
                                    href={`https://wa.me/919840012345?text=${encodeURIComponent(`Hello Sha's Jewellery, please help me with my order ${trackingData.order_no} (AWB: ${trackingData.awb_code})`)}`}
                                    target="_blank"
                                    rel="noreferrer"
                                    className="flex items-center justify-center gap-1.5 py-2 px-3 rounded-xl bg-emerald-50 border border-emerald-200 text-xs font-bold text-emerald-800 hover:bg-emerald-100 transition shadow-2xs"
                                >
                                    <IconWhatsapp className="w-3.5 h-3.5 text-emerald-600" />
                                    <span>WhatsApp Support</span>
                                </a>

                                <a
                                    href={`mailto:shasjewelery@gmail.com?subject=Inquiry on Order ${trackingData.order_no}`}
                                    className="flex items-center justify-center gap-1.5 py-2 px-3 rounded-xl bg-white border border-slate-200 text-xs font-bold text-slate-700 hover:bg-slate-50 transition shadow-2xs"
                                >
                                    <IconMail className="w-3.5 h-3.5 text-blue-600" />
                                    <span>Email Support</span>
                                </a>
                            </div>
                        </div>
                    </div>
                )}
            </main>

            {/* FOOTER */}
            <footer className="bg-white border-t border-slate-200 py-6 text-center text-xs text-slate-500 space-y-1">
                <p className="font-semibold text-slate-700">
                    © {new Date().getFullYear()} Sha's Jewellery. All rights reserved.
                </p>
                <p className="text-[11px] text-slate-400">
                    26/B 1st Floor, CMR Road, Munichalai, Madurai - 625009 • In partnership with Department of Posts, Gov. of India
                </p>
            </footer>
        </div>
    );
};

export default PublicTrackOrder;
