import React, { useState } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import { X, Building2, Globe, Zap, Shield, BarChart3, Users, ChevronRight, CheckCircle2, Loader2 } from 'lucide-react';
import { base44 } from '@/api/base44Client';

const PLANS = [
  {
    id: 'growth',
    name: 'Growth',
    volume: 'Up to $10M/month',
    fee: '0.15%',
    features: ['API Access', 'Priority Support', 'Custom Limits', 'Dedicated Account Manager'],
  },
  {
    id: 'institutional',
    name: 'Institutional',
    volume: 'Up to $100M/month',
    fee: '0.08%',
    features: ['Full API Suite', '24/7 Dedicated Line', 'White-label Options', 'Custom Integrations', 'Compliance Package'],
    highlight: true,
  },
  {
    id: 'sovereign',
    name: 'Sovereign',
    volume: 'Unlimited',
    fee: 'Negotiable',
    features: ['Private Infrastructure', 'On-premise Deployment', 'Regulatory Liaison', 'Custom SLA', 'Direct Engineering Access'],
  },
];

const FEATURES = [
  { icon: <Zap className="w-5 h-5" />, label: 'Sub-millisecond Execution', desc: 'Institutional-grade latency across 195 countries' },
  { icon: <Shield className="w-5 h-5" />, label: 'SOC 2 / ISO 27001', desc: 'Full compliance stack with audit trails' },
  { icon: <BarChart3 className="w-5 h-5" />, label: 'Advanced Analytics', desc: 'Real-time dashboards, custom reporting & alerts' },
  { icon: <Globe className="w-5 h-5" />, label: 'Global Liquidity', desc: 'Deep order books across 50+ trading pairs' },
];

export default function EnterpriseModal({ onClose }) {
  const [step, setStep] = useState('overview'); // overview | contact | success
  const [selectedPlan, setSelectedPlan] = useState('institutional');
  const [form, setForm] = useState({ company: '', name: '', email: '', volume: '', message: '' });
  const [loading, setLoading] = useState(false);

  const handleSubmit = async (e) => {
    e.preventDefault();
    setLoading(true);
    await base44.integrations.Core.SendEmail({
      to: form.email,
      subject: `NEXUS Enterprise Access — ${PLANS.find(p => p.id === selectedPlan)?.name} Plan Request`,
      body: `Thank you ${form.name},\n\nWe have received your Enterprise Access request for the ${PLANS.find(p => p.id === selectedPlan)?.name} plan.\n\nExpected monthly volume: ${form.volume}\n\nOur institutional team will contact you within 24 hours.\n\n— NEXUS Financial Network`,
    });
    setLoading(false);
    setStep('success');
  };

  return (
    <AnimatePresence>
      <motion.div
        initial={{ opacity: 0 }}
        animate={{ opacity: 1 }}
        exit={{ opacity: 0 }}
        className="fixed inset-0 z-50 flex items-center justify-center bg-black/90 backdrop-blur-xl p-4"
        onClick={(e) => e.target === e.currentTarget && onClose()}
      >
        <motion.div
          initial={{ opacity: 0, scale: 0.95, y: 20 }}
          animate={{ opacity: 1, scale: 1, y: 0 }}
          exit={{ opacity: 0, scale: 0.95, y: 20 }}
          className="relative w-full max-w-4xl max-h-[90vh] overflow-y-auto bg-black border border-white/10"
        >
          {/* Corner accents */}
          <div className="absolute top-0 left-0 w-16 h-px bg-red-500/60" />
          <div className="absolute top-0 left-0 w-px h-16 bg-red-500/60" />
          <div className="absolute bottom-0 right-0 w-16 h-px bg-red-500/60" />
          <div className="absolute bottom-0 right-0 w-px h-16 bg-red-500/60" />

          {/* Header */}
          <div className="flex items-center justify-between px-8 py-6 border-b border-white/5">
            <div className="flex items-center gap-3">
              <div className="w-1.5 h-1.5 rounded-full bg-red-500 animate-pulse" />
              <span className="text-white/30 text-[10px] tracking-[0.4em] uppercase">NEXUS // Enterprise</span>
            </div>
            <button onClick={onClose} className="text-white/20 hover:text-white/60 transition-colors">
              <X className="w-5 h-5" />
            </button>
          </div>

          <div className="px-8 py-8">
            {/* SUCCESS */}
            {step === 'success' && (
              <motion.div
                initial={{ opacity: 0, y: 20 }}
                animate={{ opacity: 1, y: 0 }}
                className="flex flex-col items-center text-center py-16 gap-6"
              >
                <CheckCircle2 className="w-16 h-16 text-emerald-400" />
                <h2 className="text-2xl font-light tracking-widest text-white uppercase">Request Received</h2>
                <p className="text-white/40 text-sm tracking-wide max-w-md">
                  Our institutional team will review your application and contact <span className="text-white/70">{form.email}</span> within 24 hours.
                </p>
                <button
                  onClick={onClose}
                  className="mt-4 px-8 py-3 text-xs tracking-[0.3em] uppercase text-white/60 border border-white/10 hover:border-white/30 hover:text-white/80 transition-all"
                >
                  Close
                </button>
              </motion.div>
            )}

            {/* OVERVIEW */}
            {step === 'overview' && (
              <motion.div initial={{ opacity: 0 }} animate={{ opacity: 1 }}>
                <div className="mb-10">
                  <h1 className="text-3xl font-thin tracking-[0.2em] text-white uppercase mb-2">Enterprise Access</h1>
                  <p className="text-white/30 text-sm tracking-wide">Institutional-grade infrastructure for high-volume operations.</p>
                </div>

                {/* Features */}
                <div className="grid grid-cols-2 md:grid-cols-4 gap-4 mb-12">
                  {FEATURES.map((f) => (
                    <div key={f.label} className="border border-white/5 p-4 hover:border-white/10 transition-colors">
                      <div className="text-red-500/70 mb-3">{f.icon}</div>
                      <div className="text-white/70 text-xs tracking-wide font-medium mb-1">{f.label}</div>
                      <div className="text-white/25 text-[10px] tracking-wide leading-relaxed">{f.desc}</div>
                    </div>
                  ))}
                </div>

                {/* Plans */}
                <div className="mb-8">
                  <p className="text-white/20 text-[10px] tracking-[0.4em] uppercase mb-6">Select your plan</p>
                  <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
                    {PLANS.map((plan) => (
                      <button
                        key={plan.id}
                        onClick={() => setSelectedPlan(plan.id)}
                        className={`relative text-left p-6 border transition-all ${
                          selectedPlan === plan.id
                            ? plan.highlight
                              ? 'border-red-500/60 bg-red-500/5'
                              : 'border-white/30 bg-white/3'
                            : 'border-white/5 hover:border-white/15'
                        }`}
                      >
                        {plan.highlight && (
                          <div className="absolute top-0 left-0 right-0 h-px bg-gradient-to-r from-transparent via-red-500/60 to-transparent" />
                        )}
                        {selectedPlan === plan.id && (
                          <div className="absolute top-3 right-3 w-1.5 h-1.5 rounded-full bg-red-500" />
                        )}
                        <div className="text-white/60 text-[10px] tracking-[0.3em] uppercase mb-1">{plan.name}</div>
                        <div className="text-white text-xl font-light tracking-wide mb-1">{plan.fee}</div>
                        <div className="text-white/25 text-[10px] tracking-wide mb-4">{plan.volume}</div>
                        <ul className="space-y-1.5">
                          {plan.features.map((f) => (
                            <li key={f} className="flex items-center gap-2 text-white/35 text-[10px] tracking-wide">
                              <ChevronRight className="w-3 h-3 text-red-500/50 flex-shrink-0" />
                              {f}
                            </li>
                          ))}
                        </ul>
                      </button>
                    ))}
                  </div>
                </div>

                <button
                  onClick={() => setStep('contact')}
                  className="group relative w-full md:w-auto px-10 py-4 text-xs tracking-[0.3em] uppercase text-white border border-red-500/50 hover:border-red-400 overflow-hidden transition-all flex items-center gap-3"
                >
                  <div className="absolute inset-0 bg-red-500/0 group-hover:bg-red-500/10 transition-all" />
                  <Building2 className="w-4 h-4 relative" />
                  <span className="relative">Apply for Enterprise Access</span>
                </button>
              </motion.div>
            )}

            {/* CONTACT FORM */}
            {step === 'contact' && (
              <motion.div initial={{ opacity: 0, x: 20 }} animate={{ opacity: 1, x: 0 }}>
                <div className="flex items-center gap-4 mb-8">
                  <button onClick={() => setStep('overview')} className="text-white/30 hover:text-white/60 text-[10px] tracking-widest uppercase transition-colors">
                    ← Back
                  </button>
                  <span className="text-white/10">|</span>
                  <span className="text-white/30 text-[10px] tracking-widest uppercase">
                    {PLANS.find(p => p.id === selectedPlan)?.name} Plan
                  </span>
                </div>

                <h2 className="text-2xl font-thin tracking-[0.2em] text-white uppercase mb-2">Contact Information</h2>
                <p className="text-white/30 text-sm tracking-wide mb-8">Our institutional team will respond within 24 hours.</p>

                <form onSubmit={handleSubmit} className="space-y-4 max-w-xl">
                  {[
                    { key: 'company', label: 'Company / Institution', placeholder: 'Acme Capital Ltd.', type: 'text' },
                    { key: 'name', label: 'Contact Name', placeholder: 'John Smith', type: 'text' },
                    { key: 'email', label: 'Business Email', placeholder: 'j.smith@acmecapital.com', type: 'email' },
                    { key: 'volume', label: 'Expected Monthly Volume (USD)', placeholder: '$5,000,000', type: 'text' },
                  ].map(({ key, label, placeholder, type }) => (
                    <div key={key}>
                      <label className="block text-white/25 text-[10px] tracking-[0.3em] uppercase mb-2">{label}</label>
                      <input
                        type={type}
                        required
                        placeholder={placeholder}
                        value={form[key]}
                        onChange={(e) => setForm({ ...form, [key]: e.target.value })}
                        className="w-full bg-white/3 border border-white/10 text-white/80 text-sm px-4 py-3 placeholder-white/15 focus:outline-none focus:border-white/30 transition-colors"
                      />
                    </div>
                  ))}
                  <div>
                    <label className="block text-white/25 text-[10px] tracking-[0.3em] uppercase mb-2">Additional Notes (optional)</label>
                    <textarea
                      placeholder="Describe your use case or any specific requirements..."
                      value={form.message}
                      onChange={(e) => setForm({ ...form, message: e.target.value })}
                      rows={3}
                      className="w-full bg-white/3 border border-white/10 text-white/80 text-sm px-4 py-3 placeholder-white/15 focus:outline-none focus:border-white/30 transition-colors resize-none"
                    />
                  </div>

                  <button
                    type="submit"
                    disabled={loading}
                    className="group relative px-10 py-4 text-xs tracking-[0.3em] uppercase text-white border border-red-500/50 hover:border-red-400 overflow-hidden transition-all flex items-center gap-3 disabled:opacity-50"
                  >
                    <div className="absolute inset-0 bg-red-500/0 group-hover:bg-red-500/10 transition-all" />
                    {loading ? <Loader2 className="w-4 h-4 animate-spin relative" /> : <Users className="w-4 h-4 relative" />}
                    <span className="relative">{loading ? 'Submitting...' : 'Submit Application'}</span>
                  </button>
                </form>
              </motion.div>
            )}
          </div>
        </motion.div>
      </motion.div>
    </AnimatePresence>
  );
}