import React, { useState } from 'react';
import { Save, RefreshCw, MessageSquare, Bot, Key, AlignLeft } from 'lucide-react';

export default function MessengerAIAgentPanel({ settings, products, showToast }: {
  settings: any;
  products: any[];
  showToast: (m: string, t?: 'success' | 'error') => void;
}) {
  const [fbToken, setFbToken] = React.useState(settings?.messengerAiFbToken || '');
  const [description, setDescription] = React.useState(settings?.messengerAiDescription || '');
  const [verifyToken, setVerifyToken] = React.useState(settings?.messengerAiFbVerifyToken || 'shophyfast_verify');
  const [aiEnabled, setAiEnabled] = React.useState(settings?.messengerAiEnabled !== false);
  const [saving, setSaving] = React.useState(false);
  const [showToken, setShowToken] = React.useState(false);

  const facebookWebhookUrl = `${window.location.origin}/api/messenger-webhook`;

  const autoKnowledgeBase = React.useMemo(() => {
    const productLines = products.slice(0, 20).map((p: any) =>
      `- ${p.nameBangla || p.name}: ৳${p.price}${p.sizes?.length ? ` (${p.sizes.join(', ')})` : ''}`
    ).join('\n');
    const contact = [
      settings?.phone ? `Phone: ${settings.phone}` : '',
      settings?.email ? `Email: ${settings.email}` : '',
      settings?.address ? `Address: ${settings.address}` : '',
    ].filter(Boolean).join('\n');
    return `=== পণ্য তালিকা ===\n${productLines || 'No products found.'}\n\n=== যোগাযোগ ===\n${contact || 'No contact info found.'}`;
  }, [products, settings]);

  const handleSave = async () => {
    setSaving(true);
    try {
      const _tok = localStorage.getItem('tenant_token') || '';
      const res = await fetch('/api/admin/settings', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Accept': 'application/json',
          ...(_tok ? { 'X-Tenant-Token': _tok } : {}),
        },
        body: JSON.stringify({
          messengerAiFbToken: fbToken,
          messengerAiDescription: description,
          messengerAiFbVerifyToken: verifyToken,
          messengerAiEnabled: aiEnabled,
        }),
      });
      const data = await res.json();
      if (!data.success) throw new Error(data.error);
      showToast('✅ Messenger AI সেটিংস সেভ হয়েছে!', 'success');
    } catch (e: any) {
      showToast('Error: ' + e.message, 'error');
    } finally {
      setSaving(false);
    }
  };

  return (
    <div className="animate-fade-in-up space-y-6">
      {/* Header */}
      <div className="bg-gradient-to-br from-slate-900 to-indigo-950 rounded-[32px] p-8 text-white relative overflow-hidden">
        <div className="absolute -right-12 -top-12 w-52 h-52 bg-purple-500/10 rounded-full pointer-events-none" />
        <div className="absolute -right-4 -bottom-8 w-32 h-32 bg-indigo-500/10 rounded-full pointer-events-none" />
        <div className="relative z-10">
          <div className="flex items-center gap-4 mb-3">
            <div className="w-14 h-14 rounded-2xl flex items-center justify-center" style={{ background: 'rgba(139,92,246,0.25)', border: '1px solid rgba(139,92,246,0.4)' }}>
              <svg width="26" height="26" viewBox="0 0 24 24" fill="none" stroke="#c4b5fd" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z" /></svg>
            </div>
            <div>
              <h2 className="text-2xl font-black text-white">Messenger AI Agent</h2>
              <p className="text-purple-300 text-sm font-medium">সম্পূর্ণ built-in PHP — কোনো third-party tool দরকার নেই</p>
            </div>
          </div>
          <div className="flex flex-wrap gap-2 mt-4">
            {['✅ Built-in PHP', '🤖 ubaidi Powered', '📦 Auto Order', '💬 বাংলা Reply', '🔄 State Machine'].map(f => (
              <span key={f} className="text-[11px] font-bold px-3 py-1 rounded-full" style={{ background: 'rgba(139,92,246,0.2)', border: '1px solid rgba(139,92,246,0.3)', color: '#c4b5fd' }}>{f}</span>
            ))}
          </div>
        </div>
      </div>

      {/* Facebook Webhook Setup */}
      <div className="bg-white rounded-[28px] border-2 border-purple-200 shadow-sm p-7">
        <div className="flex items-center gap-3 mb-6">
          <div className="w-10 h-10 bg-purple-50 text-purple-600 rounded-xl flex items-center justify-center">
            <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"><path d="M18 2h-3a5 5 0 0 0-5 5v3H7v4h3v8h4v-8h3l1-4h-4V7a1 1 0 0 1 1-1h3z" /></svg>
          </div>
          <div>
            <h3 className="text-base font-black text-slate-800">Facebook Webhook Setup</h3>
            <p className="text-xs text-slate-500">Meta Developer Console-এ নিচের তথ্য দিন — সরাসরি website থেকেই কাজ করবে</p>
          </div>
          <span className="ml-auto text-[10px] font-black px-2.5 py-1 rounded-full" style={{ background: 'rgba(139,92,246,0.1)', color: '#7c3aed', border: '1px solid rgba(139,92,246,0.2)' }}>BUILT-IN ⚡</span>
        </div>
        <div className="space-y-4">
          <div>
            <p className="text-[10px] font-black uppercase tracking-widest text-slate-500 mb-2">📡 Callback URL — Meta-তে দিন</p>
            <div className="flex items-center gap-2 bg-purple-50 border border-purple-200 rounded-xl px-4 py-3">
              <span className="text-xs font-mono text-purple-800 flex-1 break-all">{facebookWebhookUrl}</span>
              <button
                onClick={() => { navigator.clipboard.writeText(facebookWebhookUrl); showToast('✅ Callback URL Copied!', 'success'); }}
                className="shrink-0 px-3 py-1.5 rounded-lg text-xs font-bold bg-purple-200 text-purple-800 hover:bg-purple-300 transition-all"
              >📋 Copy</button>
            </div>
          </div>
          <div>
            <p className="text-[10px] font-black uppercase tracking-widest text-slate-500 mb-2">🔑 Verify Token — Meta-তে দিন</p>
            <div className="flex gap-2">
              <input
                value={verifyToken}
                onChange={e => setVerifyToken(e.target.value)}
                placeholder="shophyfast_verify"
                className="flex-1 border border-slate-200 rounded-xl px-4 py-3 text-sm font-mono font-bold outline-none focus:ring-2 focus:ring-purple-400 text-slate-800"
              />
              <button
                onClick={() => { navigator.clipboard.writeText(verifyToken); showToast('✅ Verify Token Copied!', 'success'); }}
                className="px-4 py-3 rounded-xl text-xs font-bold bg-slate-100 text-slate-600 hover:bg-slate-200 transition-all"
              >📋</button>
            </div>
          </div>
          <div className="bg-amber-50 border border-amber-100 rounded-xl p-4">
            <p className="text-[11px] font-black text-amber-700 mb-2">📋 Meta Console-এ এই Subscribed Fields যোগ করুন:</p>
            <div className="flex flex-wrap gap-2">
              {['messages', 'messaging_postbacks', 'messaging_optins'].map(f => (
                <span key={f} className="text-[10px] font-black px-2.5 py-1 bg-amber-100 text-amber-800 rounded-lg">{f}</span>
              ))}
            </div>
          </div>
        </div>
      </div>

      {/* Facebook Token — full width */}
      <div className="bg-white rounded-[28px] border border-slate-200 shadow-sm p-7">
        <div className="flex items-center gap-3 mb-5">
          <div className="w-10 h-10 bg-blue-50 text-blue-700 rounded-xl flex items-center justify-center font-black text-xl">f</div>
          <div>
            <h3 className="text-base font-black text-slate-800">Facebook Page Access Token</h3>
            <p className="text-xs text-slate-500">Messenger-এ reply পাঠানোর জন্য</p>
          </div>
        </div>
        <div className="relative">
          <input
            type={showToken ? 'text' : 'password'}
            value={fbToken}
            onChange={e => setFbToken(e.target.value)}
            placeholder="EAAxxxxxxxx..."
            className="w-full border border-slate-200 rounded-xl px-4 py-3 text-sm font-mono pr-12 outline-none focus:ring-2 focus:ring-blue-400 text-slate-800"
          />
          <button onClick={() => setShowToken(!showToken)} className="absolute right-3 top-1/2 -translate-y-1/2 text-slate-500 dark:text-slate-400 hover:text-slate-600 text-xs">
            {showToken ? '🙈' : '👁️'}
          </button>
        </div>
        <p className="text-[11px] text-slate-500 dark:text-slate-400 mt-2 font-medium">Meta Developer Console → Graph Explorer</p>
      </div>

      {/* Auto Knowledge Base */}
      <div className="bg-white rounded-[28px] border border-slate-200 shadow-sm p-7">
        <div className="flex items-center gap-3 mb-5">
          <div className="w-10 h-10 bg-amber-50 text-amber-600 rounded-xl flex items-center justify-center">
            <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"><path d="M2 3h6a4 4 0 0 1 4 4v14a3 3 0 0 0-3-3H2z" /><path d="M22 3h-6a4 4 0 0 0-4 4v14a3 3 0 0 1 3-3h7z" /></svg>
          </div>
          <div>
            <h3 className="text-base font-black text-slate-800">Auto Knowledge Base</h3>
            <p className="text-xs text-slate-500">Database থেকে live fetch — admin-কে কিছু করতে হবে না</p>
          </div>
          <span className="ml-auto text-[10px] font-black px-2.5 py-1 rounded-full bg-green-50 text-green-600 border border-green-100">AUTO ✓</span>
        </div>
        <div className="bg-slate-50 border border-slate-200 rounded-xl p-4 mb-4 max-h-48 overflow-y-auto">
          <pre className="text-[11px] text-slate-600 font-mono whitespace-pre-wrap leading-relaxed">{autoKnowledgeBase}</pre>
        </div>
        <label className="text-xs font-black uppercase tracking-widest text-slate-500 mb-2 block">অতিরিক্ত বিবরণ (ঐচ্ছিক)</label>
        <textarea
          value={description}
          onChange={e => setDescription(e.target.value)}
          rows={4}
          placeholder="ডেলিভারি নিয়ম, অফার, বিশেষ তথ্য — AI এগুলো customer-কে জানাবে..."
          className="w-full border border-slate-200 rounded-xl px-4 py-3 text-sm outline-none focus:ring-2 focus:ring-purple-400 text-slate-700 resize-none"
        />
      </div>

      {/* How It Works */}
      <div className="bg-gradient-to-br from-indigo-50 to-purple-50 border border-purple-100 rounded-[28px] p-7">
        <h3 className="text-base font-black text-slate-800 mb-4">⚙️ কীভাবে কাজ করে</h3>
        <ol className="space-y-3">
          {[
            { step: '১', title: 'Meta-তে Webhook Register করুন', desc: 'Callback URL ও Verify Token উপরে থেকে copy করে Meta Developer Console → Webhooks-এ দিন' },
            { step: '২', title: 'Facebook Page Access Token দিন', desc: 'উপরের form-এ FB Token পূরণ করে সেটিংস সেভ করুন। AI (OpenRouter) আমাদের নিজস্ব VPS-এ চলে — আলাদা কোনো API key লাগবে না' },
            { step: '৩', title: 'AI নিজেই সব করবে', desc: 'Customer message করলে Ubaidi AI বাংলায় reply দেবে। অর্ডার করতে চাইলে নাম → ফোন → ঠিকানা নিয়ে database-এ order তৈরি করবে' },
            { step: '৪', title: 'Order দেখুন Admin-এ', desc: 'সব Messenger order, Orders Management-এ "Messenger" source হিসেবে দেখা যাবে' },
          ].map(({ step, title, desc }) => (
            <li key={step} className="flex gap-4">
              <div className="w-7 h-7 rounded-full bg-purple-600 text-white flex items-center justify-center text-xs font-black flex-shrink-0 mt-0.5">{step}</div>
              <div>
                <p className="text-sm font-black text-slate-800">{title}</p>
                <p className="text-xs text-slate-500 font-medium mt-0.5">{desc}</p>
              </div>
            </li>
          ))}
        </ol>
      </div>

      {/* Enable Toggle */}
      <div className="flex items-center justify-between bg-white rounded-[28px] border border-slate-200 shadow-sm px-7 py-5">
        <div className="flex items-center gap-3">
          <div className="w-10 h-10 bg-slate-50 rounded-xl flex items-center justify-center text-xl">{aiEnabled ? '🟢' : '🔴'}</div>
          <div>
            <p className="text-sm font-black text-slate-800">AI Agent {aiEnabled ? 'চালু আছে' : 'বন্ধ আছে'}</p>
            <p className="text-xs text-slate-500">বন্ধ করলে AI reply দেবে না</p>
          </div>
        </div>
        <button
          onClick={() => setAiEnabled(!aiEnabled)}
          className={`relative w-14 h-7 rounded-full transition-all duration-300 ${aiEnabled ? 'bg-emerald-500' : 'bg-slate-300'}`}
        >
          <div className={`absolute top-1 w-5 h-5 bg-white rounded-full shadow transition-all duration-300 ${aiEnabled ? 'left-8' : 'left-1'}`} />
        </button>
      </div>

      {/* Save Button */}
      <div className="flex justify-end">
        <button
          onClick={handleSave}
          disabled={saving}
          className="flex items-center gap-3 px-8 py-3.5 rounded-2xl font-black text-sm text-slate-800 dark:text-white transition-all active:scale-95 disabled:opacity-60 shadow-lg"
          style={{ background: 'linear-gradient(135deg, #7c3aed, #4f46e5)', boxShadow: '0 8px 24px rgba(124,58,237,0.3)' }}
        >
          {saving
            ? (<><svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" className="animate-spin"><path d="M21 12a9 9 0 1 1-6.219-8.56" /></svg> সেভ হচ্ছে...</>)
            : (<><svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"><path d="M19 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11l5 5v11a2 2 0 0 1-2 2z" /><polyline points="17 21 17 13 7 13 7 21" /><polyline points="7 3 7 8 15 8" /></svg> সেটিংস সেভ করুন</>)
          }
        </button>
      </div>

    </div>
  );
}

// ── DomainTab ─────────────────────────────────────────────────────────────────
