import React, { useState } from 'react';
import { CreditCard, Landmark, Phone, CheckCircle, Loader2, ShieldCheck, X } from 'lucide-react';
import { Course, Language } from '../types';
import { translations } from '../data';

interface PaystackModalProps {
  course: Course;
  currency: 'NGN' | 'USD';
  lang: Language;
  onSuccess: () => void;
  onClose: () => void;
}

export default function PaystackModal({ course, currency, lang, onSuccess, onClose }: PaystackModalProps) {
  const t = translations[lang];
  const [activeTab, setActiveTab] = useState<'card' | 'bank' | 'ussd'>('card');
  const [paymentState, setPaymentState] = useState<'idle' | 'processing' | 'success'>('idle');
  
  // Card form states
  const [cardNumber, setCardNumber] = useState('');
  const [cardExpiry, setCardExpiry] = useState('');
  const [cardCVV, setCardCVV] = useState('');
  const [error, setError] = useState('');

  const amount = currency === 'NGN' ? course.price : course.priceUSD;
  const currencySymbol = currency === 'NGN' ? '₦' : '$';

  const handleCardNumberChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    let value = e.target.value.replace(/\D/g, '');
    if (value.length > 16) value = value.slice(0, 16);
    // Add spaces every 4 digits
    const formatted = value.match(/.{1,4}/g)?.join(' ') || value;
    setCardNumber(formatted);
  };

  const handleExpiryChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    let value = e.target.value.replace(/\D/g, '');
    if (value.length > 4) value = value.slice(0, 4);
    if (value.length > 2) {
      value = value.slice(0, 2) + '/' + value.slice(2);
    }
    setCardExpiry(value);
  };

  const handleCVVChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const value = e.target.value.replace(/\D/g, '').slice(0, 3);
    setCardCVV(value);
  };

  const handlePay = (e: React.FormEvent) => {
    e.preventDefault();
    setError('');

    if (activeTab === 'card') {
      if (cardNumber.replace(/\s/g, '').length < 16) {
        setError(lang === 'en' ? 'Please enter a valid 16-digit card number.' : 'يرجى إدخال رقم بطاقة صالح مكون من ١٦ رقماً.');
        return;
      }
      if (!cardExpiry.includes('/') || cardExpiry.length < 5) {
        setError(lang === 'en' ? 'Please enter a valid expiry date (MM/YY).' : 'يرجى إدخال تاريخ انتهاء صلاحية صالح (شهر/سنة).');
        return;
      }
      if (cardCVV.length < 3) {
        setError(lang === 'en' ? 'Please enter a valid 3-digit CVV.' : 'يرجى إدخال رمز CVV صحيح من ٣ أرقام.');
        return;
      }
    }

    // Trigger simulation
    setPaymentState('processing');
    setTimeout(() => {
      setPaymentState('success');
      setTimeout(() => {
        onSuccess();
      }, 1800);
    }, 2200);
  };

  return (
    <div className="fixed inset-0 bg-black/65 backdrop-blur-sm z-50 flex items-center justify-center p-4">
      {/* Modal Container */}
      <div 
        className="bg-white rounded-2xl max-w-md w-full overflow-hidden shadow-2xl border border-teal-50 animate-in fade-in zoom-in-95 duration-200"
        dir={lang === 'ar' ? 'rtl' : 'ltr'}
      >
        {/* Paystack Header */}
        <div className="bg-[#09A5DB] text-white p-5 relative flex items-center justify-between">
          <div className="flex items-center gap-3">
            {/* Custom Paystack green dot indicator logo */}
            <div className="bg-white p-1.5 rounded-lg flex items-center justify-center shadow-sm">
              <span className="text-[#3bb75e] font-extrabold text-lg tracking-tight">p</span>
            </div>
            <div>
              <h3 className="font-sans font-bold text-base leading-tight tracking-tight">
                {t.paystackHeading}
              </h3>
              <p className="text-xs text-blue-50/90 font-mono mt-0.5">
                {t.paystackSub}
              </p>
            </div>
          </div>
          <button 
            onClick={onClose}
            className="text-white hover:bg-white/10 p-1.5 rounded-full transition-colors absolute right-4 top-4"
            aria-label="Close"
          >
            <X size={20} />
          </button>
        </div>

        {/* Course Price Quick View */}
        <div className="bg-teal-50/50 p-4 border-b border-teal-100 flex justify-between items-center px-6">
          <div className="text-left">
            <span className="text-xs text-gray-500 font-sans block">
              {lang === 'en' ? 'Course to Purchase' : 'الدورة المطلوبة'}
            </span>
            <span className="text-sm font-semibold text-gray-800 line-clamp-1">
              {lang === 'en' ? course.title : course.titleAr}
            </span>
          </div>
          <div className="text-right">
            <span className="text-xs text-gray-500 font-sans block">
              {lang === 'en' ? 'Total Amount' : 'المبلغ الإجمالي'}
            </span>
            <span className="text-base font-bold text-teal-700 font-mono">
              {currencySymbol}{amount.toLocaleString()}
            </span>
          </div>
        </div>

        {paymentState === 'idle' && (
          <div className="p-6">
            {/* Paystack Tab Selectors */}
            <div className="grid grid-cols-3 gap-2 bg-gray-100 p-1 rounded-lg mb-6">
              <button
                type="button"
                onClick={() => { setActiveTab('card'); setError(''); }}
                className={`flex flex-col items-center py-2 px-1 rounded-md text-xs font-medium transition-all ${
                  activeTab === 'card'
                    ? 'bg-white text-[#09A5DB] shadow-sm'
                    : 'text-gray-500 hover:text-gray-800'
                }`}
              >
                <CreditCard size={16} className="mb-1" />
                <span>{t.paystackCard}</span>
              </button>
              <button
                type="button"
                onClick={() => { setActiveTab('bank'); setError(''); }}
                className={`flex flex-col items-center py-2 px-1 rounded-md text-xs font-medium transition-all ${
                  activeTab === 'bank'
                    ? 'bg-white text-[#09A5DB] shadow-sm'
                    : 'text-gray-500 hover:text-gray-800'
                }`}
              >
                <Landmark size={16} className="mb-1" />
                <span>{lang === 'en' ? 'Bank Transfer' : 'حوالة بنكية'}</span>
              </button>
              <button
                type="button"
                onClick={() => { setActiveTab('ussd'); setError(''); }}
                className={`flex flex-col items-center py-2 px-1 rounded-md text-xs font-medium transition-all ${
                  activeTab === 'ussd'
                    ? 'bg-white text-[#09A5DB] shadow-sm'
                    : 'text-gray-500 hover:text-gray-800'
                }`}
              >
                <Phone size={16} className="mb-1" />
                <span>{t.paystackUSSD}</span>
              </button>
            </div>

            {error && (
              <div className="bg-red-50 text-red-600 p-3 rounded-lg text-xs mb-4 border border-red-100 text-center font-medium">
                {error}
              </div>
            )}

            <form onSubmit={handlePay}>
              {/* Card Form */}
              {activeTab === 'card' && (
                <div className="space-y-4">
                  <div>
                    <label className="block text-xs font-semibold text-gray-600 mb-1">
                      {t.cardNumber}
                    </label>
                    <input
                      type="text"
                      value={cardNumber}
                      onChange={handleCardNumberChange}
                      placeholder="4012 3456 7890 1234"
                      className="w-full border border-gray-300 rounded-lg p-2.5 text-sm font-mono focus:outline-none focus:ring-2 focus:ring-[#09A5DB]/20 focus:border-[#09A5DB] transition-all"
                      required
                    />
                  </div>
                  <div className="grid grid-cols-2 gap-4">
                    <div>
                      <label className="block text-xs font-semibold text-gray-600 mb-1">
                        {t.cardExpiry}
                      </label>
                      <input
                        type="text"
                        value={cardExpiry}
                        onChange={handleExpiryChange}
                        placeholder="MM/YY"
                        className="w-full border border-gray-300 rounded-lg p-2.5 text-sm font-mono text-center focus:outline-none focus:ring-2 focus:ring-[#09A5DB]/20 focus:border-[#09A5DB] transition-all"
                        required
                      />
                    </div>
                    <div>
                      <label className="block text-xs font-semibold text-gray-600 mb-1">
                        {t.cardCVV}
                      </label>
                      <input
                        type="password"
                        value={cardCVV}
                        onChange={handleCVVChange}
                        placeholder="123"
                        className="w-full border border-gray-300 rounded-lg p-2.5 text-sm font-mono text-center focus:outline-none focus:ring-2 focus:ring-[#09A5DB]/20 focus:border-[#09A5DB] transition-all"
                        required
                      />
                    </div>
                  </div>
                </div>
              )}

              {/* Bank Transfer */}
              {activeTab === 'bank' && (
                <div className="space-y-4 text-center py-2">
                  <p className="text-xs text-gray-600 leading-relaxed">
                    {lang === 'en' 
                      ? 'Transfer the exact amount to the temporary bank account below. Paystack will automatically detect the payment.'
                      : 'قم بتحويل المبلغ الدقيق إلى الحساب المصرفي المؤقت أدناه. سيكتشف نظام بيستك عملية الدفع تلقائياً.'}
                  </p>
                  <div className="bg-gray-50 rounded-xl p-4 border border-gray-100 text-left space-y-2">
                    <div className="flex justify-between items-center text-xs">
                      <span className="text-gray-400">Bank Name</span>
                      <span className="font-bold text-gray-800">Wema Bank (Paystack Account)</span>
                    </div>
                    <div className="flex justify-between items-center text-xs">
                      <span className="text-gray-400">Account Number</span>
                      <span className="font-mono font-bold text-gray-800 text-sm">9026461916</span>
                    </div>
                    <div className="flex justify-between items-center text-xs">
                      <span className="text-gray-400">Beneficiary</span>
                      <span className="font-bold text-teal-800">Dar Al-Fikr Academy LMS</span>
                    </div>
                  </div>
                  <p className="text-[10px] text-amber-600 font-semibold">
                    {lang === 'en' 
                      ? '⚠️ Accounts are valid for 20 minutes only.' 
                      : '⚠️ الحسابات صالحة لمدة ٢٠ دقيقة فقط.'}
                  </p>
                </div>
              )}

              {/* USSD */}
              {activeTab === 'ussd' && (
                <div className="space-y-4 text-center py-2">
                  <p className="text-xs text-gray-600 leading-relaxed">
                    {lang === 'en'
                      ? 'Dial the fast-code below on your registered phone number to complete this authorization.'
                      : 'اطلب الرمز السريع أدناه من هاتف المحمول المسجل لتفويض العملية بأمان.'}
                  </p>
                  <div className="bg-amber-50/50 rounded-xl p-4 border border-amber-100 font-mono text-center">
                    <span className="text-base font-bold text-amber-700 block">*737*1*9026461916#</span>
                    <span className="text-[10px] text-amber-600 mt-1 block">GTBank Secure Paystack Channel</span>
                  </div>
                </div>
              )}

              {/* Pay Submit Button */}
              <button
                type="submit"
                className="w-full bg-[#3bb75e] hover:bg-[#329e4f] text-white py-3 px-4 rounded-xl font-semibold text-sm mt-6 flex items-center justify-center gap-2 shadow-md transition-all active:scale-[0.98]"
              >
                <ShieldCheck size={18} />
                <span>
                  {t.payAmount} {currencySymbol}{amount.toLocaleString()}
                </span>
              </button>
            </form>

            <div className="mt-4 flex items-center justify-center gap-1.5 text-[10px] text-gray-400">
              <ShieldCheck size={12} className="text-[#3bb75e]" />
              <span>Secured by Paystack | PCI-DSS Certified</span>
            </div>
          </div>
        )}

        {/* Processing State */}
        {paymentState === 'processing' && (
          <div className="p-12 text-center flex flex-col items-center justify-center space-y-4 min-h-[300px]">
            <Loader2 className="animate-spin text-[#09A5DB]" size={48} />
            <h4 className="font-sans font-bold text-gray-700 text-base mt-2">
              {t.paymentProcessing}
            </h4>
            <p className="text-xs text-gray-400">
              {lang === 'en' ? 'Verifying 3D-Secure credentials and banking channel...' : 'جاري التحقق من الهوية الثلاثية للبطاقة والقنوات المصرفية المصرح بها...'}
            </p>
          </div>
        )}

        {/* Success State */}
        {paymentState === 'success' && (
          <div className="p-12 text-center flex flex-col items-center justify-center space-y-4 min-h-[300px] animate-in zoom-in-95 duration-300">
            <CheckCircle className="text-[#3bb75e]" size={64} />
            <h4 className="font-sans font-bold text-gray-800 text-lg">
              {t.paymentSuccess}
            </h4>
            <div className="bg-teal-50/80 px-4 py-2.5 rounded-lg text-xs text-teal-800 font-medium">
              {t.successNotice}
            </div>
            <p className="text-xs text-gray-400 font-mono">
              Ref ID: DF-{Math.floor(100000 + Math.random() * 900000)}
            </p>
          </div>
        )}
      </div>
    </div>
  );
}
