import React, { useState, useEffect } from 'react';
import { Globe, Plus, CheckCircle, RefreshCw, XCircle, AlertCircle, LogIn } from 'lucide-react';

function DomainTab({ tenantToken: initialToken }: { tenantToken: string }) {
  // Live token — may be updated if user logs in inline
  const [tok, setTok] = useState(initialToken || localStorage.getItem('tenant_token') || '');
  const [loginPhone, setLoginPhone] = useState('');
  const [loginPass, setLoginPass] = useState('');
  const [loginLoading, setLoginLoading] = useState(false);
  const [loginErr, setLoginErr] = useState('');

  // Subdomain State
  const [currentSlug, setCurrentSlug] = useState('');
  const [inputSlug, setInputSlug] = useState('');
  const [preview, setPreview] = useState('');
  const [available, setAvailable] = useState<boolean | null>(null);
  const [checking, setChecking] = useState(false);
  const [saving, setSaving] = useState(false);
  const [msg, setMsg] = useState<{ text: string; type: 'success' | 'error' } | null>(null);
  const [isLocked, setIsLocked] = useState(false);

  // Custom Domain State
  const [currentCustomDomain, setCurrentCustomDomain] = useState('');
  const [inputCustomDomain, setInputCustomDomain] = useState('');
  const [savingCustomDomain, setSavingCustomDomain] = useState(false);
  const [cdMsg, setCdMsg] = useState<{ text: string; type: 'success' | 'error' } | null>(null);
  const [ns1, setNs1] = useState('');
  const [ns2, setNs2] = useState('');
  const [ns3, setNs3] = useState('');
  const [ns4, setNs4] = useState('');
  const [ns5, setNs5] = useState('');
  const [ns6, setNs6] = useState('');

  // ── Inline Tenant Login ─────────────────────────────────────────────────────
  const getTenantHeaders = () => ({
    'Content-Type': 'application/json',
    'Authorization': `Bearer ${localStorage.getItem('tenant_token')}`
  });

  const handleTenantLogin = async (e: React.FormEvent) => {
    e.preventDefault();
    setLoginErr(''); setLoginLoading(true);
    try {
      const res = await fetch('/api/auth/login', {
        method: 'POST',
        headers: getTenantHeaders(),
        body: JSON.stringify({ phone: loginPhone.replace(/[^0-9]/g, ''), password: loginPass }),
      });
      const d = await res.json();
      if (d.success) {
        localStorage.setItem('tenant_token', d.token);
        localStorage.setItem('tenant_data', JSON.stringify(d.tenant));
        setTok(d.token);
        setLoginErr('');
      } else {
        setLoginErr(d.error || 'Login ব্যর্থ হয়েছে');
      }
    } catch { setLoginErr('Network error'); }
    finally { setLoginLoading(false); }
  };

  // ── Show login form if no token ─────────────────────────────────────────────
  if (!tok) {
    return (
      <div className="max-w-md space-y-6 animate-fade-in-up">
        <div>
          <h2 className="text-4xl font-black flex items-center gap-3 text-black">🌐 Domain Name</h2>
          <p className="text-purple-600 mt-2 font-bold">Domain set করতে আপনার Store Account-এ login করুন।</p>
        </div>
        <div className="bg-white rounded-3xl p-8 border shadow-sm space-y-5">
          <div className="flex items-center gap-3 p-4 bg-amber-50 border border-amber-100 rounded-2xl">
            <span className="text-2xl">🔐</span>
            <div>
              <p className="font-black text-sm text-black">Store Account দরকার</p>
              <p className="text-xs text-amber-600 mt-0.5 font-bold">আপনার Store-এর ফোন ও পাসওয়ার্ড দিন</p>
            </div>
          </div>
          {loginErr && (
            <div className="px-4 py-3 bg-red-50 border border-red-100 rounded-2xl text-sm text-red-600 font-semibold">
              ❌ {loginErr}
            </div>
          )}
          <form onSubmit={handleTenantLogin} className="space-y-4">
            <div>
              <label className="text-[10px] font-black uppercase text-slate-500 dark:text-slate-400 block mb-1.5">ফোন নম্বর</label>
              <input type="tel" value={loginPhone} onChange={e => setLoginPhone(e.target.value)}
                placeholder="01XXXXXXXXX" required
                className="w-full px-4 py-3 bg-slate-50 rounded-2xl border-2 border-transparent focus:border-purple-500 text-sm font-medium outline-none transition" />
            </div>
            <div>
              <label className="text-[10px] font-black uppercase text-slate-500 dark:text-slate-400 block mb-1.5">পাসওয়ার্ড</label>
              <input type="password" value={loginPass} onChange={e => setLoginPass(e.target.value)}
                placeholder="আপনার password" required
                className="w-full px-4 py-3 bg-slate-50 rounded-2xl border-2 border-transparent focus:border-purple-500 text-sm font-medium outline-none transition" />
            </div>
            <button type="submit" disabled={loginLoading}
              className="w-full py-4 rounded-2xl font-black text-slate-800 dark:text-white text-base transition-all active:scale-95 disabled:opacity-50"
              style={{ background: 'linear-gradient(135deg, #7c3aed, #4f46e5)', boxShadow: '0 8px 25px rgba(124,58,237,0.35)' }}>
              {loginLoading ? '⏳ Login হচ্ছে...' : '🔑 Store Account Login'}
            </button>
          </form>
          <p className="text-xs text-slate-500 dark:text-slate-400 text-center">
            Account নেই? <a href="/" className="text-purple-600 font-black hover:underline">shophyfast.com</a> থেকে তৈরি করুন
          </p>
        </div>
      </div>
    );
  }

  // Load current info
  useEffect(() => {
    if (!tok) return;
    fetch('/api/admin/tenant/me', { headers: { 'X-Tenant-Token': tok } })
      .then(r => r.json())
      .then(d => {
        if (d.data?.business_slug) { 
            setCurrentSlug(d.data.business_slug); 
            setInputSlug(d.data.business_slug); 
        }
        if (d.data?.custom_domain) {
            setCurrentCustomDomain(d.data.custom_domain);
            setInputCustomDomain(d.data.custom_domain);
        }
        setIsLocked(!!d.data?.subdomain_locked);
          if (d.name_server_1) setNs1(d.name_server_1);
          if (d.name_server_2) setNs2(d.name_server_2);
          if (d.name_server_3) setNs3(d.name_server_3);
          if (d.name_server_4) setNs4(d.name_server_4);
          if (d.name_server_5) setNs5(d.name_server_5);
          if (d.name_server_6) setNs6(d.name_server_6);
      })
      .catch(() => { });
  }, [tok]);

  // Real-time slug availability check
  useEffect(() => {
    const raw = inputSlug.trim().toLowerCase().replace(/[^a-z0-9-]/g, '-').replace(/-+/g, '-').replace(/^-|-$/g, '');
    setPreview(raw);
    if (!raw || raw.length < 3) { setAvailable(null); return; }
    if (raw === currentSlug) { setAvailable(true); return; }

    setChecking(true); setAvailable(null);
    const timer = setTimeout(async () => {
      try {
        const res = await fetch(`/api/auth/slug-check?slug=${encodeURIComponent(raw)}`);
        const d = await res.json();
        setAvailable(d.available);
      } catch { setAvailable(null); }
      finally { setChecking(false); }
    }, 500);
    return () => clearTimeout(timer);
  }, [inputSlug, currentSlug]);

  const handleSaveSlug = async () => {
    if (!preview || available === false) return;
    setSaving(true); setMsg(null);
    try {
      const res = await fetch('/api/admin/tenant/update-slug', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json', 'X-Tenant-Token': tok },
        body: JSON.stringify({ custom_slug: preview }),
      });
      const d = await res.json();
      if (d.success) {
        setCurrentSlug(preview);
        setInputSlug(preview);
        setIsLocked(true);
        setMsg({ text: `✅ ${d.message} — ${d.subdomain}`, type: 'success' });
      } else {
        setMsg({ text: `❌ ${d.error}`, type: 'error' });
      }
    } catch { setMsg({ text: '❌ Network error', type: 'error' }); }
    finally { setSaving(false); }
  };

  const handleSaveCustomDomain = async () => {
    if (!inputCustomDomain.trim()) return;
    setSavingCustomDomain(true); setCdMsg(null);
    try {
      const res = await fetch('/api/admin/tenant/update-custom-domain', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json', 'X-Tenant-Token': tok },
        body: JSON.stringify({ custom_domain: inputCustomDomain }),
      });
      const d = await res.json();
      if (d.success) {
        setCurrentCustomDomain(d.custom_domain);
        setInputCustomDomain(d.custom_domain);
        setCdMsg({ text: `✅ ${d.message}`, type: 'success' });
      } else {
        setCdMsg({ text: `❌ ${d.error}`, type: 'error' });
      }
    } catch { setCdMsg({ text: '❌ Network error', type: 'error' }); }
    finally { setSavingCustomDomain(false); }
  };

  const handleRemoveCustomDomain = async () => {
    if (!confirm('আপনি কি নিশ্চিত যে আপনার Custom Domain রিমুভ করতে চান? এর ফলে আপনার Subdomain আবার চালু হয়ে যাবে।')) return;
    setSavingCustomDomain(true); setCdMsg(null);
    try {
      const res = await fetch('/api/admin/tenant/remove-custom-domain', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json', 'X-Tenant-Token': tok },
      });
      const d = await res.json();
      if (d.success) {
        setCurrentCustomDomain('');
        setInputCustomDomain('');
        setCdMsg({ text: `✅ ${d.message}`, type: 'success' });
      } else {
        setCdMsg({ text: `❌ ${d.error}`, type: 'error' });
      }
    } catch { setCdMsg({ text: '❌ Network error', type: 'error' }); }
    finally { setSavingCustomDomain(false); }
  };

  const slugStatus = () => {
    if (checking) return { icon: '⏳', text: 'Checking...', color: '#64748b' };
    if (preview.length < 3) return { icon: '⌨️', text: 'কমপক্ষে ৩ অক্ষর দিন', color: '#94a3b8' };
    if (preview === currentSlug) return { icon: '✅', text: 'এটাই আপনার বর্তমান subdomain', color: '#059669' };
    if (available === true) return { icon: '✅', text: 'Available! এই নাম নেওয়া যাবে', color: '#059669' };
    if (available === false) return { icon: '❌', text: 'এই নাম আগেই নেওয়া হয়েছে', color: '#dc2626' };
    return { icon: '🌐', text: '', color: '#94a3b8' };
  };

  const status = slugStatus();

  return (
    <div className="max-w-full space-y-12 animate-fade-in-up pb-32">
      <div>
        <h2 className="text-4xl font-black flex items-center gap-3 text-black">🌐 Domain Name</h2>
        <p className="text-purple-600 mt-2 font-bold">আপনার store-এর Subdomain এবং Custom Domain সেট করুন।</p>
      </div>

      {/* ─────────────────────────────────────────────────────────────
          SECTION 1: SHOPHYFAST SUBDOMAIN
          ───────────────────────────────────────────────────────────── */}
      <div className="space-y-6">
        <h3 className="text-2xl font-black text-black border-b-2 border-slate-100 pb-2">Shophyfast Subdomain</h3>
        
        {/* Current Domain Card */}
        <div className="bg-gradient-to-br from-purple-50 to-indigo-50 rounded-3xl p-6 border border-purple-100">
          <p className="text-xs font-black uppercase text-purple-600 mb-3">বর্তমান Store URL</p>
          <div className="flex items-center gap-3">
            <div className="w-10 h-10 rounded-2xl bg-purple-100 flex items-center justify-center text-xl">🌐</div>
            <div className="flex-1">
              <p className="font-black text-lg text-black">
                {currentSlug ? (
                  <><span className="text-purple-600">{currentSlug}</span>.shophyfast.com</>
                ) : (
                  <span className="text-slate-600 dark:text-slate-400">Subdomain set করা হয়নি</span>
                )}
              </p>
              {currentSlug && (
                <a href={`http://${currentSlug}.shophyfast.com`} target="_blank" rel="noreferrer"
                  className="text-xs text-purple-400 hover:text-purple-600 hover:underline transition font-bold">
                  Visit store ↗
                </a>
              )}
            </div>
            {isLocked && (
              <div className="flex items-center gap-1.5 px-3 py-1.5 bg-red-50 border border-red-200 rounded-xl">
                <span className="text-sm">🔒</span>
                <span className="text-xs font-black text-red-600">Locked</span>
              </div>
            )}
          </div>
        </div>

        {isLocked ? (
          <div className="bg-amber-50 border border-amber-200 rounded-3xl p-8 space-y-4">
            <div className="flex items-start gap-4">
              <span className="text-3xl">🔒</span>
              <div>
                <p className="font-black text-black text-lg">Subdomain পরিবর্তন করা যাবে না</p>
                <p className="text-amber-700 text-sm mt-1 leading-relaxed font-bold">
                  আপনার store-এর subdomain <strong className="text-black">{currentSlug}.shophyfast.com</strong> একবার সেট করার পর আর পরিবর্তন করা সম্ভব নয়।
                </p>
              </div>
            </div>
            <div className="bg-white rounded-2xl p-4 border border-amber-100">
              <p className="text-xs font-black uppercase text-purple-600 mb-2">আপনার Store Link</p>
              <div className="flex items-center gap-3">
                <code className="flex-1 text-sm font-mono text-purple-700 bg-purple-50 px-4 py-2.5 rounded-xl font-bold">
                  {currentSlug}.shophyfast.com
                </code>
                <button
                  onClick={() => { navigator.clipboard.writeText(`${currentSlug}.shophyfast.com`); }}
                  className="px-4 py-2.5 rounded-xl bg-purple-600 text-white text-xs font-black hover:bg-purple-700 transition"
                >
                  Copy
                </button>
              </div>
            </div>
          </div>
        ) : (
          <div className="bg-white rounded-3xl p-8 border shadow-sm space-y-5">
            <h3 className="text-lg font-black flex items-center gap-2 text-black">✏️ Subdomain সেট করুন <span className="text-xs font-medium text-red-500">(শুধুমাত্র একবার)</span></h3>

            {msg && (
              <div className={`px-4 py-3 rounded-2xl text-sm font-bold ${msg.type === 'success' ? 'bg-green-50 text-green-700 border border-green-100' : 'bg-red-50 text-red-600 border border-red-100'}`}>
                {msg.text}
              </div>
            )}

            <div>
              <label className="text-[10px] font-black uppercase text-black block mb-2">আপনার পছন্দের নাম লিখুন</label>
              <div className="flex items-center rounded-2xl border-2 border-slate-200 focus-within:border-purple-500 transition bg-slate-50 overflow-hidden">
                <div className="px-4 py-3.5 bg-slate-100 border-r border-slate-200 text-slate-500 dark:text-slate-400 text-sm font-mono select-none whitespace-nowrap">
                  🌐
                </div>
                <input
                  value={inputSlug}
                  onChange={e => setInputSlug(e.target.value)}
                  placeholder="your-shop"
                  className="flex-1 px-4 py-3.5 bg-transparent text-sm font-bold font-mono outline-none text-black"
                />
                <div className="px-4 py-3.5 bg-slate-100 border-l border-slate-200 text-slate-600 font-bold text-sm font-mono select-none whitespace-nowrap">
                  .shophyfast.com
                </div>
              </div>

              <div className="mt-3 flex items-center gap-2">
                <span style={{ color: status.color }} className="text-base">{status.icon}</span>
                <div>
                  {preview && (
                    <p className="text-sm font-black text-slate-700">
                      <span className="text-purple-600">{preview}</span>.shophyfast.com
                    </p>
                  )}
                  {status.text && <p className="text-xs mt-0.5 font-bold" style={{ color: status.color }}>{status.text}</p>}
                </div>
              </div>
            </div>

            <button
              onClick={handleSaveSlug}
              disabled={saving || available === false || checking || preview.length < 3 || preview === currentSlug}
              className="w-full py-4 rounded-2xl font-black text-slate-800 dark:text-white text-base transition-all active:scale-95 disabled:opacity-40 disabled:cursor-not-allowed flex items-center justify-center gap-2"
              style={{ background: 'linear-gradient(135deg, #7c3aed, #4f46e5)', boxShadow: '0 8px 25px rgba(124,58,237,0.35)' }}>
              {saving ? '⏳ Saving...' : '🔒 Subdomain চিরতরে সেট করুন'}
            </button>
          </div>
        )}
      </div>


      {/* ─────────────────────────────────────────────────────────────
          SECTION 2: OWN CUSTOM DOMAIN
          ───────────────────────────────────────────────────────────── */}
      <div className="space-y-6 pt-6 border-t-2 border-slate-100">
        <h3 className="text-2xl font-black text-black border-b-2 border-slate-100 pb-2 flex items-center gap-3">
          ⭐ Your Custom Domain
        </h3>
        
        {/* Current Custom Domain Card */}
        {currentCustomDomain && (
          <div className="bg-gradient-to-br from-green-50 to-emerald-50 rounded-3xl p-6 border border-green-100">
            <p className="text-xs font-black uppercase text-green-600 mb-3">আপনার নিজস্ব Domain</p>
            <div className="flex items-center gap-3">
              <div className="w-10 h-10 rounded-2xl bg-green-100 flex items-center justify-center text-xl">🚀</div>
              <div className="flex-1">
                <p className="font-black text-lg text-black">
                  {currentCustomDomain}
                </p>
                <a href={`http://${currentCustomDomain}`} target="_blank" rel="noreferrer"
                  className="text-xs text-green-600 hover:text-green-700 hover:underline transition font-bold">
                  Visit custom domain ↗
                </a>
              </div>
              <div className="flex flex-col gap-2 items-end">
                <div className="flex items-center gap-1.5 px-3 py-1.5 bg-green-100 border border-green-200 rounded-xl">
                  <span className="text-sm">✅</span>
                  <span className="text-xs font-black text-green-700">Active</span>
                </div>
                <button
                  onClick={handleRemoveCustomDomain}
                  className="px-3 py-1.5 bg-red-50 text-red-600 border border-red-200 rounded-xl text-xs font-black hover:bg-red-100 transition"
                >
                  🗑️ Remove
                </button>
              </div>
            </div>
          </div>
        )}

        <div className="bg-white rounded-3xl p-8 border shadow-sm space-y-5">
          <h3 className="text-lg font-black flex items-center gap-2 text-black">✏️ আপনার নিজস্ব ডোমেইন যোগ করুন</h3>
          <p className="text-xs text-slate-500 font-bold mb-4">যেমন: mart.com বা myshop.com.bd</p>

          {cdMsg && (
            <div className={`px-4 py-3 rounded-2xl text-sm font-bold ${cdMsg.type === 'success' ? 'bg-green-50 text-green-700 border border-green-100' : 'bg-red-50 text-red-600 border border-red-100'}`}>
              {cdMsg.text}
            </div>
          )}

          <div>
            <label className="text-[10px] font-black uppercase text-black block mb-2">আপনার Domain Name</label>
            <input
              value={inputCustomDomain}
              onChange={e => setInputCustomDomain(e.target.value)}
              placeholder="e.g. mart.com"
              className="w-full px-4 py-3.5 bg-slate-50 rounded-2xl border-2 border-slate-200 focus:border-purple-500 text-sm font-bold font-mono outline-none text-black transition"
            />
          </div>

          <button
            onClick={handleSaveCustomDomain}
            disabled={savingCustomDomain || !inputCustomDomain.trim()}
            className="w-full py-4 rounded-2xl font-black text-white text-base transition-all active:scale-95 disabled:opacity-40 disabled:cursor-not-allowed flex items-center justify-center gap-2"
            style={{ background: 'linear-gradient(135deg, #0ea5e9, #2563eb)', boxShadow: '0 8px 25px rgba(14,165,233,0.35)' }}>
            {savingCustomDomain ? '⏳ Saving...' : '💾 Custom Domain Save করুন'}
          </button>
        </div>

        {/* DNS Configuration Section */}
        <div className="bg-amber-50 border border-amber-200 rounded-3xl p-8 space-y-4">
          <div className="flex items-start gap-4">
            <span className="text-3xl">⚙️</span>
            <div>
              <p className="font-black text-black text-lg">Name Server Configuration</p>
              <p className="text-amber-800 text-sm mt-1 leading-relaxed font-bold">
                আপনার ডোমেইনটি আমাদের প্ল্যাটফর্মের সাথে কাজ করার জন্য, আপনি যেখানে ডোমেইন কিনেছেন (যেমন Namecheap, GoDaddy) সেখানে গিয়ে ডোমেইনের Name Server হিসেবে নিচের Name Server গুলো বসাতে হবে।
              </p>
              <p className="text-amber-700 text-xs mt-2 leading-relaxed font-bold">
                * Name Server আপডেট হওয়ার পর ডোমেইনটি চালু হতে ২৪-৪৮ ঘণ্টা সময় লাগতে পারে।
              </p>
            </div>
          </div>
          <div className="bg-white rounded-2xl p-5 border border-amber-100 space-y-3 mt-4">
            {[ns1, ns2, ns3, ns4, ns5, ns6].filter(ns => ns && ns.trim() !== '').map((ns, idx) => (
              <div key={idx}>
                <p className="text-[10px] font-black uppercase text-purple-600 mb-1">Name Server {idx + 1}</p>
                <div className="flex items-center gap-3">
                  <code className="flex-1 text-sm font-mono text-purple-700 bg-purple-50 px-4 py-2.5 rounded-xl font-bold">
                    {ns}
                  </code>
                  <button
                    onClick={() => { navigator.clipboard.writeText(ns); }}
                    className="px-4 py-2.5 rounded-xl bg-purple-100 text-purple-700 text-xs font-black hover:bg-purple-200 transition"
                  >
                    Copy
                  </button>
                </div>
              </div>
            ))}
          </div>
        </div>
      </div>
    </div>
  );
}

export default DomainTab;
