'use client';

import React, { useState } from 'react';
import Header from '@/components/layout/Header';
import Footer from '@/components/layout/Footer';
import { motion } from 'framer-motion';
import { Search, Package, Truck, CheckCircle2, ArrowRight, Loader2, AlertCircle } from 'lucide-react';
import { useRouter } from 'next/navigation';
import { api } from '@/lib/api';

const OrderTrackingLanding = () => {
  const [orderId, setOrderId] = useState('');
  const [isTracking, setIsTracking] = useState(false);
  const [errorMessage, setErrorMessage] = useState<string | null>(null);
  const router = useRouter();

  const handleTrack = async (e: React.FormEvent) => {
    e.preventDefault();
    const trimmed = orderId.trim();
    if (!trimmed || isTracking) return;

    setIsTracking(true);
    setErrorMessage(null);

    try {
      const hasLetters = /[A-Za-z]/.test(trimmed);
      let res: any;
      let resolvedId: number | string | null = null;

      if (hasLetters || trimmed.toUpperCase().startsWith('ORD-')) {
        res = await api.getOrderByNumber(trimmed);
      } else {
        res = await api.getOrderById(trimmed);
      }

      if (res && res.status === 'success' && res.data) {
        resolvedId = res.data.id ?? trimmed;
      }

      if (resolvedId != null) {
        router.push(`/orders/${resolvedId}`);
      } else {
        setErrorMessage(`No order found with this ID or number: ${trimmed}. Please check and try again.`);
      }
    } catch (err: any) {
      const msg =
        err?.message && err.message.includes('404')
          ? `No order found with this ID or number: ${trimmed}. Please check and try again.`
          : 'Unable to verify your order right now. Please try again in a moment.';
      setErrorMessage(msg);
    } finally {
      setIsTracking(false);
    }
  };

  return (
    <div className="min-h-screen bg-zinc-50">
      <Header />
      
      <main className="max-w-7xl mx-auto px-4 py-24 md:py-32">
        <div className="grid grid-cols-1 lg:grid-cols-2 gap-16 items-center">
          
          {/* Left Side - Text */}
          <motion.div
            initial={{ opacity: 0, x: -20 }}
            animate={{ opacity: 1, x: 0 }}
          >
            <div className="inline-flex items-center gap-2 px-4 py-2 bg-emerald-50 rounded-full text-emerald-600 text-[10px] font-black uppercase tracking-widest mb-8">
              <Truck className="w-3 h-3" />
              Live Tracking
            </div>
            <h1 className="text-5xl md:text-7xl font-black text-zinc-900 mb-8 tracking-tight leading-[0.9]">
              Where is my <br /><span className="text-emerald-600">Order?</span>
            </h1>
            <p className="text-lg text-zinc-500 font-medium mb-12 max-w-md leading-relaxed">
              Enter your order number to get real-time updates on your package's journey from our warehouse to your doorstep.
            </p>

            <form onSubmit={handleTrack} className="relative max-w-md group">
              <div className="absolute inset-y-0 left-6 flex items-center text-zinc-400 group-focus-within:text-emerald-600 transition-colors">
                <Search className="w-5 h-5" />
              </div>
              <input 
                type="text" 
                placeholder="Order ID or Number (e.g. 55 or ORD-XXXX)"
                value={orderId}
                onChange={(e) => setOrderId(e.target.value)}
                className="w-full pl-16 pr-32 py-6 bg-white border-none rounded-[2rem] shadow-xl shadow-zinc-200/50 text-sm font-bold focus:ring-4 focus:ring-emerald-500/10 transition-all placeholder:text-zinc-300"
              />
              <button 
                type="submit"
                disabled={!orderId.trim() || isTracking}
                aria-busy={isTracking}
                className={`absolute right-2 top-2 bottom-2 px-8 rounded-[1.5rem] font-black text-xs uppercase tracking-widest transition-all active:scale-95 flex items-center gap-2 ${
                  isTracking
                    ? "bg-emerald-700 text-white opacity-90 cursor-not-allowed"
                    : "bg-emerald-600 text-white hover:bg-emerald-700"
                }`}
              >
                {isTracking ? (
                  <>
                    <Loader2 className="w-4 h-4 animate-spin" />
                    Tracking...
                  </>
                ) : (
                  <>
                    Track
                    <ArrowRight className="w-4 h-4" />
                  </>
                )}
              </button>
            </form>

            {errorMessage && (
              <div className="mt-6 inline-flex items-center gap-3 px-4 py-3 rounded-2xl bg-rose-50 border border-rose-100 text-rose-700 text-sm font-medium shadow-sm">
                <AlertCircle className="w-4 h-4" />
                <span>{errorMessage}</span>
              </div>
            )}

            <div className="mt-12 flex items-center gap-8 border-t border-zinc-200 pt-12">
              <div className="flex flex-col">
                <span className="text-2xl font-black text-zinc-900">24/7</span>
                <span className="text-[10px] font-bold text-zinc-400 uppercase tracking-widest">Support</span>
              </div>
              <div className="w-px h-10 bg-zinc-200" />
              <div className="flex flex-col">
                <span className="text-2xl font-black text-zinc-900">100%</span>
                <span className="text-[10px] font-bold text-zinc-400 uppercase tracking-widest">Reliable</span>
              </div>
              <div className="w-px h-10 bg-zinc-200" />
              <div className="flex flex-col">
                <span className="text-2xl font-black text-zinc-900">Live</span>
                <span className="text-[10px] font-bold text-zinc-400 uppercase tracking-widest">Updates</span>
              </div>
            </div>
          </motion.div>

          {/* Right Side - Visual */}
          <motion.div
            initial={{ opacity: 0, scale: 0.9 }}
            animate={{ opacity: 1, scale: 1 }}
            transition={{ delay: 0.2 }}
            className="relative"
          >
            <div className="aspect-square bg-emerald-600 rounded-[4rem] overflow-hidden relative shadow-2xl shadow-emerald-200">
              <div className="absolute inset-0 bg-gradient-to-br from-white/20 to-transparent" />
              
              {/* Floating Cards */}
              <motion.div
                animate={{ y: [0, -20, 0] }}
                transition={{ duration: 4, repeat: Infinity, ease: "easeInOut" }}
                className="absolute top-12 left-12 right-12 bg-white/10 backdrop-blur-md border border-white/20 p-8 rounded-3xl"
              >
                <div className="flex items-center gap-4 mb-6">
                  <div className="w-12 h-12 bg-white rounded-2xl flex items-center justify-center text-emerald-600 shadow-lg">
                    <Package className="w-6 h-6" />
                  </div>
                  <div>
                    <p className="text-xs text-emerald-100 font-bold uppercase tracking-widest">Order #55</p>
                    <p className="text-lg font-black text-white">In Transit</p>
                  </div>
                </div>
                <div className="h-2 bg-white/20 rounded-full overflow-hidden">
                  <motion.div 
                    initial={{ width: 0 }}
                    animate={{ width: "70%" }}
                    transition={{ duration: 2, delay: 0.5 }}
                    className="h-full bg-white shadow-[0_0_20px_rgba(255,255,255,0.5)]" 
                  />
                </div>
              </motion.div>

              <motion.div
                animate={{ y: [0, 20, 0] }}
                transition={{ duration: 5, repeat: Infinity, ease: "easeInOut", delay: 0.5 }}
                className="absolute bottom-12 right-12 bg-white p-6 rounded-3xl shadow-2xl flex items-center gap-4"
              >
                <div className="w-10 h-10 bg-emerald-50 rounded-xl flex items-center justify-center text-emerald-600">
                  <CheckCircle2 className="w-6 h-6" />
                </div>
                <div>
                  <p className="text-[10px] font-black text-zinc-400 uppercase tracking-widest">Estimated Delivery</p>
                  <p className="text-sm font-black text-zinc-900">Tomorrow, 12:30 PM</p>
                </div>
              </motion.div>
            </div>
            
            {/* Background Decoration */}
            <div className="absolute -z-10 -top-12 -right-12 w-64 h-64 bg-emerald-100 rounded-full blur-3xl opacity-50" />
            <div className="absolute -z-10 -bottom-12 -left-12 w-64 h-64 bg-emerald-50 rounded-full blur-3xl opacity-50" />
          </motion.div>
        </div>
      </main>

      <Footer />
    </div>
  );
};

export default OrderTrackingLanding;
