import { useState, useEffect } from 'react';
import ProUpsell from '../UI/ProUpsell';
import Button from '../UI/Button';
import { fetchWebhooks, createWebhook, updateWebhook, deleteWebhook, testWebhook } from '../../utils/api';

const HIGHLIGHTS = [
  { icon: '🔗', title: 'Zapier / Make / n8n', desc: 'Connect to 5,000+ apps with no-code automation' },
  { icon: '🌐', title: 'Custom Webhooks', desc: 'HMAC-SHA256 signed payloads to any HTTP endpoint' },
  { icon: '💬', title: 'Slack Alerts', desc: 'Instant notifications when leads abandon' },
  { icon: '📊', title: 'CRM Push', desc: 'HubSpot, Salesforce, ActiveCampaign and more' },
];

const ALL_EVENTS = [
  { id: 'lead.created',   label: 'Lead Created' },
  { id: 'lead.abandoned', label: 'Lead Abandoned' },
  { id: 'lead.recovered', label: 'Lead Recovered' },
  { id: 'lead.submitted', label: 'Lead Submitted' },
  { id: 'email.sent',     label: 'Email Sent' },
  { id: 'list.assigned',  label: 'List Assigned' },
];

// 10+ integration app directory
const APP_DIRECTORY = [
  {
    name: 'Zapier',
    icon: '⚡',
    color: '#FF4A00',
    bg: '#fff5f0',
    category: 'Automation',
    desc: 'Connect RescueFill to 6,000+ apps. Use "Webhooks by Zapier → Catch Hook" as trigger.',
    useCase: 'Trigger CRM updates, Slack messages, Google Sheets rows on every abandoned lead.',
    docs: '#',
  },
  {
    name: 'Make (Integromat)',
    icon: '🔄',
    color: '#6D00CC',
    bg: '#f5f0ff',
    category: 'Automation',
    desc: 'Visual automation with powerful branching. Use "Webhooks → Custom webhook".',
    useCase: 'Build multi-step scenarios: email → wait → SMS → CRM → Slack.',
    docs: '#',
  },
  {
    name: 'n8n',
    icon: '🔀',
    color: '#FF6D5A',
    bg: '#fff5f3',
    category: 'Automation',
    desc: 'Self-hosted automation platform. Paste webhook URL from n8n Webhook node.',
    useCase: 'Run on your own server — full data privacy, unlimited executions.',
    docs: '#',
  },
  {
    name: 'HubSpot',
    icon: '🧡',
    color: '#FF7A59',
    bg: '#fff6f3',
    category: 'CRM',
    desc: 'Create contacts, deals, and activities directly from abandoned lead events.',
    useCase: 'Auto-create contact in HubSpot, set lifecycle stage to "Lead", trigger sequences.',
    docs: '#',
  },
  {
    name: 'Salesforce',
    icon: '☁️',
    color: '#00A1E0',
    bg: '#f0faff',
    category: 'CRM',
    desc: 'Push leads as Salesforce Leads or Contacts with full field mapping.',
    useCase: 'Sync abandoned leads to Salesforce pipeline with source tracking.',
    docs: '#',
  },
  {
    name: 'ActiveCampaign',
    icon: '📬',
    color: '#356AE6',
    bg: '#f0f4ff',
    category: 'Email CRM',
    desc: 'Add subscribers, update custom fields, and trigger automations on lead events.',
    useCase: 'Enroll leads in AC automation sequences for multi-step nurture.',
    docs: '#',
  },
  {
    name: 'Slack',
    icon: '💬',
    color: '#4A154B',
    bg: '#fdf5ff',
    category: 'Notifications',
    desc: 'Post rich messages to any Slack channel when leads abandon forms.',
    useCase: 'Alert your sales team in #leads channel with lead name, email, and form.',
    docs: '#',
  },
  {
    name: 'Mailchimp',
    icon: '🐒',
    color: '#FFE01B',
    bg: '#fffef0',
    category: 'Email Marketing',
    desc: 'Add abandoned leads to Mailchimp audiences and trigger automations.',
    useCase: 'Start abandoned form email series via Mailchimp Customer Journeys.',
    docs: '#',
  },
  {
    name: 'Google Sheets',
    icon: '📊',
    color: '#34A853',
    bg: '#f0fbf5',
    category: 'Data',
    desc: 'Log every abandoned lead event to a Google Sheet for analysis.',
    useCase: 'Build custom dashboards, track recovery rates, share with team.',
    docs: '#',
  },
  {
    name: 'Airtable',
    icon: '🗄️',
    color: '#FCB400',
    bg: '#fff9e6',
    category: 'Data',
    desc: 'Push lead data to Airtable bases as structured records.',
    useCase: 'Build a visual CRM or ops board with your abandoned lead data.',
    docs: '#',
  },
  {
    name: 'Twilio / SMS',
    icon: '📱',
    color: '#F22F46',
    bg: '#fff0f1',
    category: 'SMS',
    desc: 'Send SMS alerts to your team or trigger Twilio flows on lead events.',
    useCase: 'Instant SMS to your sales rep when a high-value lead abandons.',
    docs: '#',
  },
  {
    name: 'Custom Webhook',
    icon: '🔗',
    color: '#1e293b',
    bg: '#f8fafc',
    category: 'Custom',
    desc: 'POST JSON to any endpoint — your own backend, microservice, or serverless function.',
    useCase: 'HMAC-SHA256 signed payload. Retry on failure. Full delivery log.',
    docs: '#',
  },
];

const CATEGORIES = ['All', ...Array.from(new Set(APP_DIRECTORY.map(a => a.category)))];

export default function Integrations({ isPro }) {
  if (!isPro) {
    return (
      <ProUpsell
        feature="Integrations & Webhooks"
        description="Push recovered leads to Zapier, Make, n8n, HubSpot, Salesforce, Slack, or any custom URL. HMAC-SHA256 signed payloads with retry logic and delivery logs."
        highlights={HIGHLIGHTS}
      />
    );
  }

  const [tab,        setTab]        = useState('webhooks'); // 'webhooks' | 'apps'
  const [webhooks,   setWebhooks]   = useState([]);
  const [loading,    setLoading]    = useState(true);
  const [error,      setError]      = useState(null);
  const [showCreate, setShowCreate] = useState(false);
  const [newUrl,     setNewUrl]     = useState('');
  const [newEvents,  setNewEvents]  = useState(ALL_EVENTS.map(e => e.id));
  const [creating,   setCreating]   = useState(false);
  const [testingId,  setTestingId]  = useState(null);
  const [deletingId, setDeletingId] = useState(null);
  const [testResult, setTestResult] = useState({});
  const [catFilter,  setCatFilter]  = useState('All');

  const load = async () => {
    try {
      setLoading(true);
      setError(null);
      const res = await fetchWebhooks();
      const data = res.data || {};
      setWebhooks(Array.isArray(data) ? data : Object.values(data));
    } catch (e) {
      setError(e.message);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => { load(); }, []);

  const toggleEvent = (id) => {
    setNewEvents(prev => prev.includes(id) ? prev.filter(e => e !== id) : [...prev, id]);
  };

  const handleCreate = async () => {
    if (!newUrl.trim()) { alert('Enter a webhook URL.'); return; }
    setCreating(true);
    try {
      await createWebhook({ url: newUrl.trim(), events: newEvents });
      setNewUrl('');
      setNewEvents(ALL_EVENTS.map(e => e.id));
      setShowCreate(false);
      load();
    } catch (e) {
      alert(e.message);
    } finally {
      setCreating(false);
    }
  };

  const handleToggle = async (webhook) => {
    const next = !webhook.active;
    try {
      await updateWebhook(webhook.id, { active: next });
      setWebhooks(prev => prev.map(w => w.id === webhook.id ? { ...w, active: next } : w));
    } catch (e) {
      alert(e.message);
    }
  };

  const handleTest = async (id) => {
    setTestingId(id);
    setTestResult(prev => ({ ...prev, [id]: null }));
    try {
      await testWebhook(id);
      setTestResult(prev => ({ ...prev, [id]: 'success' }));
    } catch (e) {
      setTestResult(prev => ({ ...prev, [id]: e.message }));
    } finally {
      setTestingId(null);
    }
  };

  const handleDelete = async (id) => {
    if (!confirm('Delete this webhook?')) return;
    setDeletingId(id);
    try {
      await deleteWebhook(id);
      setWebhooks(prev => prev.filter(w => w.id !== id));
    } catch (e) {
      alert(e.message);
    } finally {
      setDeletingId(null);
    }
  };

  const filteredApps = catFilter === 'All'
    ? APP_DIRECTORY
    : APP_DIRECTORY.filter(a => a.category === catFilter);

  return (
    <div className="space-y-5">

      {/* Header */}
      <div className="flex items-center justify-between">
        <div>
          <h2 className="text-xl font-bold text-slate-900">Integrations & Webhooks</h2>
          <p className="text-sm text-slate-500 mt-0.5">Connect RescueFill to Zapier, Make, HubSpot, Slack, and 12+ more apps.</p>
        </div>
        {tab === 'webhooks' && (
          <Button variant="primary" onClick={() => setShowCreate(true)}>+ Add Webhook</Button>
        )}
      </div>

      {/* Tab bar */}
      <div className="flex gap-1 bg-slate-100 p-1 rounded-xl w-fit">
        {[['webhooks', '🔗 My Webhooks'], ['apps', '🌐 App Directory']].map(([id, label]) => (
          <button key={id} onClick={() => setTab(id)}
            className={`px-4 py-1.5 rounded-lg text-sm font-semibold transition-all ${
              tab === id
                ? 'bg-white text-slate-900 shadow-sm'
                : 'text-slate-500 hover:text-slate-700'
            }`}>
            {label}
          </button>
        ))}
      </div>

      {/* ══ Tab: My Webhooks ══ */}
      {tab === 'webhooks' && (
        <>
          {showCreate && (
            <div className="bg-white border border-slate-200 rounded-xl p-5 space-y-4" style={{ boxShadow: '0 1px 3px rgba(0,0,0,0.06)' }}>
              <h3 className="font-semibold text-slate-900">New Webhook</h3>
              <div>
                <label className="text-xs font-semibold text-slate-600 mb-1 block">Endpoint URL *</label>
                <input
                  type="url"
                  placeholder="https://hooks.zapier.com/hooks/catch/..."
                  value={newUrl}
                  onChange={e => setNewUrl(e.target.value)}
                  className="w-full border border-slate-300 rounded-lg px-3 py-2 text-sm outline-none focus:ring-2 focus:ring-indigo-500"
                />
              </div>
              <div>
                <label className="text-xs font-semibold text-slate-600 mb-2 block">Events to Fire</label>
                <div className="grid grid-cols-2 sm:grid-cols-3 gap-2">
                  {ALL_EVENTS.map(ev => (
                    <label key={ev.id} className="flex items-center gap-2 text-sm text-slate-700 cursor-pointer select-none">
                      <input
                        type="checkbox"
                        checked={newEvents.includes(ev.id)}
                        onChange={() => toggleEvent(ev.id)}
                        className="rounded border-slate-300 text-indigo-600 focus:ring-indigo-500"
                      />
                      {ev.label}
                    </label>
                  ))}
                </div>
              </div>
              <div className="flex gap-2">
                <Button variant="primary" size="sm" onClick={handleCreate} loading={creating} disabled={!newUrl.trim()}>
                  Save Webhook
                </Button>
                <Button variant="secondary" size="sm" onClick={() => { setShowCreate(false); setNewUrl(''); setNewEvents(ALL_EVENTS.map(e => e.id)); }}>
                  Cancel
                </Button>
              </div>
            </div>
          )}

          {loading ? (
            <div className="flex items-center justify-center py-16">
              <div className="flex flex-col items-center gap-3">
                <div className="rf-spinner" />
                <p className="text-sm text-slate-500">Loading webhooks…</p>
              </div>
            </div>
          ) : error ? (
            <div className="bg-red-50 border border-red-200 rounded-xl p-4 text-sm text-red-700">{error}</div>
          ) : webhooks.length === 0 ? (
            <div className="bg-white border border-slate-200 rounded-xl p-12 text-center">
              <div className="text-4xl mb-3">🔗</div>
              <h3 className="font-semibold text-slate-900 mb-1">No webhooks yet</h3>
              <p className="text-sm text-slate-500 mb-4">Add a webhook to push lead events to Zapier, Make, or any HTTP endpoint.</p>
              <Button variant="primary" onClick={() => setShowCreate(true)}>+ Add First Webhook</Button>
            </div>
          ) : (
            <div className="bg-white border border-slate-200 rounded-xl overflow-hidden" style={{ boxShadow: '0 1px 3px rgba(0,0,0,0.06)' }}>
              <div className="divide-y divide-slate-100">
                {webhooks.map(webhook => (
                  <div key={webhook.id} className="p-5">
                    <div className="flex items-start justify-between gap-4">
                      <div className="min-w-0 flex-1">
                        <div className="flex items-center gap-2 mb-1">
                          <span className={`w-2 h-2 rounded-full flex-shrink-0 ${webhook.active ? 'bg-emerald-500' : 'bg-slate-300'}`} />
                          <p className="text-sm font-medium text-slate-900 truncate">{webhook.url}</p>
                        </div>
                        <p className="text-xs text-slate-500 ml-4">
                          {Array.isArray(webhook.events) ? webhook.events.join(' · ') : 'All events'}
                        </p>
                      </div>
                      <div className="flex items-center gap-2 flex-shrink-0">
                        <button
                          onClick={() => handleToggle(webhook)}
                          className={`text-xs font-medium px-3 py-1.5 rounded-lg border transition-colors ${
                            webhook.active
                              ? 'border-slate-300 text-slate-600 hover:bg-slate-50'
                              : 'border-emerald-300 text-emerald-700 hover:bg-emerald-50'
                          }`}>
                          {webhook.active ? 'Disable' : 'Enable'}
                        </button>
                        <button
                          onClick={() => handleTest(webhook.id)}
                          disabled={testingId === webhook.id}
                          className="text-xs font-medium px-3 py-1.5 rounded-lg border border-blue-200 text-blue-700 hover:bg-blue-50 transition-colors disabled:opacity-50">
                          {testingId === webhook.id ? 'Testing…' : 'Test'}
                        </button>
                        <button
                          onClick={() => handleDelete(webhook.id)}
                          disabled={deletingId === webhook.id}
                          className="text-xs font-medium px-3 py-1.5 rounded-lg border border-red-200 text-red-600 hover:bg-red-50 transition-colors disabled:opacity-50">
                          {deletingId === webhook.id ? '…' : 'Delete'}
                        </button>
                      </div>
                    </div>
                    {testResult[webhook.id] !== undefined && testResult[webhook.id] !== null && (
                      <p className={`text-xs mt-2 ml-4 font-medium ${testResult[webhook.id] === 'success' ? 'text-emerald-600' : 'text-red-600'}`}>
                        {testResult[webhook.id] === 'success' ? '✓ Test payload sent successfully' : `✗ ${testResult[webhook.id]}`}
                      </p>
                    )}
                  </div>
                ))}
              </div>
            </div>
          )}

          <div className="bg-amber-50 border border-amber-200 rounded-xl p-5">
            <h3 className="text-sm font-semibold text-amber-900 mb-2">📋 Webhook Payload Format</h3>
            <pre className="text-xs text-amber-800 bg-amber-100 rounded-lg p-3 overflow-x-auto leading-relaxed">{`{
  "event": "lead.abandoned",
  "timestamp": "2024-01-15T10:30:00Z",
  "lead": {
    "id": 42,
    "email": "jane@example.com",
    "name": "Jane Smith",
    "form_id": "contact-form",
    "status": "abandoned",
    "city": "New York",
    "country_code": "US"
  }
}`}</pre>
            <p className="text-xs text-amber-700 mt-2">All payloads include an <code className="bg-amber-200 px-1 rounded">X-RescueFill-Signature</code> header for HMAC-SHA256 verification.</p>
          </div>
        </>
      )}

      {/* ══ Tab: App Directory ══ */}
      {tab === 'apps' && (
        <div className="space-y-5">

          {/* Category filter */}
          <div className="flex flex-wrap gap-2">
            {CATEGORIES.map(cat => (
              <button key={cat} onClick={() => setCatFilter(cat)}
                className={`px-3 py-1 text-xs font-semibold rounded-full border transition-colors ${
                  catFilter === cat
                    ? 'bg-indigo-600 text-white border-indigo-600'
                    : 'bg-white text-slate-600 border-slate-200 hover:border-indigo-300 hover:text-indigo-700'
                }`}>
                {cat}
              </button>
            ))}
          </div>

          {/* App grid */}
          <div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-4">
            {filteredApps.map(app => (
              <div key={app.name} className="bg-white border border-slate-200 rounded-xl p-5 hover:border-indigo-300 hover:shadow-md transition-all">
                <div className="flex items-start gap-3 mb-3">
                  <div style={{ background: app.bg, color: app.color, border: `1.5px solid ${app.color}33` }}
                    className="w-10 h-10 rounded-xl flex items-center justify-center text-xl flex-shrink-0">
                    {app.icon}
                  </div>
                  <div className="min-w-0 flex-1">
                    <div className="flex items-center gap-2">
                      <h4 className="text-sm font-bold text-slate-900">{app.name}</h4>
                      <span className="text-[10px] font-semibold px-1.5 py-0.5 rounded-full bg-slate-100 text-slate-500">
                        {app.category}
                      </span>
                    </div>
                    <p className="text-xs text-slate-500 mt-0.5 leading-relaxed">{app.desc}</p>
                  </div>
                </div>
                <div className="bg-slate-50 rounded-lg p-3 mb-3">
                  <p className="text-xs text-slate-600 leading-relaxed">
                    <span className="font-semibold text-slate-700">Use case:</span> {app.useCase}
                  </p>
                </div>
                <button
                  onClick={() => { setTab('webhooks'); setShowCreate(true); }}
                  style={{ borderColor: app.color + '55', color: app.color, background: app.bg }}
                  className="w-full text-xs font-semibold py-1.5 rounded-lg border transition-opacity hover:opacity-80">
                  + Add {app.name} Webhook
                </button>
              </div>
            ))}
          </div>

          {/* How it works */}
          <div className="bg-indigo-50 border border-indigo-200 rounded-xl p-5">
            <h3 className="text-sm font-semibold text-indigo-900 mb-3">🔌 How Integrations Work</h3>
            <div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
              {[
                { step: '1', title: 'Add Webhook URL', desc: 'Get the webhook URL from your app (Zapier, Make, n8n, etc.) and paste it in My Webhooks.' },
                { step: '2', title: 'Choose Events', desc: 'Select which lead events fire the webhook — abandoned, recovered, submitted, etc.' },
                { step: '3', title: 'Receive Lead Data', desc: 'RescueFill POSTs signed JSON payloads. Map fields in your automation to complete the integration.' },
              ].map(({ step, title, desc }) => (
                <div key={step} className="flex gap-3">
                  <div className="w-6 h-6 bg-indigo-600 text-white rounded-full flex items-center justify-center text-xs font-bold flex-shrink-0 mt-0.5">
                    {step}
                  </div>
                  <div>
                    <p className="text-xs font-bold text-indigo-900 mb-0.5">{title}</p>
                    <p className="text-xs text-indigo-700 leading-relaxed">{desc}</p>
                  </div>
                </div>
              ))}
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
