import React, { useState, useEffect } from 'react';
import { CheckCircle, AlertCircle, RefreshCw, LogIn, CreditCard, Clock, Check, X, Shield, Star, Zap } from 'lucide-react';

function MyPlanTab({ tenantToken }: { tenantToken: string }) {
  const [plans, setPlans] = useState<any[]>([]);
  const [mySub, setMySub] = useState<any>(null);
  const [myTenant, setMyTenant] = useState<any>(null);
  const [paymentMethods, setPaymentMethods] = useState<any>({});
  const [loading, setLoading] = useState(true);
  const [submitting, setSubmitting] = useState(false);
  const [selectedPlan, setSelectedPlan] = useState<any>(null);
  const [payForm, setPayForm] = useState({ payment_method: '', payment_number: '', transaction_id: '', amount: '', screenshot: '' });
  const [msg, setMsg] = useState('');

  const daysRemaining = (dateStr: string) => {
    if (!dateStr) return null;
    return Math.ceil((new Date(dateStr).getTime() - Date.now()) / 86400000);
  };

  useEffect(() => {
    const fetchData = async () => {
      setLoading(true);
      try {
        const [plansRes, subRes, ldRes] = await Promise.all([
          fetch('/api/auth/plans'),
          tenantToken ? fetch('/api/admin/tenant/me', { headers: { 'X-Tenant-Token': tenantToken } }) : Promise.resolve(null),
          fetch('/api/landing-data'),
        ]);
        const plansData = await plansRes.json();
        if (plansData.success) setPlans(plansData.data || plansData.plans || []);
        if (subRes) {
          const subData = await subRes.json();
          if (subData.success) {
            setMyTenant(subData.data);
            setMySub(subData.data?.plan_id ? { plan_id: subData.data.plan_id, status: subData.data.subscription_status } : null);
          }
        }
        const ldData = await ldRes.json();
        if (ldData.payment_methods) {
          setPaymentMethods(ldData.payment_methods);
          const enabled = ldData.payment_methods?.enabled || {};
          const first = ['bkash', 'nagad', 'rocket', 'bank'].find(m => enabled[m] !== false && ldData.payment_methods[m]);
          if (first) setPayForm(prev => ({ ...prev, payment_method: first }));
        }
      } catch { } finally { setLoading(false); }
    };
    fetchData();
  }, [tenantToken]);

  const handleSelectPlan = (plan: any) => {
    setSelectedPlan(plan);
    setPayForm(prev => ({ ...prev, amount: String(plan.price) }));
    setMsg('');
    // Scroll to payment form after render
    setTimeout(() => {
      document.getElementById('payment-form-section')?.scrollIntoView({ behavior: 'smooth', block: 'start' });
    }, 80);
  };

  const handleSubscribe = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!selectedPlan) return;
    setSubmitting(true); setMsg('');
    try {
      const res = await fetch('/api/auth/subscribe', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json', 'X-Tenant-Token': tenantToken },
        body: JSON.stringify({ plan_id: selectedPlan.id, ...payForm, amount: parseFloat(payForm.amount) }),
      });
      const data = await res.json();
      if (data.success) { setMsg('✅ ' + data.message); setSelectedPlan(null); }
      else setMsg('❌ ' + data.error);
    } catch { setMsg('❌ Network error'); } finally { setSubmitting(false); }
  };

  const STATUS_INFO: Record<string, { label: string; color: string; bg: string; icon: string }> = {
    trial: { label: 'Free Trial', color: '#2563eb', bg: '#eff6ff', icon: '🎯' },
    trial_expired: { label: 'Trial Ended', color: '#dc2626', bg: '#fef2f2', icon: '⏰' },
    pending: { label: 'Pending', color: '#d97706', bg: '#fffbeb', icon: '⏳' },
    active: { label: 'Active', color: '#059669', bg: '#f0fdf4', icon: '✅' },
    expired: { label: 'Expired', color: '#dc2626', bg: '#fef2f2', icon: '❌' },
    suspended: { label: 'Suspended', color: '#64748b', bg: '#f8fafc', icon: '🚫' },
  };

  const status = myTenant?.subscription_status || 'trial';
  const statusInfo = STATUS_INFO[status] || STATUS_INFO.trial;
  const expiresAt = myTenant?.subscription_expires_at;
  const remaining = expiresAt ? daysRemaining(expiresAt) : null;
  const pmIcons: Record<string, string> = { bkash: '📱 bKash', nagad: '📱 Nagad', rocket: '📱 Rocket', bank: '🏦 Bank Transfer' };
  const pmColors: Record<string, string> = { bkash: '#ec407a', nagad: '#f97316', rocket: '#7c3aed', bank: '#2563eb' };
  const enabledPm = paymentMethods?.enabled || {};
  const availableMethods = (['bkash', 'nagad', 'rocket', 'bank'] as const).filter(
    m => enabledPm[m] !== false && paymentMethods[m]
  );

  if (loading) return <div className="flex items-center justify-center py-20"><div className="text-slate-500 dark:text-slate-400 animate-pulse">Loading plan info...</div></div>;

  return (
    <div className="w-full space-y-6 animate-fade-in-up pb-32 md:pb-8">
      <div>
        <h2 className="text-4xl font-black flex items-center gap-3 text-black">📦 My Plan</h2>
        <p className="text-slate-800 mt-2 font-medium">আপনার subscription status এবং plan দেখুন।</p>
      </div>

      {/* ── Renewal Alert (≤7 days) ── */}
      {status === 'active' && remaining !== null && remaining <= 7 && (
        <div className="flex items-start gap-4 bg-amber-50 border-2 border-amber-300 rounded-3xl p-5">
          <span className="text-3xl">⚠️</span>
          <div className="flex-1">
            <p className="font-black text-amber-800 text-base">Plan মেয়াদ শেষ হতে <span className="text-red-600">{remaining} দিন</span> বাকি!</p>
            <p className="text-amber-700 text-sm mt-1">Renew না করলে store বন্ধ হয়ে যাবে। এখনই নিচে থেকে plan select করুন।</p>
          </div>
          <button onClick={() => document.getElementById('plan-section')?.scrollIntoView({ behavior: 'smooth' })}
            className="px-4 py-2 bg-amber-500 text-white rounded-2xl font-black text-xs hover:bg-amber-600 transition whitespace-nowrap">
            Renew করুন ↓
          </button>
        </div>
      )}

      {/* ── Expired Alert ── */}
      {(status === 'expired' || status === 'trial_expired') && (
        <div className="flex items-start gap-4 bg-red-50 border-2 border-red-300 rounded-3xl p-5">
          <span className="text-3xl">🚫</span>
          <div>
            <p className="font-black text-red-800 text-base">{status === 'trial_expired' ? 'Free Trial শেষ!' : 'Plan মেয়াদ শেষ!'}</p>
            <p className="text-red-700 text-sm mt-1">নিচে থেকে একটি plan select করুন।</p>
          </div>
        </div>
      )}

      {/* ── Current Status ── */}
      <div className="rounded-3xl p-6 border" style={{ background: statusInfo.bg, borderColor: statusInfo.color + '30' }}>
        <div className="flex items-center gap-4">
          <div className="text-4xl">{statusInfo.icon}</div>
          <div className="flex-1">
            <div className="flex items-center gap-3 flex-wrap">
              <h3 className="font-black text-xl text-black">{myTenant?.business_name || 'আপনার Business'}</h3>
              <span className="text-xs font-black px-3 py-1 rounded-full" style={{ background: statusInfo.color, color: '#fff' }}>{statusInfo.label}</span>
            </div>
            {expiresAt && status === 'active' && (
              <p className="text-sm mt-1 font-bold text-black">
                মেয়াদ শেষ: {new Date(expiresAt).toLocaleDateString('bn-BD')}
                {remaining !== null && <span className="ml-2 font-black text-black">({remaining} দিন বাকি)</span>}
              </p>
            )}
            {status === 'pending' && <p className="text-sm mt-1 text-amber-600 font-bold">Payment verify হচ্ছে। Approve হলে activate হবে।</p>}
            {status === 'trial' && (
              <p className="text-sm mt-1 text-blue-600 font-bold">
                {myTenant?.trial_days_remaining != null ? `Free Trial চলছে — ${myTenant.trial_days_remaining} দিন বাকি।` : 'Free Trial mode চলছে।'}
              </p>
            )}
            {mySub && <p className="text-xs mt-2 font-bold text-black">Current Plan: <strong>{mySub.plan_name}</strong> • ৳{mySub.amount}</p>}
          </div>
        </div>
      </div>

      {/* ── Plans ── */}
      <div id="plan-section">
        <h3 className="text-2xl font-black mb-5 text-black">📋 {status === 'active' ? 'Renew / Upgrade Plan' : 'Plan বেছে নিন'}</h3>
        <div className="grid grid-cols-1 md:grid-cols-3 gap-5">
          {plans.map((plan: any) => (
            <div key={plan.id}
              className={`rounded-3xl p-6 border-2 transition-all relative ${plan.is_popular ? 'border-amber-400 shadow-lg shadow-amber-100' :
                selectedPlan?.id === plan.id ? 'border-purple-500 bg-purple-50 shadow-lg' :
                  'bg-white border-slate-200 hover:border-purple-300 hover:shadow-md'
                }`}>
              {plan.is_popular && (
                <div className="absolute -top-3.5 left-1/2 -translate-x-1/2 bg-amber-400 text-white text-[11px] font-black px-4 py-1 rounded-full shadow">
                  ⭐ সবচেয়ে জনপ্রিয়
                </div>
              )}
              <h4 className="font-black text-lg mb-1 mt-2 text-black">{plan.name}</h4>
              <div className="flex flex-col mb-1">
                {plan.regular_price && plan.regular_price > plan.price && (
                  <p className="text-sm font-bold text-slate-500 dark:text-slate-400 line-through decoration-red-500/50 decoration-2 mb-0.5" title="Regular Price">
                    ৳{plan.regular_price?.toLocaleString()}
                  </p>
                )}
                <div className="flex items-center gap-2">
                  <p className="text-3xl font-black text-purple-600">৳{plan.price?.toLocaleString()}</p>
                  {plan.regular_price && plan.regular_price > plan.price && (
                    <span className="bg-green-100 text-green-700 text-[10px] font-black px-2 py-0.5 rounded-full uppercase tracking-wider">Discount!</span>
                  )}
                </div>
              </div>
              <p className="text-xs text-slate-800 font-bold mb-4">{plan.duration_days} দিন</p>
              <ul className="space-y-1.5 mb-5">
                {(() => {
                  const df = Array.isArray(plan.display_features) ? plan.display_features : [];
                  const ff = Array.isArray(plan.features)
                    ? plan.features
                    : (plan.features && typeof plan.features === 'object'
                      ? Object.entries(plan.features).filter(([, v]) => v).map(([k]) => k) : []);
                  return (df.length > 0 ? df : ff);
                })().map((f: string, i: number) => (
                  <li key={i} className="flex items-start gap-1.5 text-xs text-slate-800 font-bold"><span className="text-green-500 mt-0.5">✓</span>{f}</li>
                ))}
              </ul>
              <button
                onClick={() => handleSelectPlan(plan)}
                className={`w-full py-2.5 rounded-2xl font-black text-sm transition-all ${selectedPlan?.id === plan.id ? 'bg-purple-600 text-white' :
                  plan.is_popular ? 'bg-amber-400 text-white hover:bg-amber-500' :
                    'border border-purple-200 text-purple-600 hover:bg-purple-50'
                  }`}>
                {selectedPlan?.id === plan.id ? '✅ Selected' : 'Select Plan'}
              </button>
            </div>
          ))}
        </div>
      </div>

      {/* ── Payment Form ── */}
      {selectedPlan && (
        <form id="payment-form-section" onSubmit={handleSubscribe} className="bg-white rounded-3xl p-8 border shadow-sm space-y-5">
          <h3 className="text-xl font-black text-black">💳 Payment — {selectedPlan.name} (৳{selectedPlan.price?.toLocaleString()})</h3>
          {msg && <div className={`px-4 py-3 rounded-2xl text-sm font-semibold ${msg.startsWith('✅') ? 'bg-green-50 text-green-700' : 'bg-red-50 text-red-600'}`}>{msg}</div>}

          {/* Method selector */}
          {availableMethods.length > 0 ? (
            <div>
              <label className="text-[10px] font-black uppercase text-black block mb-2">Payment Method বেছে নিন</label>
              <div className="grid grid-cols-2 gap-3">
                {availableMethods.map(m => (
                  <button key={m} type="button" onClick={() => setPayForm(prev => ({ ...prev, payment_method: m }))}
                    className={`flex items-center gap-2 px-4 py-3 rounded-2xl border-2 font-black text-sm transition-all text-black ${payForm.payment_method === m ? 'border-purple-500 bg-purple-50' : 'border-slate-200 hover:border-purple-300'
                      }`}>
                    {pmIcons[m]}
                  </button>
                ))}
              </div>
            </div>
          ) : (
            <div className="px-4 py-3 bg-amber-50 border border-amber-100 rounded-2xl text-sm text-amber-900 font-bold">
              ⚠️ Super Admin এখনো payment method configure করেননি।
            </div>
          )}

          {/* Show payment number/details */}
          {payForm.payment_method && paymentMethods[payForm.payment_method] && (
            <div className="p-5 rounded-2xl border-2 mb-4" style={{ borderColor: pmColors[payForm.payment_method] + '40', background: pmColors[payForm.payment_method] + '05' }}>
              {payForm.payment_method === 'bank' ? (
                <>
                  <p className="text-sm font-black uppercase mb-3 flex items-center gap-2" style={{ color: pmColors[payForm.payment_method] }}>
                    🏦 Bank Account Details
                  </p>
                  <div className="bg-white p-4 rounded-xl shadow-sm border border-slate-100 whitespace-pre-wrap font-mono text-sm mb-2">
                    {paymentMethods[payForm.payment_method]}
                  </div>
                  <button type="button" onClick={() => {
                    const btn = document.getElementById('copy-bank');
                    if (btn) { btn.innerText = '✅ Copied!'; setTimeout(() => btn.innerText = '📋 Copy Bank Details', 2000); }
                    navigator.clipboard.writeText(paymentMethods[payForm.payment_method]);
                  }}
                    id="copy-bank"
                    className="text-xs font-bold px-4 py-2 rounded-lg bg-white border text-slate-600 hover:text-slate-800 transition-all shadow-sm active:scale-95">
                    📋 Copy Bank Details
                  </button>
                </>
              ) : (
                <div className="space-y-4">
                  <p className="text-sm font-black flex items-center gap-2 mb-4 border-b pb-3" style={{ borderColor: pmColors[payForm.payment_method] + '20', color: pmColors[payForm.payment_method] }}>
                    {pmIcons[payForm.payment_method]} {payForm.payment_method.toUpperCase()} Payment Guide
                  </p>

                  <ol className="space-y-4 text-sm text-slate-700 font-medium">
                    <li className="flex items-start gap-3">
                      <span className="flex-shrink-0 w-6 h-6 rounded-full bg-slate-100 flex items-center justify-center font-black text-xs text-slate-500">1</span>
                      <span>আপনার <strong style={{ color: pmColors[payForm.payment_method] }}>{payForm.payment_method.toUpperCase()}</strong> মোবাইল অ্যাপে বা USSD মেনুতে যান।</span>
                    </li>
                    <li className="flex items-start gap-3">
                      <span className="flex-shrink-0 w-6 h-6 rounded-full bg-slate-100 flex items-center justify-center font-black text-xs text-slate-500">2</span>
                      <span><strong>Send Money</strong> -এ ক্লিক করুন। (Payment অপশন ও প্রযোজ্য হতে পারে মার্চেন্ট নাম্বারের ক্ষেত্রে)।</span>
                    </li>
                    <li className="flex items-start gap-3">
                      <span className="flex-shrink-0 w-6 h-6 rounded-full bg-slate-100 flex items-center justify-center font-black text-xs text-slate-500">3</span>
                      <div className="flex-1">
                        <span className="block mb-2">প্রাপক নম্বর হিসেবে এই নম্বরটি লিখুনঃ</span>
                        <div className="flex items-center justify-between bg-white px-4 py-2.5 rounded-xl border border-slate-200">
                          <code className="font-mono font-black text-lg" style={{ color: pmColors[payForm.payment_method] }}>{paymentMethods[payForm.payment_method]}</code>
                          <button type="button" onClick={() => {
                            const btn = document.getElementById('copy-num');
                            if (btn) { btn.innerText = '✅ Copied'; setTimeout(() => btn.innerText = '📋 Copy', 2000); }
                            navigator.clipboard.writeText(paymentMethods[payForm.payment_method]);
                          }}
                            id="copy-num"
                            className="bg-slate-100 hover:bg-slate-200 text-slate-600 text-xs font-black px-3 py-1.5 rounded-lg transition-all active:scale-95">
                            📋 Copy
                          </button>
                        </div>
                      </div>
                    </li>
                    <li className="flex items-start gap-3">
                      <span className="flex-shrink-0 w-6 h-6 rounded-full bg-slate-100 flex items-center justify-center font-black text-xs text-slate-500">4</span>
                      <div className="flex-1">
                        <span className="block mb-2">টাকার পরিমাণঃ</span>
                        <div className="flex items-center justify-between bg-white px-4 py-2.5 rounded-xl border border-slate-200">
                          <span className="font-black text-lg">৳ {selectedPlan.price?.toLocaleString()}</span>
                          <button type="button" onClick={() => {
                            const btn = document.getElementById('copy-amt');
                            if (btn) { btn.innerText = '✅ Copied'; setTimeout(() => btn.innerText = '📋 Copy', 2000); }
                            navigator.clipboard.writeText(String(selectedPlan.price));
                          }}
                            id="copy-amt"
                            className="bg-slate-100 hover:bg-slate-200 text-slate-600 text-xs font-black px-3 py-1.5 rounded-lg transition-all active:scale-95">
                            📋 Copy
                          </button>
                        </div>
                      </div>
                    </li>
                    <li className="flex items-start gap-3">
                      <span className="flex-shrink-0 w-6 h-6 rounded-full bg-slate-100 flex items-center justify-center font-black text-xs text-slate-500">5</span>
                      <span>নিশ্চিত করতে এখন আপনার পিন লিখুন।</span>
                    </li>
                    <li className="flex items-start gap-3">
                      <span className="flex-shrink-0 w-6 h-6 rounded-full bg-slate-100 flex items-center justify-center font-black text-xs text-slate-500">6</span>
                      <span>এখন নিচের বক্সে আপনার <strong>Transaction ID</strong> দিন এবং Submit Payment বাটনে ক্লিক করুন!</span>
                    </li>
                  </ol>
                </div>
              )}
            </div>
          )}

          <div className="grid grid-cols-2 gap-4">
            <div>
              <label className="text-[10px] font-black uppercase text-black block mb-1.5">আপনার Number</label>
              <input value={payForm.payment_number} onChange={e => setPayForm({ ...payForm, payment_number: e.target.value })}
                placeholder="01XXXXXXXXX" className="w-full px-4 py-3 bg-slate-50 rounded-2xl border text-sm outline-none focus:border-purple-400 font-bold text-black" />
            </div>
            <div>
              <label className="text-[10px] font-black uppercase text-black block mb-1.5">Transaction ID *</label>
              <input required value={payForm.transaction_id} onChange={e => setPayForm({ ...payForm, transaction_id: e.target.value })}
                placeholder="TrxID দিন" className="w-full px-4 py-3 bg-slate-50 rounded-2xl border text-sm outline-none focus:border-purple-400 font-bold text-black" />
            </div>
            <div className="col-span-2">
              <label className="text-[10px] font-black uppercase text-black block mb-1.5">Amount (৳) *</label>
              <input required type="number" value={payForm.amount} onChange={e => setPayForm({ ...payForm, amount: e.target.value })}
                className="w-full px-4 py-3 bg-slate-50 rounded-2xl border text-sm outline-none focus:border-purple-400 font-black text-lg text-black" />
            </div>
          </div>

          <div>
            <label className="text-[10px] font-black uppercase text-black block mb-1.5">Screenshot (Optional)</label>
            <input type="file" accept="image/*" onChange={e => {
              const file = e.target.files?.[0];
              if (file) { const r = new FileReader(); r.onload = ev => setPayForm({ ...payForm, screenshot: ev.target?.result as string }); r.readAsDataURL(file); }
            }} className="w-full px-4 py-3 bg-slate-50 rounded-2xl border text-sm font-bold text-black" />
          </div>

          <div className="flex gap-3">
            <button type="button" onClick={() => { setSelectedPlan(null); setMsg(''); }} className="flex-1 py-3.5 border rounded-2xl font-black text-sm hover:bg-slate-50">Cancel</button>
            <button type="submit" disabled={submitting} className="flex-1 py-3.5 bg-purple-600 hover:bg-purple-700 text-white rounded-2xl font-black text-sm disabled:opacity-50">
              {submitting ? '⏳ Sending...' : '📤 Submit Payment'}
            </button>
          </div>
        </form>
      )}
    </div>
  );
}

export default MyPlanTab;
