/**
 * @license
 * SPDX-License-Identifier: Apache-2.0
 */

import React, { useState, useEffect } from 'react';
import { Property, Booking, UserAccount } from '../types';
import { 
  CreditCard, 
  Wallet, 
  Smartphone, 
  HelpCircle, 
  Check, 
  Clock, 
  ArrowRight, 
  ShieldCheck, 
  AlertCircle,
  QrCode,
  Sparkles,
  Info,
  Flame,
  Printer,
  ChevronRight,
  IndianRupee,
  Lock,
  Coins
} from 'lucide-react';

interface PaymentModalProps {
  property: Property;
  bookingData: {
    userName: string;
    userEmail: string;
    vehicleNumber: string;
    vehicleType: 'Car' | 'Two-Wheeler';
    bookingDate: string;
    timeSlot: string;
    totalHours: number;
    totalFare: number;
  };
  currentUser: UserAccount;
  onPaymentSuccess: (paymentMethod: 'PhonePe' | 'Card' | 'COD' | 'Wallet', paymentStatus: 'Paid' | 'Pending') => void;
  onCancel: () => void;
}

export default function PaymentModal({
  property,
  bookingData,
  currentUser,
  onPaymentSuccess,
  onCancel
}: PaymentModalProps) {
  
  // Choose payment method (PhonePe, Card, COD, Wallet)
  const [method, setMethod] = useState<'PhonePe' | 'Card' | 'COD' | 'Wallet'>('PhonePe');
  
  // Processing States
  const [stage, setStage] = useState<'selection' | 'processing' | 'success'>('selection');
  const [timer, setTimer] = useState<number>(0);
  const [otpSent, setOtpSent] = useState(false);
  const [generatedTicketCode, setGeneratedTicketCode] = useState('');

  // Form states
  const [upiId, setUpiId] = useState(`${bookingData.userName.toLowerCase().replace(/\s+/g, '')}@ybl`);
  const [cardNumber, setCardNumber] = useState('');
  const [cardExpiry, setCardExpiry] = useState('');
  const [cardCvv, setCardCvv] = useState('');
  const [cardHolder, setCardHolder] = useState(bookingData.userName);

  // Read driver live wallet details
  const walletBalance = currentUser.walletBalance ?? 0;
  const isWalletSufficient = walletBalance >= bookingData.totalFare;

  // Generate confirmation security code upon success
  useEffect(() => {
    const code = 'CP-' + Math.floor(100000 + Math.random() * 900000).toString();
    setGeneratedTicketCode(code);
  }, []);

  const handleProcessPayment = (e: React.FormEvent) => {
    e.preventDefault();
    setStage('processing');
    
    // Simulate real gateway latency
    let count = 0;
    const interval = setInterval(() => {
      count++;
      if (count >= 2) {
        clearInterval(interval);
        setStage('success');
      }
    }, 1000);
  };

  const confirmReceiptSuccess = () => {
    // Return parameters up to App
    const finalStatus = method === 'COD' ? 'Pending' : 'Paid';
    onPaymentSuccess(method, finalStatus);
  };

  return (
    <div className="fixed inset-0 bg-slate-950/80 backdrop-blur-sm z-50 flex items-center justify-center p-4 overflow-y-auto selection:bg-amber-500 selection:text-slate-900 select-none">
      
      <div className="bg-slate-900 border border-slate-800 rounded-3xl w-full max-w-lg overflow-hidden shadow-2xl relative text-slate-100 my-8">
        
        {/* Banner border highlight */}
        <div className="h-1.5 bg-gradient-to-r from-amber-500 via-emerald-500 to-sky-500" />

        {/* STAGE A: SELECTION & GATEWAYS OPTIONS */}
        {stage === 'selection' && (
          <div className="p-6 md:p-8 space-y-6">
            
            {/* Header info */}
            <div className="flex justify-between items-center pb-4 border-b border-slate-800">
              <div>
                <span className="text-[9px] bg-amber-500/10 text-amber-400 border border-amber-500/20 px-2 py-0.5 rounded font-black tracking-wider uppercase font-mono">
                  Secure Checkout
                </span>
                <h3 className="text-lg font-black text-white mt-1">Select Payment Gateway</h3>
              </div>
              <button
                onClick={onCancel}
                className="text-slate-400 hover:text-white transition-all text-xs font-bold"
              >
                ✕ Cancel
              </button>
            </div>

            {/* Quick Invoice overview summary */}
            <div className="bg-slate-950 p-4 rounded-2xl border border-slate-800/80 space-y-3 font-mono text-xs text-left">
              <div className="flex justify-between items-start">
                <div>
                  <span className="text-[10px] text-slate-500 block font-bold uppercase">Spot Reserved</span>
                  <strong className="text-white text-sm font-sans font-black">{property.title}</strong>
                </div>
                <div className="text-right">
                  <span className="text-[10px] text-slate-500 block font-bold uppercase">Total Fare</span>
                  <strong className="text-amber-400 text-base font-black flex items-center justify-end">
                    <IndianRupee className="w-4 h-4 text-amber-500" /> {bookingData.totalFare}
                  </strong>
                </div>
              </div>

              <div className="grid grid-cols-2 gap-3 pt-2 border-t border-slate-850 text-[10px] text-slate-400 font-medium">
                <div>🕐 Time Slot: <strong className="text-slate-200">{bookingData.timeSlot}</strong></div>
                <div>📅 Date: <strong className="text-slate-200">{bookingData.bookingDate}</strong></div>
                <div>🚗 Vehicle Plate: <strong className="text-amber-400 font-mono">{bookingData.vehicleNumber}</strong></div>
                <div>🕒 Hours Blocked: <strong className="text-slate-200">{bookingData.totalHours} hr</strong></div>
              </div>
            </div>

            {/* Selector Grid Buttons (PhonePe, Card, Wallet, COD) */}
            <div className="grid grid-cols-2 sm:grid-cols-4 gap-2">
              
              {/* PhonePe UPI */}
              <button
                type="button"
                onClick={() => setMethod('PhonePe')}
                className={`py-3 px-2 rounded-2xl border-2 flex flex-col items-center justify-center gap-1.5 transition-all outline-none
                  ${method === 'PhonePe' 
                    ? 'border-violet-600 bg-violet-950/20 text-white' 
                    : 'border-slate-800 bg-slate-950 text-slate-400 hover:border-slate-700'}`}
              >
                <div className="w-7 h-7 rounded-lg bg-violet-600 flex items-center justify-center font-black text-white text-[10px]">
                  PP
                </div>
                <span className="text-[10px] font-black tracking-tight font-sans">PhonePe UPI</span>
              </button>

              {/* Online Debit/Credit Cards */}
              <button
                type="button"
                onClick={() => setMethod('Card')}
                className={`py-3 px-2 rounded-2xl border-2 flex flex-col items-center justify-center gap-1.5 transition-all outline-none
                  ${method === 'Card' 
                    ? 'border-amber-500 bg-amber-500/5 text-white' 
                    : 'border-slate-800 bg-slate-950 text-slate-400 hover:border-slate-700'}`}
              >
                <CreditCard className={`w-6 h-6 ${method === 'Card' ? 'text-amber-400' : 'text-slate-500'}`} />
                <span className="text-[10px] font-black tracking-tight font-sans">Debit Card</span>
              </button>

              {/* App Wallet balance */}
              <button
                type="button"
                onClick={() => setMethod('Wallet')}
                className={`py-3 px-2 rounded-2xl border-2 flex flex-col items-center justify-center gap-1.5 transition-all outline-none
                  ${method === 'Wallet' 
                    ? 'border-teal-500 bg-teal-950/20 text-white' 
                    : 'border-slate-800 bg-slate-950 text-slate-400 hover:border-slate-700'}`}
              >
                <Coins className={`w-6 h-6 ${method === 'Wallet' ? 'text-teal-400' : 'text-slate-500'}`} />
                <span className="text-[10px] font-black tracking-tight font-sans">App Wallet</span>
              </button>

              {/* Cash On Delivery / Arrival */}
              <button
                type="button"
                onClick={() => setMethod('COD')}
                className={`py-3 px-2 rounded-2xl border-2 flex flex-col items-center justify-center gap-1.5 transition-all outline-none
                  ${method === 'COD' 
                    ? 'border-blue-500 bg-blue-500/5 text-white' 
                    : 'border-slate-800 bg-slate-950 text-slate-400 hover:border-slate-700'}`}
              >
                <Wallet className={`w-6 h-6 ${method === 'COD' ? 'text-blue-405' : 'text-slate-500'}`} />
                <span className="text-[10px] font-black tracking-tight font-sans font-sans">Pay on Spot</span>
              </button>

            </div>

            {/* Custom Payment Screen for each method */}
            <div className="bg-slate-950 p-5 rounded-2xl border border-slate-800 text-left">
              
              {/* PhonePe Gate representation */}
              {method === 'PhonePe' && (
                <form onSubmit={handleProcessPayment} className="space-y-4">
                  <div className="flex items-center gap-2 mb-1.5 pb-2 border-b border-slate-900/60">
                    <span className="text-violet-400 font-extrabold text-xs">💜 PhonePe Direct UPI Gateway</span>
                  </div>

                  <div className="space-y-1">
                    <label className="block text-[10px] text-slate-500 font-bold uppercase tracking-wider font-mono">
                      Your UPI Identification Address
                    </label>
                    <input
                      type="text"
                      required
                      value={upiId}
                      onChange={(e) => setUpiId(e.target.value)}
                      className="w-full px-3.5 py-2.5 bg-slate-900 border border-slate-800 rounded-xl text-xs font-semibold text-slate-200 outline-none focus:ring-2 focus:ring-violet-600 font-mono"
                    />
                    <p className="text-[9.5px] text-slate-500">
                      Payment request will be broadcast to your PhonePe mobile application instantly.
                    </p>
                  </div>

                  <button
                    type="submit"
                    className="w-full py-3 px-4 bg-violet-600 hover:bg-violet-500 text-white rounded-xl text-xs font-black tracking-wider uppercase transition-all flex items-center justify-center gap-1"
                  >
                    <Lock className="w-4 h-4" />
                    <span>Pay ₹{bookingData.totalFare} with UPI</span>
                  </button>
                </form>
              )}

              {/* Online Debit/Credit Cards */}
              {method === 'Card' && (
                <form onSubmit={handleProcessPayment} className="space-y-4">
                  <div className="flex items-center gap-2 mb-1.5 pb-2 border-b border-slate-900/60">
                    <span className="text-amber-500 font-extrabold text-xs">💳 Secured Card Payment Gateway</span>
                  </div>

                  <div className="space-y-3.5">
                    <div className="space-y-1">
                      <label className="block text-[10px] text-slate-500 font-bold uppercase tracking-wider font-mono">
                        Cardholder Name
                      </label>
                      <input
                        type="text"
                        required
                        value={cardHolder}
                        onChange={(e) => setCardHolder(e.target.value)}
                        className="w-full px-3.5 py-2.5 bg-slate-900 border border-slate-800 rounded-xl text-xs font-semibold text-slate-200 outline-none focus:ring-2 focus:ring-amber-500"
                      />
                    </div>

                    <div className="space-y-1">
                      <label className="block text-[10px] text-slate-500 font-bold uppercase tracking-wider font-mono">
                        16-Digit Credit Card Number
                      </label>
                      <input
                        type="text"
                        required
                        maxLength={19}
                        placeholder="4111 2222 3333 4444"
                        value={cardNumber}
                        onChange={(e) => setCardNumber(e.target.value.replace(/[^\d ]/g, ''))}
                        className="w-full px-3.5 py-2.5 bg-slate-900 border border-slate-800 rounded-xl text-xs font-semibold text-slate-200 outline-none focus:ring-2 focus:ring-amber-500 font-mono"
                      />
                    </div>

                    <div className="grid grid-cols-2 gap-3">
                      <div className="space-y-1">
                        <label className="block text-[10px] text-slate-500 font-bold uppercase tracking-wider font-mono">
                          Expiry MM/YY
                        </label>
                        <input
                          type="text"
                          required
                          maxLength={5}
                          placeholder="12/28"
                          value={cardExpiry}
                          onChange={(e) => setCardExpiry(e.target.value)}
                          className="w-full px-3.5 py-2.5 bg-slate-900 border border-slate-800 rounded-xl text-xs font-semibold text-slate-200 outline-none focus:ring-2 focus:ring-amber-500 font-mono text-center"
                        />
                      </div>

                      <div className="space-y-1">
                        <label className="block text-[10px] text-slate-500 font-bold uppercase tracking-wider font-mono">
                          CVV Code
                        </label>
                        <input
                          type="password"
                          required
                          maxLength={3}
                          placeholder="***"
                          value={cardCvv}
                          onChange={(e) => setCardCvv(e.target.value.replace(/\D/g, ''))}
                          className="w-full px-3.5 py-2.5 bg-slate-900 border border-slate-800 rounded-xl text-xs font-semibold text-slate-200 outline-none focus:ring-2 focus:ring-amber-500 font-mono text-center"
                        />
                      </div>
                    </div>
                  </div>

                  <button
                    type="submit"
                    className="w-full py-3 px-4 bg-amber-500 hover:bg-amber-400 text-slate-95 w-full text-slate-950 rounded-xl text-xs font-black tracking-wider uppercase transition-all flex items-center justify-center gap-1"
                  >
                    <Lock className="w-4 h-4" />
                    <span>Authorize Secure Transaction</span>
                  </button>
                </form>
              )}

              {/* Wallet Balance Integration */}
              {method === 'Wallet' && (
                <div className="space-y-4">
                  <div className="flex items-center gap-2 mb-1.5 pb-2 border-b border-slate-900/60 justify-between">
                    <span className="text-teal-400 font-extrabold text-xs flex items-center gap-1">
                      <Coins className="w-4 h-4" />
                      App wallet balance check
                    </span>
                    <span className="text-[10px] font-mono font-bold text-slate-500">SECURE DEDUCTION</span>
                  </div>

                  <div className="bg-slate-900 p-4 rounded-xl border border-slate-850 flex items-center justify-between">
                    <div>
                      <span className="text-[9px] text-slate-500 uppercase tracking-wider block font-bold font-mono">Available Balance</span>
                      <strong className={`text-lg font-black font-mono tracking-tight block mt-0.5
                        ${isWalletSufficient ? 'text-teal-400' : 'text-rose-455'}`}
                      >
                        ₹{walletBalance}
                      </strong>
                    </div>

                    <div className="text-right">
                      <span className="text-[9px] text-slate-500 uppercase tracking-wider block font-bold font-mono">Checkout Cost</span>
                      <strong className="text-white text-lg font-black font-mono tracking-tight block mt-0.5">
                        ₹{bookingData.totalFare}
                      </strong>
                    </div>
                  </div>

                  {isWalletSufficient ? (
                    <div className="p-3 bg-emerald-950/20 border border-emerald-900/40 rounded-xl text-[11px] text-emerald-400 font-semibold leading-relaxed">
                      🎁 Dynamic checked-in reward cash active! You have sufficient wallet balance to pay for this reservation instantly with no bank delay.
                    </div>
                  ) : (
                    <div className="p-3 bg-rose-955/15 border border-rose-900/40 rounded-xl text-[11px] text-rose-405 font-bold leading-relaxed space-y-1">
                      <div>⚠️ Insufficient Wallet Balance!</div>
                      <p className="text-slate-450 font-normal">
                        You need ₹{bookingData.totalFare - walletBalance} more to pay using this source. Please use PhonePe UPI, Credit Card, or Top Up your wallet in the Profile tab.
                      </p>
                    </div>
                  )}

                  <button
                    type="button"
                    disabled={!isWalletSufficient}
                    onClick={handleProcessPayment}
                    className={`w-full py-3 px-4 rounded-xl text-xs font-black tracking-wider uppercase transition-all flex items-center justify-center gap-1
                      ${isWalletSufficient
                        ? 'bg-teal-600 hover:bg-teal-500 text-white cursor-pointer'
                        : 'bg-slate-900/80 text-slate-600 cursor-not-allowed border border-slate-850'
                      }`}
                  >
                    <Lock className="w-4 h-4" />
                    <span>{isWalletSufficient ? `Pay ₹${bookingData.totalFare} Instantly` : 'Insufficient Funds'}</span>
                  </button>
                </div>
              )}

              {/* Pay on arrival Postpaid */}
              {method === 'COD' && (
                <div className="space-y-4">
                  <div className="flex items-center gap-2 mb-1.5 pb-2 border-b border-slate-900/60">
                    <span className="text-blue-405 font-extrabold text-xs">🤝 Postpaid Handshake Deal</span>
                  </div>

                  <div className="p-3.5 bg-blue-955/10 border border-blue-900/30 rounded-xl text-slate-350 text-[11px] leading-relaxed space-y-2 font-mono">
                    <p className="text-slate-200 font-bold">How Pay on Arrival works:</p>
                    <ul className="list-disc pl-4 space-y-1">
                      <li>Reserve place instantly without digital UPI entry now.</li>
                      <li>Produce cash, card swipe, or dynamic spot QR scan at the physical gate after parking or charging.</li>
                      <li>Highly secure for instant dispatch.</li>
                    </ul>
                  </div>

                  <button
                    type="button"
                    onClick={handleProcessPayment}
                    className="w-full py-3 px-4 bg-blue-600 hover:bg-blue-500 text-white rounded-xl text-xs font-black tracking-wider uppercase transition-all flex items-center justify-center gap-1"
                  >
                    <Lock className="w-4 h-4" />
                    <span>Confirm Offline Spot-Pay Agreement</span>
                  </button>
                </div>
              )}

            </div>

            {/* Footer trust elements */}
            <div className="flex items-center justify-center gap-2 text-slate-500 text-[10px] font-bold uppercase tracking-wider">
              <ShieldCheck className="w-4 h-4 text-emerald-500" />
              <span>ISOTC-27001 Certified Payments Secure Enclave</span>
            </div>

          </div>
        )}

        {/* STAGE B: ROUTING CHARGE / PROCESSING GRAPH */}
        {stage === 'processing' && (
          <div className="p-12 text-center space-y-6">
            <div className="relative w-16 h-16 mx-auto">
              {/* Spinning visual loading tracker */}
              <div className="w-16 h-16 rounded-full border-4 border-slate-800 border-t-amber-500 animate-spin" />
              <div className="absolute inset-0 flex items-center justify-center text-slate-400">
                <Clock className="w-6 h-6 animate-pulse" />
              </div>
            </div>
            
            <div className="space-y-2">
              <h4 className="font-extrabold text-white text-base">Contacting Banking Gateway...</h4>
              <p className="text-slate-500 text-xs font-mono max-w-sm mx-auto">
                Securely handshaking cryptographic tokens over SSL with {method} router ledger. Do not close context or press back.
              </p>
            </div>
          </div>
        )}

        {/* STAGE C: SUCCESS SPLASH BANNER */}
        {stage === 'success' && (
          <div className="p-8 md:p-10 text-center space-y-6">
            <div className="w-16 h-16 bg-emerald-500/10 border border-emerald-500/30 text-emerald-400 rounded-3xl flex items-center justify-center mx-auto shadow-lg animate-bounce">
              <Check className="w-8 h-8 stroke-[3]" />
            </div>

            <div className="space-y-2">
              <span className="text-[10px] bg-emerald-500/10 text-emerald-400 border border-emerald-500/20 px-2 py-0.5 rounded font-black tracking-widest uppercase font-mono">
                Transaction Completed
              </span>
              <h3 className="text-xl font-black text-white mt-2">Space Booked Successfully!</h3>
              <p className="text-slate-400 text-xs leading-relaxed max-w-xs mx-auto">
                Your authorization permit has been locked into the local power grid ledger for {bookingData.vehicleNumber}.
              </p>
            </div>

            {/* Simulated Receipt Pass specs */}
            <div className="bg-slate-950 p-4.5 rounded-2xl border border-slate-850 space-y-2.5 text-left text-xs font-mono">
              <div className="flex justify-between border-b border-slate-850 pb-2">
                <span className="text-slate-500 font-bold">DIGITAL PASSCODE</span>
                <span className="text-amber-400 font-black tracking-wider uppercase">{generatedTicketCode}</span>
              </div>
              <div className="space-y-1 font-semibold text-[11px] text-slate-400">
                <div>• Station Location: <strong className="text-slate-200">{property.title}</strong></div>
                <div>• Arrival Spec Date: <strong className="text-slate-200">{bookingData.bookingDate}</strong></div>
                <div>• Allocated vehicle plate: <strong className="text-amber-500 font-bold">{bookingData.vehicleNumber}</strong></div>
                <div>• Checkout receipt: sent to <strong className="text-slate-200">{bookingData.userEmail}</strong></div>
              </div>
            </div>

            <button
              onClick={confirmReceiptSuccess}
              className="w-full py-3 px-4 bg-emerald-500 hover:bg-emerald-400 text-slate-950 rounded-xl text-xs font-black tracking-wider uppercase transition-all shadow-md active:scale-95 flex items-center justify-center gap-1"
            >
              <span>Acknowledge & Sync passes</span>
              <ArrowRight className="w-4 h-4" />
            </button>
          </div>
        )}

      </div>

    </div>
  );
}
