import React, { useState } from 'react';
import {
  ShieldAlert,
  CheckCircle2,
  XCircle,
  AlertTriangle,
  Loader2,
  Smartphone,
  CreditCard,
  Building,
  ArrowRight,
  Sparkles,
  Lock
} from 'lucide-react';
import { useApp } from '../context/AppContext';

interface SandboxPaymentModalProps {
  transactionId: string;
  gateway: 'bkash' | 'nagad' | 'rocket' | 'sslcommerz' | 'shurjopay' | 'aamarpay';
  amount: number;
  listingName: string;
  onComplete: (success: boolean, message: string, transactionId: string) => void;
  onCancel: () => void;
}

export const SandboxPaymentModal: React.FC<SandboxPaymentModalProps> = ({
  transactionId,
  gateway,
  amount,
  listingName,
  onComplete,
  onCancel,
}) => {
  const { settings, tNum } = useApp();
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [actionStep, setActionStep] = useState<'prompt' | 'processing'>('prompt');
  const [selectedScenario, setSelectedScenario] = useState<'success' | 'fail' | 'cancel'>('success');
  const [customOtp, setCustomOtp] = useState('1234');
  const [customPin, setCustomPin] = useState('12345');

  const getGatewayTheme = () => {
    switch (gateway) {
      case 'bkash':
        return {
          name: 'bKash Checkout (Sandbox)',
          bg: '#E2136E',
          textColor: '#FFFFFF',
          accent: 'bg-[#E2136E] text-white',
          border: 'border-[#E2136E]/40',
          badge: 'bKash Direct Tokenized API',
        };
      case 'nagad':
        return {
          name: 'Nagad PGW (Sandbox)',
          bg: '#F7941D',
          textColor: '#FFFFFF',
          accent: 'bg-[#F7941D] text-white',
          border: 'border-[#F7941D]/40',
          badge: 'Nagad E-Commerce Gateway',
        };
      case 'rocket':
        return {
          name: 'DBBL Rocket (Sandbox)',
          bg: '#8B1E78',
          textColor: '#FFFFFF',
          accent: 'bg-[#8B1E78] text-white',
          border: 'border-[#8B1E78]/40',
          badge: 'Rocket MFS Terminal API',
        };
      case 'sslcommerz':
        return {
          name: 'SSLCommerz Hosted Pay (Sandbox)',
          bg: '#006A4E',
          textColor: '#FFFFFF',
          accent: 'bg-[#006A4E] text-white',
          border: 'border-[#006A4E]/40',
          badge: 'SSLCommerz Gateway Engine',
        };
      case 'aamarpay':
        return {
          name: 'aamarPay Super Checkout (Sandbox)',
          bg: '#5E3BEE',
          textColor: '#FFFFFF',
          accent: 'bg-[#5E3BEE] text-white',
          border: 'border-[#5E3BEE]/40',
          badge: 'aamarPay Multi-Channel PGW',
        };
      default:
        return {
          name: `${gateway.toUpperCase()} PGW (Sandbox)`,
          bg: '#10B981',
          textColor: '#FFFFFF',
          accent: 'bg-emerald-600 text-white',
          border: 'border-emerald-500/40',
          badge: 'Bangladesh Payment Gateway',
        };
    }
  };

  const theme = getGatewayTheme();

  const handleExecuteScenario = async (scenario: 'success' | 'fail' | 'cancel') => {
    setIsSubmitting(true);
    setActionStep('processing');

    try {
      const res = await fetch('/api/payments/sandbox/action', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          transactionId,
          action: scenario,
        }),
      });

      const data = await res.json();
      setTimeout(() => {
        setIsSubmitting(false);
        if (data.success) {
          onComplete(true, data.message || 'Payment successfully verified!', transactionId);
        } else {
          onComplete(false, data.message || 'Payment simulation failed or cancelled.', transactionId);
        }
      }, 1000);
    } catch {
      setIsSubmitting(false);
      onComplete(false, 'Network error during sandbox verification.', transactionId);
    }
  };

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center p-3 sm:p-4 md:p-6 bg-black/80 backdrop-blur-md animate-in fade-in duration-200">
      <div
        className="w-full max-w-md rounded-2xl bg-[#11161B] border border-[#2A3440] shadow-2xl overflow-hidden text-left flex flex-col max-h-[92dvh] sm:max-h-[88dvh] relative"
        style={{ borderColor: 'var(--border-color, #2A3440)' }}
      >
        {/* Gateway Header Banner */}
        <div
          className="p-4 sm:p-5 text-white flex items-center justify-between shadow-md shrink-0"
          style={{ backgroundColor: theme.bg }}
        >
          <div className="flex items-center gap-3">
            <div className="w-10 h-10 rounded-xl bg-white/20 backdrop-blur-sm flex items-center justify-center font-black text-white text-base">
              {gateway === 'bkash' && 'bK'}
              {gateway === 'nagad' && 'NG'}
              {gateway === 'rocket' && 'RK'}
              {gateway === 'sslcommerz' && 'SSL'}
              {gateway === 'shurjopay' && 'SP'}
              {gateway === 'aamarpay' && 'AP'}
            </div>
            <div>
              <h3 className="font-bold text-base tracking-tight">{theme.name}</h3>
              <p className="text-[11px] opacity-90 font-mono">{theme.badge}</p>
            </div>
          </div>
          <span className="px-2.5 py-1 rounded-full bg-black/30 text-[10px] font-bold tracking-wider font-mono border border-white/20">
            TEST MODE
          </span>
        </div>

        {/* Info & Sandbox Notice */}
        <div className="p-4 sm:p-5 space-y-4 overflow-y-auto flex-1 overscroll-contain">
          <div className="p-3 rounded-xl bg-amber-500/10 border border-amber-500/30 text-amber-300 text-xs flex items-start gap-2.5">
            <ShieldAlert className="w-4 h-4 text-amber-400 shrink-0 mt-0.5" />
            <div>
              <strong className="block font-semibold">Active Sandbox Simulator</strong>
              <span>
                Testing end-to-end server verification without real money. The backend will execute complete transaction validation and idempotency handling.
              </span>
            </div>
          </div>

          {/* Invoice Summary Card */}
          <div className="p-3.5 rounded-xl bg-[#0A0D0F] border border-[#222A33] space-y-2 text-xs">
            <div className="flex items-center justify-between text-slate-400">
              <span>Merchant Order:</span>
              <span className="font-mono text-slate-200 font-bold">{listingName}</span>
            </div>
            <div className="flex items-center justify-between text-slate-400">
              <span>Internal Txn ID:</span>
              <span className="font-mono text-slate-300">{transactionId}</span>
            </div>
            <div className="border-t border-[#1D252E] pt-2 flex items-center justify-between">
              <span className="font-bold text-white">Amount to Pay:</span>
              <span className="font-mono font-black text-base text-emerald-400">
                {settings.currency_symbol}{tNum(amount)}
              </span>
            </div>
          </div>

          {/* Mock Interactive Flow */}
          {actionStep === 'prompt' && (
            <div className="space-y-3">
              <div className="space-y-1 text-xs">
                <label className="text-slate-300 font-semibold flex items-center justify-between">
                  <span>Simulated OTP / Wallet PIN</span>
                  <span className="text-[10px] text-slate-500 font-mono">Auto-filled for sandbox test</span>
                </label>
                <div className="grid grid-cols-2 gap-2 font-mono">
                  <input
                    type="text"
                    value={customOtp}
                    onChange={e => setCustomOtp(e.target.value)}
                    placeholder="OTP (1234)"
                    className="w-full px-3 py-2 bg-[#0A0D0F] border border-[#222A33] rounded-xl text-white text-xs focus:border-emerald-500 focus:outline-none"
                  />
                  <input
                    type="password"
                    value={customPin}
                    onChange={e => setCustomPin(e.target.value)}
                    placeholder="PIN (12345)"
                    className="w-full px-3 py-2 bg-[#0A0D0F] border border-[#222A33] rounded-xl text-white text-xs focus:border-emerald-500 focus:outline-none"
                  />
                </div>
              </div>

              {/* Simulation Action Buttons */}
              <div className="pt-2 space-y-2">
                <button
                  type="button"
                  disabled={isSubmitting}
                  onClick={() => handleExecuteScenario('success')}
                  className="w-full py-3 px-4 rounded-xl bg-emerald-600 hover:bg-emerald-500 text-white font-bold text-xs sm:text-sm flex items-center justify-center gap-2 shadow-lg shadow-emerald-950/40 transition-all cursor-pointer"
                >
                  <CheckCircle2 className="w-4 h-4" />
                  <span>Simulate Successful Payment (Instant Verify)</span>
                </button>

                <div className="grid grid-cols-2 gap-2">
                  <button
                    type="button"
                    disabled={isSubmitting}
                    onClick={() => handleExecuteScenario('fail')}
                    className="py-2.5 px-3 rounded-xl bg-rose-950/40 border border-rose-800/40 hover:bg-rose-900/50 text-rose-300 font-semibold text-xs flex items-center justify-center gap-1.5 transition-all cursor-pointer"
                  >
                    <XCircle className="w-3.5 h-3.5" />
                    <span>Simulate Failed Payment</span>
                  </button>

                  <button
                    type="button"
                    disabled={isSubmitting}
                    onClick={() => handleExecuteScenario('cancel')}
                    className="py-2.5 px-3 rounded-xl bg-slate-800 hover:bg-slate-700 text-slate-300 font-semibold text-xs flex items-center justify-center gap-1.5 transition-all cursor-pointer"
                  >
                    <AlertTriangle className="w-3.5 h-3.5" />
                    <span>Cancel / Abort</span>
                  </button>
                </div>
              </div>
            </div>
          )}

          {/* Processing State */}
          {actionStep === 'processing' && (
            <div className="py-6 text-center space-y-3">
              <div className="w-12 h-12 rounded-xl bg-emerald-500/20 border border-emerald-500/30 flex items-center justify-center mx-auto text-emerald-400">
                <Loader2 className="w-6 h-6 animate-spin" />
              </div>
              <div className="space-y-1">
                <h4 className="font-bold text-white text-sm">Validating with {gateway.toUpperCase()} Server...</h4>
                <p className="text-xs text-slate-400 font-mono">Executing server-side payment callback & rank recalculation</p>
              </div>
            </div>
          )}
        </div>
      </div>
    </div>
  );
};
