import React, { useState } from 'react';
import { motion, AnimatePresence } from 'motion/react';
import { X, CreditCard, ShieldCheck, CheckCircle2, Copy, Check, ArrowLeft, Zap } from 'lucide-react';
import confetti from 'canvas-confetti';
import { useCart } from '../context/CartContext';
import { useAuth } from '../context/AuthContext';
import { useToast } from '../context/ToastContext';
import { formatPrice, toPersianDigits } from '../utils/formatters';
import { api } from '../services/api';
import type { Order } from '../types';

interface CheckoutModalProps {
  isOpen: boolean;
  onClose: () => void;
  onOrderSuccess: (order: Order) => void;
}

export const CheckoutModal: React.FC<CheckoutModalProps> = ({ isOpen, onClose, onOrderSuccess }) => {
  const { items, subtotal, discountAmount, couponCode, finalTotal, clearCart } = useCart();
  const { user } = useAuth();
  const { success, error } = useToast();

  const [name, setName] = useState(user?.name || '');
  const [mobile, setMobile] = useState(user?.mobile || '');
  const [email, setEmail] = useState(user?.email || '');
  const [notes, setNotes] = useState('');
  const [paymentMethod] = useState<'online_gateway'>('online_gateway');
  const [submitting, setSubmitting] = useState(false);
  const [completedOrder, setCompletedOrder] = useState<Order | null>(null);
  const [copiedKey, setCopiedKey] = useState<string | null>(null);
  const supportTelegram = import.meta.env.VITE_SUPPORT_TELEGRAM_ID || 'ZanaShopSupport';
  const supportTelegramUrl = `https://t.me/${supportTelegram.replace(/^@/, '')}`;

  if (!isOpen) return null;

  const handleSubmitOrder = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!name.trim() || !mobile.trim()) {
      error('لطفاً نام و شماره موبایل خود را وارد کنید');
      return;
    }

    setSubmitting(true);
    try {
      const orderPayload = {
        guestInfo: {
          name: name.trim(),
          mobile: mobile.trim(),
          email: email.trim() || (user?.email || ''),
          notes: notes.trim(),
        },
        items: items.map(item => ({
          productId: item.product.id,
          quantity: item.quantity,
          region: item.selectedRegion,
        })),
        couponCode: couponCode || undefined,
        paymentMethod,
      };

      const placedOrder = await api.createOrder(orderPayload);
      setCompletedOrder(placedOrder);
      clearCart();
      success(`سفارش شماره ${placedOrder.orderNumber} با موفقیت ثبت شد`, 'ثبت موفق');

      // Trigger Celebration Confetti
      try {
        confetti({
          particleCount: 80,
          spread: 70,
          origin: { y: 0.6 },
          colors: ['#a855f7', '#9333ea', '#6366f1', '#10b981', '#ffffff'],
        });
      } catch (e) {
        console.error(e);
      }
    } catch (err: any) {
      error(err.message || 'خطا در ثبت سفارش');
    } finally {
      setSubmitting(false);
    }
  };

  const copyToClipboard = (text: string) => {
    navigator.clipboard.writeText(text);
    setCopiedKey(text);
    setTimeout(() => setCopiedKey(null), 2000);
  };

  return (
    <div className="fixed inset-0 z-50 overflow-y-auto flex items-center justify-center p-4">
      {/* Backdrop */}
      <div onClick={onClose} className="fixed inset-0 bg-black/80 backdrop-blur-md" />

      <motion.div
        initial={{ opacity: 0, scale: 0.95 }}
        animate={{ opacity: 1, scale: 1 }}
        exit={{ opacity: 0, scale: 0.95 }}
        className="relative w-full max-w-2xl bg-[#110926] border border-purple-500/30 rounded-3xl p-6 sm:p-8 shadow-2xl z-10 text-right overflow-hidden"
      >
        
        {/* Close Button */}
        <button
          onClick={onClose}
          className="absolute left-4 top-4 p-2 text-zinc-400 hover:text-white rounded-xl bg-[#1a0f35] border border-purple-500/20"
        >
          <X className="w-5 h-5" />
        </button>

        {completedOrder ? (
          /* Order Complete / License Screen */
          <div className="space-y-6 text-center py-4">
            <div className="w-16 h-16 rounded-2xl bg-emerald-950/80 border border-emerald-500/40 text-emerald-400 mx-auto flex items-center justify-center shadow-lg shadow-emerald-900/30">
              <CheckCircle2 className="w-10 h-10" />
            </div>

            <div className="space-y-1">
              <h3 className="text-2xl font-black text-white">سفارش شما با موفقیت ثبت شد!</h3>
              <p className="text-xs sm:text-sm text-zinc-400">
                کد پیگیری سفارش شما: <strong className="text-purple-300 font-mono text-base px-2 py-0.5 bg-purple-950 rounded border border-purple-500/30">{completedOrder.orderNumber}</strong>
              </p>
            </div>

            {/* License Keys Delivery Box */}
            {completedOrder.licenseKeys && completedOrder.licenseKeys.length > 0 && (
              <div className="p-4 rounded-2xl bg-[#180f33] border border-purple-500/30 text-right space-y-3">
                <div className="flex items-center justify-between">
                  <span className="text-xs font-bold text-emerald-300 flex items-center gap-1.5">
                    <Zap className="w-4 h-4 text-emerald-400" />
                    لایسنس / مشخصات اختصاصی تحویل داده شده:
                  </span>
                  <span className="text-[10px] text-zinc-400">تحویل آنی خودکار</span>
                </div>

                <div className="space-y-2">
                  {completedOrder.licenseKeys.map((key, i) => (
                    <div
                      key={i}
                      className="p-3 bg-[#0a0516] rounded-xl border border-purple-500/20 flex items-center justify-between font-mono text-xs text-purple-200"
                    >
                      <span className="select-all break-all">{key}</span>
                      <button
                        onClick={() => copyToClipboard(key)}
                        className="mr-2 p-1.5 text-zinc-400 hover:text-white rounded-lg bg-purple-950 border border-purple-500/30 shrink-0 flex items-center gap-1 text-[11px]"
                      >
                        {copiedKey === key ? (
                          <>
                            <Check className="w-3.5 h-3.5 text-emerald-400" />
                            <span className="text-emerald-400">کپی شد</span>
                          </>
                        ) : (
                          <>
                            <Copy className="w-3.5 h-3.5" />
                            <span>کپی</span>
                          </>
                        )}
                      </button>
                    </div>
                  ))}
                </div>

                {completedOrder.deliveryInstructions && (
                  <p className="text-xs text-zinc-300 leading-relaxed bg-[#120a26] p-2.5 rounded-lg border border-purple-900/40">
                    💡 {completedOrder.deliveryInstructions}
                  </p>
                )}
              </div>
            )}

            <div className="p-4 rounded-2xl bg-purple-500/[0.06] border border-purple-500/20 text-right space-y-2">
              <div className="flex items-center gap-2 text-sm font-bold text-white">
                <Zap className="w-4 h-4 text-purple-400" />
                مرحله بعد: تحویل کانفیگ WireGuard
              </div>
              <p className="text-xs text-zinc-400 leading-7">
                سفارش شما در انتظار بررسی و تأیید پرداخت است. پس از تأیید، کانفیگ برای <strong className="text-zinc-200">یک کاربر</strong> آماده می‌شود و از طریق ایمیل ثبت‌شده یا پشتیبانی تلگرام برای شما ارسال خواهد شد.
              </p>
              <a href={supportTelegramUrl} target="_blank" rel="noreferrer" className="inline-flex items-center gap-2 text-xs font-bold text-purple-300 hover:text-purple-200">
                <ArrowLeft className="w-3.5 h-3.5" />
                پشتیبانی تلگرام: @{supportTelegram.replace(/^@/, '')}
              </a>
            </div>

            {/* Action Buttons */}
            <div className="flex flex-col sm:flex-row gap-3 pt-2">
              <button
                onClick={() => {
                  onClose();
                  onOrderSuccess(completedOrder);
                }}
                className="flex-1 py-3 rounded-xl bg-purple-600 hover:bg-purple-500 text-white font-bold text-xs sm:text-sm transition-colors"
              >
                مشاهده در تاریخچه سفارش‌ها
              </button>
              <button
                onClick={onClose}
                className="px-5 py-3 rounded-xl bg-[#170e30] hover:bg-[#201442] text-zinc-300 hover:text-white text-xs sm:text-sm font-semibold border border-purple-500/20"
              >
                بستن و ادامه خرید
              </button>
            </div>

          </div>
        ) : (
          /* Checkout Form */
          <form onSubmit={handleSubmitOrder} className="space-y-6">
            
            <div className="flex items-center gap-3 border-b border-purple-900/40 pb-4">
              <div className="w-10 h-10 rounded-xl bg-purple-600/30 border border-purple-500/40 flex items-center justify-center text-purple-300">
                <CreditCard className="w-5 h-5" />
              </div>
              <div>
                <h3 className="text-xl font-bold text-white">ثبت سفارش و پرداخت</h3>
                <p className="text-xs text-zinc-400 mt-0.5">
                  اطلاعات تماس خود را برای دریافت فاکتور و کانفیگ WireGuard وارد نمایید.
                </p>
              </div>
            </div>

            {/* Form Fields */}
            <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
              <div>
                <label className="block text-xs font-bold text-zinc-300 mb-1.5">
                  نام و نام خانوادگی <span className="text-rose-400">*</span>
                </label>
                <input
                  type="text"
                  required
                  value={name}
                  onChange={(e) => setName(e.target.value)}
                  placeholder="مثال: رضا محمدی"
                  className="w-full bg-[#0c071a] text-sm text-zinc-100 placeholder-zinc-500 px-3.5 py-2.5 rounded-xl border border-purple-500/20 focus:border-purple-500 focus:outline-none"
                />
              </div>

              <div>
                <label className="block text-xs font-bold text-zinc-300 mb-1.5">
                  شماره موبایل <span className="text-rose-400">*</span>
                </label>
                <input
                  type="tel"
                  required
                  value={mobile}
                  onChange={(e) => setMobile(e.target.value)}
                  placeholder="09123456789"
                  className="w-full bg-[#0c071a] text-sm text-zinc-100 placeholder-zinc-500 px-3.5 py-2.5 rounded-xl border border-purple-500/20 focus:border-purple-500 focus:outline-none text-left font-mono"
                  dir="ltr"
                />
              </div>

              <div className="sm:col-span-2">
                <label className="block text-xs font-bold text-zinc-300 mb-1.5">
                  ایمیل (جهت ارسال فاکتور و کانفیگ)
                </label>
                <input
                  type="email"
                  value={email}
                  onChange={(e) => setEmail(e.target.value)}
                  placeholder="you@example.com"
                  className="w-full bg-[#0c071a] text-sm text-zinc-100 placeholder-zinc-500 px-3.5 py-2.5 rounded-xl border border-purple-500/20 focus:border-purple-500 focus:outline-none text-left font-mono"
                  dir="ltr"
                />
              </div>

              <div className="sm:col-span-2">
                <label className="block text-xs font-bold text-zinc-300 mb-1.5">
                  یادداشت سفارش (اختیاری)
                </label>
                <input
                  type="text"
                  value={notes}
                  onChange={(e) => setNotes(e.target.value)}
                  placeholder="مثال: توضیحات مربوط به سفارش (اختیاری)"
                  className="w-full bg-[#0c071a] text-sm text-zinc-100 placeholder-zinc-500 px-3.5 py-2.5 rounded-xl border border-purple-500/20 focus:border-purple-500 focus:outline-none"
                />
              </div>
            </div>

            {/* ZarinPal Payment Gateway */}
            <div className="space-y-2 pt-2">
              <label className="block text-xs font-bold text-zinc-300 mb-1.5">روش پرداخت:</label>
              <div className="p-4 rounded-xl border bg-purple-900/30 border-purple-500 shadow-md text-right">
                <div className="flex items-center justify-between mb-1">
                  <span className="text-xs font-black text-white">پرداخت آنلاین با زرین‌پال</span>
                  <span className="w-2.5 h-2.5 rounded-full bg-emerald-400 shadow-[0_0_12px_rgba(52,211,153,.7)]" />
                </div>
                <span className="text-[11px] text-zinc-300">پرداخت امن از طریق درگاه زرین‌پال؛ اتصال واقعی درگاه پس از دریافت اطلاعات پذیرنده فعال می‌شود.</span>
              </div>
            </div>

            {/* Order Final Summary */}
            <div className="p-4 rounded-2xl bg-[#0c071a] border border-purple-500/20 space-y-2 text-xs">
              <div className="flex justify-between text-zinc-400">
                <span>تعداد کل اقلام:</span>
                <span className="font-semibold text-zinc-200">{toPersianDigits(items.reduce((acc, i) => acc + i.quantity, 0))} عدد</span>
              </div>

              <div className="flex justify-between text-zinc-400">
                <span>مبلغ کل:</span>
                <span className="font-semibold text-zinc-200">{formatPrice(subtotal)}</span>
              </div>

              {discountAmount > 0 && (
                <div className="flex justify-between text-emerald-400">
                  <span>تخفیف اعمال شده ({couponCode}):</span>
                  <span className="font-bold">-{formatPrice(discountAmount)}</span>
                </div>
              )}

              <div className="flex justify-between text-base font-black text-white pt-2 border-t border-purple-900/40">
                <span>مبلغ نهایی قابل پرداخت:</span>
                <span className="text-purple-300">{formatPrice(finalTotal)}</span>
              </div>
            </div>

            {/* Submit Button */}
            <button
              type="submit"
              disabled={submitting}
              className="w-full py-4 rounded-xl bg-gradient-to-r from-purple-600 to-indigo-600 hover:from-purple-500 hover:to-indigo-500 text-white font-bold text-sm shadow-xl shadow-purple-600/30 transition-all hover:scale-[1.01] active:scale-95 disabled:opacity-50 flex items-center justify-center gap-2"
            >
              {submitting ? (
                <span>در حال ثبت سفارش...</span>
              ) : (
                <>
                  <ShieldCheck className="w-5 h-5" />
                  <span>ثبت سفارش — {formatPrice(finalTotal)}</span>
                </>
              )}
            </button>

          </form>
        )}

      </motion.div>
    </div>
  );
};
