import { useState } from "react";
import { Link, useNavigate } from "react-router-dom";
import {
  ArrowLeft,
  CheckCircle,
  ShoppingBag,
  User,
  Phone,
  MapPin,
  MessageSquare,
  Building2,
  Tag,
  Truck,
  Shield,
  Package,
} from "lucide-react";
import { toast } from "sonner";
import { useCartStore } from "@/stores/cartStore";

const CITIES = [
  "صنعاء",
  "عدن",
  "تعز",
  "الحديدة",
  "إب",
  "حضرموت",
  "ذمار",
  "المكلا",
  "مأرب",
  "صعدة",
  "لحج",
  "البيضاء",
];

const PROMO_CODES: Record<string, number> = {
  BNPASH10: 0.1,
  SAVE15: 0.15,
  WELCOME20: 0.2,
};

interface FormData {
  name: string;
  phone: string;
  city: string;
  district: string;
  address: string;
  notes: string;
}

interface FormErrors {
  name?: string;
  phone?: string;
  city?: string;
  address?: string;
}

function InputField({
  label,
  required,
  error,
  children,
  icon,
}: {
  label: string;
  required?: boolean;
  error?: string;
  children: React.ReactNode;
  icon?: React.ReactNode;
}) {
  return (
    <div>
      <label className="flex items-center gap-1.5 text-sm font-bold text-gray-700 mb-2">
        {icon && <span className="text-orange-500">{icon}</span>}
        {label}
        {required && <span className="text-red-500">*</span>}
      </label>
      {children}
      {error && (
        <p className="text-red-500 text-xs mt-1.5 flex items-center gap-1">
          <span className="w-3.5 h-3.5 bg-red-500 text-white rounded-full inline-flex items-center justify-center text-xs font-bold shrink-0">!</span>
          {error}
        </p>
      )}
    </div>
  );
}

export default function CheckoutPage() {
  const { items, totalPrice, clearCart } = useCartStore();
  const navigate = useNavigate();

  const [form, setForm] = useState<FormData>({
    name: "",
    phone: "",
    city: "",
    district: "",
    address: "",
    notes: "",
  });
  const [errors, setErrors] = useState<FormErrors>({});
  const [promoCode, setPromoCode] = useState("");
  const [promoInput, setPromoInput] = useState("");
  const [discountRate, setDiscountRate] = useState(0);
  const [orderPlaced, setOrderPlaced] = useState(false);
  const [orderId] = useState(() => `BNP-${Date.now().toString().slice(-6)}`);
  const [step, setStep] = useState<1 | 2>(1); // 1: form, 2: confirm

  const shipping = totalPrice > 5000 ? 0 : 500;
  const discountAmount = Math.floor(totalPrice * discountRate);
  const finalTotal = totalPrice - discountAmount + shipping;

  if (items.length === 0 && !orderPlaced) {
    return (
      <div className="max-w-lg mx-auto px-4 py-20 text-center">
        <div className="bg-white rounded-3xl shadow-lg p-10">
          <ShoppingBag className="text-orange-300 mx-auto mb-4" size={72} />
          <h2 className="text-2xl font-black text-gray-800 mb-2">السلة فارغة</h2>
          <p className="text-gray-500 mb-6">أضف منتجات إلى سلتك أولاً ثم تابع الدفع</p>
          <Link to="/products" className="btn-primary inline-block">
            تسوق الآن
          </Link>
        </div>
      </div>
    );
  }

  if (orderPlaced) {
    return (
      <div className="max-w-lg mx-auto px-4 py-16 text-center">
        <div className="bg-white rounded-3xl shadow-xl p-10">
          {/* Success animation circle */}
          <div className="relative mx-auto w-28 h-28 mb-6">
            <div className="absolute inset-0 bg-green-100 rounded-full animate-ping opacity-30" />
            <div className="relative w-28 h-28 bg-green-100 rounded-full flex items-center justify-center">
              <CheckCircle className="text-green-500" size={60} />
            </div>
          </div>

          <h2 className="text-3xl font-black text-gray-800 mb-2">تم تقديم طلبك!</h2>
          <p className="text-gray-500 mb-1">رقم طلبك</p>
          <div className="inline-block bg-orange-50 border border-orange-200 text-orange-600 font-black text-lg px-6 py-2 rounded-xl mb-6">
            {orderId}
          </div>

          <div className="bg-gray-50 rounded-2xl p-5 text-right mb-6 space-y-3">
            <div className="flex justify-between text-sm">
              <span className="text-gray-500">الاسم</span>
              <span className="font-bold text-gray-800">{form.name}</span>
            </div>
            <div className="flex justify-between text-sm">
              <span className="text-gray-500">الهاتف</span>
              <span className="font-bold text-gray-800" dir="ltr">{form.phone}</span>
            </div>
            <div className="flex justify-between text-sm">
              <span className="text-gray-500">المدينة</span>
              <span className="font-bold text-gray-800">{form.city}</span>
            </div>
            <div className="flex justify-between text-sm">
              <span className="text-gray-500">المبلغ الإجمالي</span>
              <span className="font-black text-orange-500 text-base">{finalTotal.toLocaleString()} ر.ي</span>
            </div>
          </div>

          <p className="text-gray-500 text-sm mb-6">
            سيتواصل معك فريقنا خلال <strong>24 ساعة</strong> لتأكيد الطلب وترتيب التوصيل
          </p>

          <div className="flex gap-3">
            <Link to="/" className="btn-primary flex-1 text-center">
              العودة للرئيسية
            </Link>
            <Link to="/products" className="btn-secondary flex-1 text-center">
              مواصلة التسوق
            </Link>
          </div>
        </div>
      </div>
    );
  }

  const validate = (): boolean => {
    const newErrors: FormErrors = {};
    if (!form.name.trim()) newErrors.name = "الاسم مطلوب";
    else if (form.name.trim().length < 3) newErrors.name = "الاسم يجب أن يكون 3 أحرف على الأقل";
    if (!form.phone.trim()) newErrors.phone = "رقم الهاتف مطلوب";
    else if (!/^[0-9+\s()-]{7,15}$/.test(form.phone.trim())) newErrors.phone = "رقم هاتف غير صحيح";
    if (!form.city) newErrors.city = "يرجى اختيار المدينة";
    if (!form.address.trim()) newErrors.address = "العنوان مطلوب";
    setErrors(newErrors);
    return Object.keys(newErrors).length === 0;
  };

  const handlePromo = () => {
    const code = promoInput.trim().toUpperCase();
    if (PROMO_CODES[code]) {
      if (promoCode === code) {
        toast.error("تم تطبيق هذا الكوبون بالفعل");
        return;
      }
      setPromoCode(code);
      setDiscountRate(PROMO_CODES[code]);
      toast.success(`✅ تم تطبيق الكوبون! خصم ${PROMO_CODES[code] * 100}%`);
    } else {
      toast.error("كوبون غير صحيح، تحقق من الكود وحاول مجدداً");
    }
  };

  const handleContinue = (e: React.FormEvent) => {
    e.preventDefault();
    if (!validate()) return;
    setStep(2);
    window.scrollTo({ top: 0, behavior: "smooth" });
  };

  const handleConfirmOrder = () => {
    setOrderPlaced(true);
    clearCart();
    toast.success("🎉 تم تقديم طلبك بنجاح!");
    window.scrollTo({ top: 0, behavior: "smooth" });
  };

  return (
    <div className="max-w-6xl mx-auto px-4 py-6">
      {/* Header */}
      <div className="flex items-center gap-3 mb-8">
        <button
          onClick={() => (step === 2 ? setStep(1) : navigate("/cart"))}
          className="text-orange-500 hover:text-orange-600 transition-colors p-1"
        >
          <ArrowLeft size={22} />
        </button>
        <div>
          <h1 className="text-2xl font-black text-gray-800">إتمام الطلب</h1>
          <p className="text-gray-400 text-sm mt-0.5">{items.length} منتج في سلتك</p>
        </div>
      </div>

      {/* Steps indicator */}
      <div className="flex items-center gap-0 mb-8 max-w-xs">
        {[
          { num: 1, label: "بيانات التوصيل" },
          { num: 2, label: "تأكيد الطلب" },
        ].map((s, i) => (
          <div key={s.num} className="flex items-center flex-1">
            <div className="flex flex-col items-center">
              <div
                className={`w-9 h-9 rounded-full flex items-center justify-center font-black text-sm transition-colors ${
                  step >= s.num
                    ? "bg-orange-500 text-white shadow-md shadow-orange-200"
                    : "bg-gray-100 text-gray-400"
                }`}
              >
                {step > s.num ? <CheckCircle size={18} /> : s.num}
              </div>
              <span className={`text-xs font-semibold mt-1.5 whitespace-nowrap ${step >= s.num ? "text-orange-500" : "text-gray-400"}`}>
                {s.label}
              </span>
            </div>
            {i < 1 && (
              <div className={`flex-1 h-0.5 mx-2 mb-5 transition-colors ${step > 1 ? "bg-orange-400" : "bg-gray-200"}`} />
            )}
          </div>
        ))}
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-5 gap-6 items-start">
        {/* ─── Left: Form or Confirm ─── */}
        <div className="lg:col-span-3 space-y-5">
          {step === 1 && (
            <form onSubmit={handleContinue} className="space-y-5">
              {/* Delivery info card */}
              <div className="bg-white rounded-2xl p-6 shadow-sm border border-gray-100">
                <h2 className="font-black text-gray-800 text-lg mb-5 flex items-center gap-2">
                  <div className="w-8 h-8 bg-orange-100 rounded-lg flex items-center justify-center">
                    <Truck size={16} className="text-orange-500" />
                  </div>
                  بيانات التوصيل
                </h2>

                <div className="space-y-4">
                  <InputField
                    label="الاسم الكامل"
                    required
                    error={errors.name}
                    icon={<User size={15} />}
                  >
                    <input
                      type="text"
                      value={form.name}
                      onChange={(e) => {
                        setForm({ ...form, name: e.target.value });
                        if (errors.name) setErrors({ ...errors, name: undefined });
                      }}
                      placeholder="مثال: محمد أحمد العبدلي"
                      className={`w-full border-2 rounded-xl px-4 py-3 text-sm outline-none transition-colors text-right ${
                        errors.name
                          ? "border-red-300 bg-red-50 focus:border-red-400"
                          : "border-gray-200 bg-gray-50 focus:border-orange-400 focus:bg-white"
                      }`}
                    />
                  </InputField>

                  <InputField
                    label="رقم الهاتف"
                    required
                    error={errors.phone}
                    icon={<Phone size={15} />}
                  >
                    <input
                      type="tel"
                      value={form.phone}
                      onChange={(e) => {
                        setForm({ ...form, phone: e.target.value });
                        if (errors.phone) setErrors({ ...errors, phone: undefined });
                      }}
                      placeholder="07XXXXXXXX"
                      dir="ltr"
                      className={`w-full border-2 rounded-xl px-4 py-3 text-sm outline-none transition-colors ${
                        errors.phone
                          ? "border-red-300 bg-red-50 focus:border-red-400"
                          : "border-gray-200 bg-gray-50 focus:border-orange-400 focus:bg-white"
                      }`}
                    />
                  </InputField>

                  <div className="grid grid-cols-2 gap-4">
                    <InputField
                      label="المدينة"
                      required
                      error={errors.city}
                      icon={<Building2 size={15} />}
                    >
                      <select
                        value={form.city}
                        onChange={(e) => {
                          setForm({ ...form, city: e.target.value });
                          if (errors.city) setErrors({ ...errors, city: undefined });
                        }}
                        className={`w-full border-2 rounded-xl px-4 py-3 text-sm outline-none transition-colors bg-gray-50 focus:bg-white ${
                          errors.city
                            ? "border-red-300 bg-red-50 focus:border-red-400"
                            : "border-gray-200 focus:border-orange-400"
                        }`}
                      >
                        <option value="">اختر المدينة</option>
                        {CITIES.map((c) => (
                          <option key={c} value={c}>{c}</option>
                        ))}
                      </select>
                    </InputField>

                    <InputField label="الحي / المنطقة" icon={<MapPin size={15} />}>
                      <input
                        type="text"
                        value={form.district}
                        onChange={(e) => setForm({ ...form, district: e.target.value })}
                        placeholder="اختياري"
                        className="w-full border-2 border-gray-200 bg-gray-50 focus:bg-white focus:border-orange-400 rounded-xl px-4 py-3 text-sm outline-none transition-colors text-right"
                      />
                    </InputField>
                  </div>

                  <InputField
                    label="العنوان التفصيلي"
                    required
                    error={errors.address}
                    icon={<MapPin size={15} />}
                  >
                    <textarea
                      value={form.address}
                      onChange={(e) => {
                        setForm({ ...form, address: e.target.value });
                        if (errors.address) setErrors({ ...errors, address: undefined });
                      }}
                      placeholder="الشارع، رقم المبنى، علامة مميزة للمكان..."
                      rows={3}
                      className={`w-full border-2 rounded-xl px-4 py-3 text-sm outline-none transition-colors resize-none text-right ${
                        errors.address
                          ? "border-red-300 bg-red-50 focus:border-red-400"
                          : "border-gray-200 bg-gray-50 focus:border-orange-400 focus:bg-white"
                      }`}
                    />
                  </InputField>

                  <InputField label="ملاحظات للتوصيل" icon={<MessageSquare size={15} />}>
                    <textarea
                      value={form.notes}
                      onChange={(e) => setForm({ ...form, notes: e.target.value })}
                      placeholder="أي تعليمات خاصة للتوصيل (اختياري)..."
                      rows={2}
                      className="w-full border-2 border-gray-200 bg-gray-50 focus:bg-white focus:border-orange-400 rounded-xl px-4 py-3 text-sm outline-none transition-colors resize-none text-right"
                    />
                  </InputField>
                </div>
              </div>

              {/* Promo code */}
              <div className="bg-white rounded-2xl p-5 shadow-sm border border-gray-100">
                <h3 className="font-black text-gray-800 mb-3 flex items-center gap-2">
                  <Tag size={18} className="text-orange-500" />
                  كوبون الخصم
                </h3>
                <div className="flex gap-2">
                  <input
                    type="text"
                    value={promoInput}
                    onChange={(e) => setPromoInput(e.target.value)}
                    onKeyDown={(e) => e.key === "Enter" && (e.preventDefault(), handlePromo())}
                    placeholder="أدخل كود الكوبون"
                    className="flex-1 border-2 border-gray-200 focus:border-orange-400 rounded-xl px-4 py-2.5 text-sm outline-none bg-gray-50 focus:bg-white transition-colors text-right"
                  />
                  <button
                    type="button"
                    onClick={handlePromo}
                    className="bg-orange-500 hover:bg-orange-600 active:scale-95 text-white text-sm font-bold px-5 rounded-xl transition-all duration-200"
                  >
                    تطبيق
                  </button>
                </div>
                {promoCode ? (
                  <div className="mt-2 flex items-center gap-2 text-green-600 text-xs font-semibold bg-green-50 px-3 py-2 rounded-lg">
                    <CheckCircle size={14} />
                    تم تطبيق الكوبون «{promoCode}» — خصم {discountRate * 100}%
                  </div>
                ) : (
                  <p className="text-xs text-gray-400 mt-2">جرب: BNPASH10 للحصول على خصم 10%</p>
                )}
              </div>

              <button
                type="submit"
                className="w-full bg-orange-500 hover:bg-orange-600 active:scale-95 text-white font-black py-4 rounded-2xl transition-all duration-200 shadow-lg hover:shadow-orange-200 flex items-center justify-center gap-2 text-base"
              >
                مراجعة الطلب
                <ArrowLeft size={18} className="rotate-180" />
              </button>
            </form>
          )}

          {step === 2 && (
            <div className="space-y-5">
              {/* Delivery summary */}
              <div className="bg-white rounded-2xl p-6 shadow-sm border border-gray-100">
                <h2 className="font-black text-gray-800 text-lg mb-5 flex items-center gap-2">
                  <div className="w-8 h-8 bg-orange-100 rounded-lg flex items-center justify-center">
                    <User size={16} className="text-orange-500" />
                  </div>
                  بيانات التوصيل
                </h2>
                <div className="space-y-3">
                  {[
                    { label: "الاسم", value: form.name, icon: <User size={14} /> },
                    { label: "الهاتف", value: form.phone, icon: <Phone size={14} />, ltr: true },
                    { label: "المدينة", value: `${form.city}${form.district ? ` - ${form.district}` : ""}`, icon: <Building2 size={14} /> },
                    { label: "العنوان", value: form.address, icon: <MapPin size={14} /> },
                    ...(form.notes ? [{ label: "ملاحظات", value: form.notes, icon: <MessageSquare size={14} /> }] : []),
                  ].map(({ label, value, icon, ltr }) => (
                    <div key={label} className="flex justify-between gap-4 py-2 border-b border-gray-50 last:border-0">
                      <div className="flex items-center gap-1.5 text-gray-500 text-sm shrink-0">
                        <span className="text-orange-400">{icon}</span>
                        {label}
                      </div>
                      <span className={`text-sm font-bold text-gray-800 text-left ${ltr ? "font-mono" : ""}`} dir={ltr ? "ltr" : "rtl"}>
                        {value}
                      </span>
                    </div>
                  ))}
                </div>
                <button
                  onClick={() => setStep(1)}
                  className="mt-4 text-sm text-orange-500 font-semibold hover:text-orange-600 transition-colors"
                >
                  ← تعديل البيانات
                </button>
              </div>

              {/* Payment method */}
              <div className="bg-white rounded-2xl p-5 shadow-sm border border-gray-100">
                <h3 className="font-black text-gray-800 mb-3">طريقة الدفع</h3>
                <div className="flex items-center gap-3 bg-orange-50 border-2 border-orange-300 rounded-xl p-4">
                  <div className="w-10 h-10 bg-orange-500 rounded-xl flex items-center justify-center shrink-0">
                    <span className="text-white text-lg">💵</span>
                  </div>
                  <div>
                    <p className="font-bold text-gray-800 text-sm">الدفع عند الاستلام</p>
                    <p className="text-xs text-gray-500">ادفع كاش عند وصول طلبك</p>
                  </div>
                  <CheckCircle size={20} className="text-orange-500 mr-auto" />
                </div>
              </div>

              {/* Guarantees */}
              <div className="grid grid-cols-3 gap-3">
                {[
                  { icon: Shield, label: "ضمان الجودة", color: "text-green-500 bg-green-50" },
                  { icon: Truck, label: "توصيل سريع", color: "text-blue-500 bg-blue-50" },
                  { icon: Package, label: "تغليف آمن", color: "text-purple-500 bg-purple-50" },
                ].map(({ icon: Icon, label, color }) => (
                  <div key={label} className="bg-white rounded-xl p-3 text-center border border-gray-100 shadow-sm">
                    <div className={`w-9 h-9 rounded-xl flex items-center justify-center mx-auto mb-2 ${color}`}>
                      <Icon size={18} />
                    </div>
                    <p className="text-xs font-bold text-gray-700">{label}</p>
                  </div>
                ))}
              </div>

              <button
                onClick={handleConfirmOrder}
                className="w-full bg-green-500 hover:bg-green-600 active:scale-95 text-white font-black py-4 rounded-2xl transition-all duration-200 shadow-lg hover:shadow-green-200 flex items-center justify-center gap-2 text-base"
              >
                <CheckCircle size={20} />
                تأكيد الطلب نهائياً — {finalTotal.toLocaleString()} ر.ي
              </button>
              <p className="text-center text-xs text-gray-400">
                بالضغط على "تأكيد الطلب" أنت توافق على شروط وأحكام صلاح مول
              </p>
            </div>
          )}
        </div>

        {/* ─── Right: Order Summary ─── */}
        <div className="lg:col-span-2 space-y-4 lg:sticky lg:top-24">
          <div className="bg-white rounded-2xl shadow-sm border border-gray-100 overflow-hidden">
            <div className="bg-orange-50 px-5 py-4 border-b border-orange-100">
              <h3 className="font-black text-gray-800 flex items-center gap-2">
                <ShoppingBag size={18} className="text-orange-500" />
                ملخص الطلب
                <span className="bg-orange-500 text-white text-xs font-bold px-2 py-0.5 rounded-full">
                  {items.length}
                </span>
              </h3>
            </div>

            {/* Items list */}
            <div className="divide-y divide-gray-50 max-h-80 overflow-y-auto">
              {items.map((item) => {
                const itemPrice = item.variant ? item.variant.price : item.product.price;
                const itemKey = item.variantKey || item.product.id;
                return (
                  <div key={itemKey} className="flex gap-3 p-4">
                    <div className="relative shrink-0">
                      <img
                        src={item.product.image}
                        alt={item.product.name}
                        className="w-16 h-16 object-cover rounded-xl bg-gray-50"
                      />
                      <span className="absolute -top-2 -left-2 w-5 h-5 bg-orange-500 text-white text-xs font-black rounded-full flex items-center justify-center">
                        {item.quantity}
                      </span>
                    </div>
                    <div className="flex-1 min-w-0">
                      <p className="text-sm font-bold text-gray-800 line-clamp-2 leading-tight mb-1.5">
                        {item.product.name}
                      </p>
                      {/* Variant info */}
                      {item.variant && (
                        <div className="flex items-center gap-1.5 flex-wrap mb-1.5">
                          {item.variant.colorHex && (
                            <span
                              className="w-3.5 h-3.5 rounded-full border border-gray-300 shrink-0"
                              style={{ backgroundColor: item.variant.colorHex }}
                            />
                          )}
                          {item.variant.color && (
                            <span className="text-xs text-gray-500 bg-gray-100 px-1.5 py-0.5 rounded-md">
                              {item.variant.color}
                            </span>
                          )}
                          {item.variant.size && (
                            <span className="text-xs text-gray-500 bg-gray-100 px-1.5 py-0.5 rounded-md font-semibold">
                              {item.variant.size}
                            </span>
                          )}
                        </div>
                      )}
                      <div className="flex justify-between items-center">
                        <span className="text-xs text-gray-400">
                          {itemPrice.toLocaleString()} × {item.quantity}
                        </span>
                        <span className="font-black text-orange-500 text-sm">
                          {(itemPrice * item.quantity).toLocaleString()} ر.ي
                        </span>
                      </div>
                    </div>
                  </div>
                );
              })}
            </div>

            {/* Price breakdown */}
            <div className="border-t border-gray-100 p-5 space-y-3">
              <div className="flex justify-between text-sm text-gray-600">
                <span>المجموع الفرعي</span>
                <span>{totalPrice.toLocaleString()} ر.ي</span>
              </div>
              {discountAmount > 0 && (
                <div className="flex justify-between text-sm font-semibold text-green-600">
                  <span>خصم الكوبون ({discountRate * 100}%)</span>
                  <span>- {discountAmount.toLocaleString()} ر.ي</span>
                </div>
              )}
              <div className="flex justify-between text-sm text-gray-600">
                <span>رسوم التوصيل</span>
                <span className={shipping === 0 ? "text-green-500 font-semibold" : ""}>
                  {shipping === 0 ? "مجاني 🎉" : `${shipping.toLocaleString()} ر.ي`}
                </span>
              </div>
              {shipping > 0 && totalPrice < 5000 && (
                <p className="text-xs text-blue-500 bg-blue-50 px-3 py-2 rounded-lg">
                  أضف {(5000 - totalPrice).toLocaleString()} ر.ي للحصول على توصيل مجاني
                </p>
              )}
              <div className="border-t pt-3 flex justify-between font-black text-lg">
                <span className="text-gray-800">الإجمالي</span>
                <span className="text-orange-500">{finalTotal.toLocaleString()} ر.ي</span>
              </div>
            </div>
          </div>

          {/* Trust */}
          <div className="bg-white rounded-2xl p-4 shadow-sm border border-gray-100">
            <div className="flex items-center gap-3 text-sm text-gray-600">
              <Shield size={18} className="text-green-500 shrink-0" />
              <span>معاملاتك آمنة ومحمية. الدفع عند الاستلام فقط.</span>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}
