'use client';

import React, { Suspense, useEffect, useState } from 'react';
import { useSearchParams } from 'next/navigation';
import { Header } from '@/components/Header';
import { Footer } from '@/components/Footer';
import { useSiteSettings } from '@/context/SiteSettingsContext';
import api from '@/lib/api';
import { 
  Search, 
  Truck, 
  Calendar, 
  MapPin, 
  CreditCard, 
  Package, 
  AlertCircle, 
  Copy, 
  Check,
  ClipboardList,
  User,
  ShoppingBag,
  ShieldCheck
} from 'lucide-react';
import { motion, AnimatePresence } from 'framer-motion';

interface OrderItem {
  product_name: string;
  product_sku: string;
  price: number;
  quantity: number;
  image: string | null;
}

interface OrderHistoryLog {
  action: string;
  from_status: string | null;
  to_status: string;
  notes: string | null;
  created_at: string;
}

interface OrderDetails {
  id: number;
  order_number: string;
  customer_name: string;
  customer_phone: string;
  delivery_address: string;
  status: string;
  payment_status: string;
  payment_method: string;
  shipping_method: string;
  subtotal: number;
  shipping_cost: number;
  discount: number;
  grand_total: number;
  created_at: string;
  items: OrderItem[];
  history: OrderHistoryLog[];
  tracking_code: string | null;
}

function TrackOrderContent() {
  const { formatPrice } = useSiteSettings();
  const searchParams = useSearchParams();
  
  const [orderNumber, setOrderNumber] = useState('');
  const [phone, setPhone] = useState('');
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');
  const [order, setOrder] = useState<OrderDetails | null>(null);
  const [copied, setCopied] = useState(false);

  useEffect(() => {
    const orderParam = searchParams.get('orderNumber') || searchParams.get('order_number');
    const phoneParam = searchParams.get('phone');
    if (orderParam || phoneParam) {
      if (orderParam) setOrderNumber(orderParam);
      if (phoneParam) setPhone(phoneParam);
      handleTrack(orderParam || '', phoneParam || '');
    }
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  const handleTrackSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    if (!orderNumber.trim() && !phone.trim()) {
      setError('Please enter your order number or phone number.');
      return;
    }
    handleTrack(orderNumber.trim(), phone.trim());
  };

  const handleTrack = async (ordNum: string, phoneNum: string) => {
    setLoading(true);
    setError('');
    setOrder(null);
    try {
      const params: Record<string, string> = {};
      if (ordNum) params.order_number = ordNum;
      if (phoneNum) params.phone = phoneNum;
      const response = await api.get('/api/orders/track', { params });
      if (response.data?.success) {
        setOrder(response.data.data);
      } else {
        setError(response.data?.message || 'Failed to fetch tracking details.');
      }
    } catch (err: any) {
      setError(
        err.response?.data?.message ||
        'No order found with the provided details. Please check and try again.'
      );
    } finally {
      setLoading(false);
    }
  };

  const copyToClipboard = (text: string) => {
    navigator.clipboard.writeText(text);
    setCopied(true);
    setTimeout(() => setCopied(false), 2000);
  };

  const statusSteps = ['pending', 'processing', 'shipped', 'delivered'];

  const getStepIndex = (status: string) => {
    const s = status.toLowerCase();
    if (s === 'pending') return 0;
    if (s === 'processing') return 1;
    if (s === 'shipped') return 2;
    if (s === 'completed' || s === 'delivered') return 3;
    return -1;
  };

  const getStatusLabel = (status: string) => {
    const s = status.toLowerCase();
    if (s === 'pending') return 'Pending Approval';
    if (s === 'processing') return 'Processing & Packaging';
    if (s === 'shipped') return 'Shipped via Courier';
    if (s === 'completed' || s === 'delivered') return 'Delivered';
    if (s === 'cancelled') return 'Cancelled';
    return status;
  };

  const currentStep = order ? getStepIndex(order.status) : -1;

  return (
    <div className="bg-slate-50 min-h-screen flex flex-col" style={{ fontFamily: 'var(--font-open-sans), sans-serif' }}>
      <Header />

      <main className="flex-grow pb-24">
        {/* Banner */}
        <section className="bg-gradient-to-r from-[#115e59] via-[#0f766e] to-[#1e1b4b] text-white py-16 px-4 relative overflow-hidden text-center">
          <div className="absolute inset-0 bg-[radial-gradient(circle_at_30%_20%,_rgba(16,185,129,0.2)_0%,_transparent_65%)]" />
          <div className="absolute inset-0 opacity-5 bg-[linear-gradient(to_right,#ffffff_1px,transparent_1px),linear-gradient(to_bottom,#ffffff_1px,transparent_1px)] bg-[size:4rem_4rem]" />
          <div className="relative max-w-2xl mx-auto space-y-4">
            <div className="inline-flex items-center gap-2 px-3 py-1 bg-white/10 rounded-full text-xs font-medium tracking-wider uppercase backdrop-blur-sm">
              <Truck size={12} className="text-emerald-400" />
              Live Order Tracking
            </div>
            <h1 className="text-3xl sm:text-4xl font-semibold tracking-tight">Track Your Order</h1>
            <p className="text-xs sm:text-sm text-slate-200 font-medium max-w-lg mx-auto leading-relaxed">
              Enter your order code or phone number to check your package status in real-time.
            </p>
          </div>
        </section>

        {/* Search Form Card */}
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          <div className="max-w-xl mx-auto bg-white shadow-xl rounded-3xl border border-slate-100 p-6 sm:p-8 -mt-8 relative z-10">
            <form onSubmit={handleTrackSubmit} className="space-y-4">
              <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                <div className="space-y-1 text-left">
                  <label htmlFor="orderNumber" className="text-xs font-medium text-slate-500 uppercase tracking-wider">
                    Order Code <span className="text-slate-400 normal-case font-normal">(optional)</span>
                  </label>
                  <div className="relative">
                    <input
                      type="text"
                      id="orderNumber"
                      placeholder="e.g. ORD-100234"
                      value={orderNumber}
                      onChange={(e) => setOrderNumber(e.target.value)}
                      className="w-full text-sm px-3.5 py-2.5 pl-9 border border-slate-200 focus:border-emerald-500 rounded-xl outline-none text-slate-700 transition-all font-medium placeholder-slate-400 bg-slate-50/50"
                    />
                    <ClipboardList className="absolute left-3 top-3 text-slate-400" size={14} />
                  </div>
                </div>

                <div className="space-y-1 text-left">
                  <label htmlFor="phone" className="text-xs font-medium text-slate-500 uppercase tracking-wider">
                    Phone Number <span className="text-slate-400 normal-case font-normal">(optional)</span>
                  </label>
                  <div className="relative">
                    <input
                      type="text"
                      id="phone"
                      placeholder="e.g. 017XXXXXXXX"
                      value={phone}
                      onChange={(e) => setPhone(e.target.value)}
                      className="w-full text-sm px-3.5 py-2.5 pl-9 border border-slate-200 focus:border-emerald-500 rounded-xl outline-none text-slate-700 transition-all font-medium placeholder-slate-400 bg-slate-50/50"
                    />
                    <User className="absolute left-3 top-3 text-slate-400" size={14} />
                  </div>
                </div>
              </div>

              {error && (
                <div className="p-3.5 bg-rose-50 border border-rose-100 text-rose-700 rounded-2xl text-sm flex items-start gap-2 text-left">
                  <AlertCircle size={15} className="shrink-0 mt-0.5" />
                  <span className="font-medium">{error}</span>
                </div>
              )}

              <button
                type="submit"
                disabled={loading}
                className="w-full py-3 bg-emerald-600 hover:bg-emerald-700 disabled:bg-emerald-600/60 text-white rounded-2xl font-medium text-sm tracking-wider uppercase transition-all shadow-md hover:shadow-lg flex items-center justify-center gap-2 cursor-pointer"
              >
                {loading ? (
                  <>
                    <span className="w-4 h-4 border-2 border-white border-t-transparent rounded-full animate-spin" />
                    Locating Order...
                  </>
                ) : (
                  <>
                    <Search size={14} />
                    Track Shipment
                  </>
                )}
              </button>
            </form>
          </div>
        </div>

        {/* Results */}
        <div className="max-w-4xl mx-auto px-4 sm:px-6 lg:px-8 mt-12">
          <AnimatePresence mode="wait">
            {order && (
              <motion.div
                initial={{ opacity: 0, y: 15 }}
                animate={{ opacity: 1, y: 0 }}
                exit={{ opacity: 0, y: -15 }}
                transition={{ duration: 0.3 }}
                className="space-y-8"
              >
                {/* Status header */}
                <div className="bg-white rounded-3xl border border-slate-200 p-6 sm:p-8 shadow-sm flex flex-col md:flex-row justify-between items-start md:items-center gap-6">
                  <div>
                    <span className="text-[10px] font-medium text-slate-400 uppercase tracking-widest block">Shipment Status</span>
                    <h2 className="text-xl sm:text-2xl font-semibold text-slate-800 mt-1">{order.order_number}</h2>
                    <p className="text-sm text-slate-500 mt-1 flex items-center gap-1.5 font-medium">
                      <Calendar size={13} />
                      Ordered: {new Date(order.created_at).toLocaleDateString()}
                    </p>
                  </div>

                  <div className="flex flex-col sm:flex-row items-start sm:items-center gap-3">
                    <span className={`px-3 py-1.5 text-xs font-medium uppercase tracking-wider rounded-xl border ${
                      order.status === 'completed' || order.status === 'delivered'
                        ? 'bg-emerald-50 text-emerald-700 border-emerald-100'
                        : order.status === 'pending'
                          ? 'bg-blue-50 text-blue-700 border-blue-100'
                          : order.status === 'processing'
                            ? 'bg-amber-50 text-amber-700 border-amber-100'
                            : order.status === 'shipped'
                              ? 'bg-indigo-50 text-indigo-700 border-indigo-100'
                              : 'bg-rose-50 text-rose-700 border-rose-100'
                    }`}>
                      {getStatusLabel(order.status)}
                    </span>

                    {order.tracking_code && (
                      <div className="flex items-center gap-1.5 bg-slate-100 rounded-xl px-3 py-1.5 border border-slate-200">
                        <span className="text-[10px] font-medium text-slate-500 uppercase">Tracking:</span>
                        <span className="text-xs font-mono text-slate-700">{order.tracking_code}</span>
                        <button
                          type="button"
                          onClick={() => copyToClipboard(order.tracking_code!)}
                          className="p-1 hover:bg-white rounded transition-colors text-slate-400 hover:text-slate-700"
                          title="Copy tracking code"
                        >
                          {copied ? <Check size={12} className="text-emerald-500" /> : <Copy size={12} />}
                        </button>
                      </div>
                    )}
                  </div>
                </div>

                {/* Progress timeline */}
                {order.status !== 'cancelled' && (
                  <div className="bg-white rounded-3xl border border-slate-200 p-6 sm:p-8 shadow-sm">
                    <h3 className="text-xs font-medium text-slate-400 uppercase tracking-widest mb-8">Consignment Progress</h3>
                    <div className="relative flex flex-col md:flex-row justify-between items-stretch md:items-center gap-8 md:gap-4">
                      <div className="absolute left-4 right-4 top-4 h-0.5 bg-slate-200 hidden md:block z-0" />
                      {currentStep > 0 && (
                        <div
                          className="absolute left-4 top-4 h-0.5 bg-emerald-500 transition-all duration-500 hidden md:block z-0"
                          style={{ width: `${(currentStep / (statusSteps.length - 1)) * 95}%` }}
                        />
                      )}
                      {statusSteps.map((step, idx) => {
                        const isDone = idx <= currentStep;
                        const isActive = idx === currentStep;
                        return (
                          <div key={step} className="flex md:flex-col items-center gap-4 md:gap-2 relative z-10 flex-1 md:text-center">
                            <div className={`w-9 h-9 rounded-full flex items-center justify-center border-2 transition-all duration-300 ${
                              isActive
                                ? 'border-emerald-600 bg-emerald-600 text-white scale-110'
                                : isDone
                                  ? 'border-emerald-500 bg-emerald-50 text-emerald-600 shadow-md ring-4 ring-emerald-500/10'
                                  : 'border-slate-300 bg-slate-100 text-slate-400'
                            }`}>
                              {idx === 0 && <Package size={15} />}
                              {idx === 1 && <ClipboardList size={15} />}
                              {idx === 2 && <Truck size={15} />}
                              {idx === 3 && <ShieldCheck size={15} />}
                            </div>
                            <div className="text-left md:text-center">
                              <p className={`text-sm font-medium capitalize ${
                                isActive ? 'text-emerald-600' : isDone ? 'text-slate-700' : 'text-slate-400'
                              }`}>
                                {step === 'pending' ? 'Order Placed'
                                  : step === 'delivered' ? 'Delivered'
                                  : step.charAt(0).toUpperCase() + step.slice(1)}
                              </p>
                              <p className="text-xs text-slate-400 mt-0.5 font-medium">
                                {idx === 0 && 'Awaiting confirmation'}
                                {idx === 1 && 'Packaged & processed'}
                                {idx === 2 && (order.tracking_code ? 'In transit via courier' : 'Package dispatched')}
                                {idx === 3 && 'Received successfully'}
                              </p>
                            </div>
                          </div>
                        );
                      })}
                    </div>
                  </div>
                )}

                {/* Cancelled banner */}
                {order.status === 'cancelled' && (
                  <div className="p-6 bg-rose-50 border border-rose-100 rounded-3xl flex items-start gap-4 text-left shadow-sm">
                    <div className="w-10 h-10 rounded-2xl bg-rose-100 text-rose-600 flex items-center justify-center shrink-0">
                      <AlertCircle size={20} />
                    </div>
                    <div>
                      <h4 className="text-sm font-semibold text-rose-800">Order Cancelled</h4>
                      <p className="text-sm text-rose-600 mt-1 font-medium">
                        This consignment has been cancelled. If you believe this is an error, please contact our support team.
                      </p>
                    </div>
                  </div>
                )}

                {/* Info grid */}
                <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                  {/* Delivery */}
                  <div className="bg-white rounded-3xl border border-slate-200 p-6 shadow-sm space-y-4 text-left">
                    <div className="flex items-center gap-2 border-b border-slate-100 pb-3">
                      <MapPin size={15} className="text-emerald-500" />
                      <h3 className="text-xs font-medium text-slate-600 uppercase tracking-wider">Delivery Details</h3>
                    </div>
                    <div className="space-y-3.5">
                      <div>
                        <span className="text-[10px] font-medium text-slate-400 uppercase tracking-wider block mb-0.5">Consignee Name</span>
                        <p className="text-sm font-semibold text-slate-700">{order.customer_name}</p>
                      </div>
                      <div>
                        <span className="text-[10px] font-medium text-slate-400 uppercase tracking-wider block mb-0.5">Phone</span>
                        <p className="text-sm font-medium text-slate-700 font-mono">{order.customer_phone}</p>
                      </div>
                      <div>
                        <span className="text-[10px] font-medium text-slate-400 uppercase tracking-wider block mb-0.5">Shipping Address</span>
                        <p className="text-sm font-medium text-slate-700 leading-relaxed">{order.delivery_address}</p>
                      </div>
                    </div>
                  </div>

                  {/* Billing */}
                  <div className="bg-white rounded-3xl border border-slate-200 p-6 shadow-sm space-y-4 text-left">
                    <div className="flex items-center gap-2 border-b border-slate-100 pb-3">
                      <CreditCard size={15} className="text-emerald-500" />
                      <h3 className="text-xs font-medium text-slate-600 uppercase tracking-wider">Billing & Payment</h3>
                    </div>
                    <div className="space-y-3.5">
                      <div className="flex justify-between">
                        <div>
                          <span className="text-[10px] font-medium text-slate-400 uppercase tracking-wider block mb-0.5">Payment Method</span>
                          <p className="text-sm font-medium text-slate-700 capitalize">{order.payment_method}</p>
                        </div>
                        <div className="text-right">
                          <span className="text-[10px] font-medium text-slate-400 uppercase tracking-wider block mb-0.5">Status</span>
                          <p className={`text-sm font-medium capitalize ${
                            order.payment_status === 'paid' ? 'text-emerald-600' : 'text-amber-600'
                          }`}>{order.payment_status}</p>
                        </div>
                      </div>
                      <div>
                        <span className="text-[10px] font-medium text-slate-400 uppercase tracking-wider block mb-0.5">Shipping Method</span>
                        <p className="text-sm font-medium text-slate-700">{order.shipping_method}</p>
                      </div>
                      <div className="pt-2.5 border-t border-slate-100 space-y-1.5">
                        <div className="flex justify-between text-sm text-slate-500 font-medium">
                          <span>Subtotal</span>
                          <span className="font-mono">{formatPrice(order.subtotal)}</span>
                        </div>
                        {order.shipping_cost > 0 && (
                          <div className="flex justify-between text-sm text-slate-500 font-medium">
                            <span>Delivery Fee</span>
                            <span className="font-mono">{formatPrice(order.shipping_cost)}</span>
                          </div>
                        )}
                        {order.discount > 0 && (
                          <div className="flex justify-between text-sm text-rose-500 font-medium">
                            <span>Discount</span>
                            <span className="font-mono">-{formatPrice(order.discount)}</span>
                          </div>
                        )}
                        <div className="flex justify-between items-center border-t border-slate-100 pt-2 text-slate-800">
                          <span className="text-sm font-semibold">Total Amount</span>
                          <span className="font-mono text-base font-semibold">{formatPrice(order.grand_total)}</span>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>

                {/* Items */}
                <div className="bg-white rounded-3xl border border-slate-200 overflow-hidden shadow-sm text-left">
                  <div className="p-6 border-b border-slate-100 flex items-center gap-2">
                    <ShoppingBag size={15} className="text-emerald-500" />
                    <h3 className="text-xs font-medium text-slate-600 uppercase tracking-wider">Consignment Items</h3>
                  </div>
                  <div className="divide-y divide-slate-100">
                    {order.items.map((item, idx) => (
                      <div key={idx} className="p-5 flex items-center gap-4 justify-between hover:bg-slate-50/40 transition-colors">
                        <div className="flex items-center gap-3 min-w-0">
                          {item.image ? (
                            <img src={item.image} alt={item.product_name} className="w-12 h-12 rounded-xl object-cover border border-slate-200 shrink-0" />
                          ) : (
                            <div className="w-12 h-12 rounded-xl bg-slate-100 flex items-center justify-center shrink-0 border border-slate-200">
                              <Package size={18} className="text-slate-400" />
                            </div>
                          )}
                          <div className="min-w-0">
                            <h4 className="text-sm font-medium text-slate-700 truncate">{item.product_name}</h4>
                            <p className="text-xs font-mono text-slate-400 mt-0.5">{item.product_sku}</p>
                          </div>
                        </div>
                        <div className="flex items-center gap-6 shrink-0">
                          <div className="text-center">
                            <span className="text-[10px] text-slate-400 font-medium block uppercase">Qty</span>
                            <span className="text-sm font-medium text-slate-700 block mt-0.5">{item.quantity}</span>
                          </div>
                          <div className="text-right">
                            <span className="text-[10px] text-slate-400 font-medium block uppercase">Price</span>
                            <span className="text-sm font-mono font-semibold text-slate-700 block mt-0.5">{formatPrice(item.price * item.quantity)}</span>
                          </div>
                        </div>
                      </div>
                    ))}
                  </div>
                </div>

                {/* History */}
                {order.history && order.history.length > 0 && (
                  <div className="bg-white rounded-3xl border border-slate-200 p-6 sm:p-8 shadow-sm text-left">
                    <h3 className="text-xs font-medium text-slate-400 uppercase tracking-widest mb-6">Dispatch History</h3>
                    <div className="relative border-l-2 border-slate-100 pl-6 space-y-6 ml-3">
                      {order.history.map((log, idx) => (
                        <div key={idx} className="relative">
                          <div className="absolute -left-[31px] top-1.5 w-4 h-4 rounded-full border-2 border-emerald-500 bg-white" />
                          <div>
                            <span className="text-xs font-mono text-slate-400">
                              {new Date(log.created_at).toLocaleString()}
                            </span>
                            <h4 className="text-sm font-medium text-slate-700 capitalize mt-0.5">
                              {log.action.replace(/_/g, ' ')}
                            </h4>
                            {log.notes && (
                              <p className="text-sm text-slate-500 mt-1 bg-slate-50 rounded-xl p-3 border border-slate-100 font-medium leading-relaxed">
                                {log.notes}
                              </p>
                            )}
                          </div>
                        </div>
                      ))}
                    </div>
                  </div>
                )}

              </motion.div>
            )}
          </AnimatePresence>
        </div>
      </main>

      <Footer />
    </div>
  );
}

export default function TrackOrderPage() {
  return (
    <Suspense fallback={
      <div className="min-h-screen flex items-center justify-center bg-slate-50">
        <div className="w-8 h-8 border-2 border-emerald-500 border-t-transparent rounded-full animate-spin" />
      </div>
    }>
      <TrackOrderContent />
    </Suspense>
  );
}
