/**
 * Funnels page — list view + inline full-screen builder.
 * Pro: shows full list + opens n8n-style canvas builder.
 * Free: shows upsell.
 */
import { useState, useEffect } from 'react';
import ProUpsell from '../UI/ProUpsell';
import Button from '../UI/Button';
import FunnelBuilder from './FunnelBuilder';
import { fetchFunnels, createFunnel, updateFunnel, deleteFunnel, fetchLists } from '../../utils/api';

const HIGHLIGHTS = [
  { icon: '🎯', title: 'Visual Canvas',    desc: 'n8n-style drag-and-drop node builder' },
  { icon: '📧', title: 'Email Nodes',      desc: 'Send personalised emails at any step' },
  { icon: '⏱️', title: 'Delay Nodes',      desc: 'Wait hours, days or weeks between steps' },
  { icon: '🔀', title: 'Condition Nodes',  desc: 'Branch Yes/No based on lead data' },
  { icon: '📋', title: 'List Assignment',  desc: 'Move leads to lists automatically' },
  { icon: '🔗', title: 'Webhook Nodes',    desc: 'Fire HTTP POST to any endpoint' },
];

const STATUS_PILL = {
  active: { cls: 'bg-emerald-100 text-emerald-700 border-emerald-200', dot: '#10b981' },
  draft:  { cls: 'bg-slate-100 text-slate-600 border-slate-200',       dot: '#94a3b8' },
  paused: { cls: 'bg-amber-100 text-amber-700 border-amber-200',       dot: '#f59e0b' },
};

export default function Funnels({ isPro }) {
  if (!isPro) return (
    <ProUpsell
      feature="Drag-Drop Funnel Builder"
      description="Build powerful visual automation workflows with an n8n-style canvas. Connect email, delay, condition, list-assign, and webhook nodes to nurture every abandoned lead."
      highlights={HIGHLIGHTS}
    />
  );

  const [view,       setView]       = useState('list');   // 'list' | 'builder'
  const [funnels,    setFunnels]    = useState([]);
  const [lists,      setLists]      = useState([]);
  const [loading,    setLoading]    = useState(true);
  const [error,      setError]      = useState(null);
  const [editing,    setEditing]    = useState(null);      // funnel being edited/created
  const [showCreate, setShowCreate] = useState(false);
  const [newName,    setNewName]    = useState('');
  const [creating,   setCreating]   = useState(false);
  const [deletingId, setDeletingId] = useState(null);

  const load = async () => {
    try {
      setLoading(true); setError(null);
      const [fr, lr] = await Promise.all([fetchFunnels(), fetchLists()]);
      setFunnels(fr.data || []);
      setLists(lr.data  || []);
    } catch (e) { setError(e.message); }
    finally     { setLoading(false); }
  };

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

  /* ── Create new funnel → open builder immediately ─── */
  const handleCreate = async () => {
    if (!newName.trim()) return;
    setCreating(true);
    try {
      const res = await createFunnel({ name: newName.trim(), status: 'draft', nodes: [], edges: [] });
      const newFunnel = { id: res.id, name: newName.trim(), status: 'draft', nodes: [], edges: [] };
      setFunnels(prev => [newFunnel, ...prev]);
      setNewName(''); setShowCreate(false);
      setEditing(newFunnel);
      setView('builder');
    } catch (e) { alert(e.message); }
    finally     { setCreating(false); }
  };

  /* ── Open existing funnel in builder ─── */
  const openBuilder = (funnel) => {
    setEditing(funnel);
    setView('builder');
  };

  /* ── Save from builder ─── */
  const handleSave = async (payload) => {
    await updateFunnel(editing.id, payload);
    const updated = { ...editing, ...payload };
    setFunnels(prev => prev.map(f => f.id === editing.id ? updated : f));
    setEditing(updated);
  };

  /* ── Back to list ─── */
  const handleBack = () => { setView('list'); setEditing(null); load(); };

  /* ── Toggle active/draft ─── */
  const handleToggle = async (funnel) => {
    const next = funnel.status === 'active' ? 'draft' : 'active';
    try {
      await updateFunnel(funnel.id, { status: next });
      setFunnels(prev => prev.map(f => f.id === funnel.id ? { ...f, status: next } : f));
    } catch (e) { alert(e.message); }
  };

  /* ── Delete ─── */
  const handleDelete = async (id) => {
    if (!confirm('Delete this funnel permanently?')) return;
    setDeletingId(id);
    try {
      await deleteFunnel(id);
      setFunnels(prev => prev.filter(f => f.id !== id));
    } catch (e) { alert(e.message); }
    finally     { setDeletingId(null); }
  };

  /* ══ Builder view (full-screen inside main) ══ */
  if (view === 'builder' && editing) {
    return (
      <FunnelBuilder
        funnel={editing}
        lists={lists}
        onSave={handleSave}
        onBack={handleBack}
      />
    );
  }

  /* ══ List view ══ */
  return (
    <div className="space-y-5">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div>
          <h2 className="text-xl font-bold text-slate-900">Funnel Builder</h2>
          <p className="text-sm text-slate-500 mt-0.5">Visual n8n-style automation for abandoned lead recovery.</p>
        </div>
        <Button variant="primary" onClick={() => setShowCreate(true)}>+ New Funnel</Button>
      </div>

      {/* Create panel */}
      {showCreate && (
        <div className="bg-white border border-slate-200 rounded-xl p-5 space-y-3" style={{ boxShadow: '0 1px 3px rgba(0,0,0,0.06)' }}>
          <h3 className="font-semibold text-slate-900 text-sm">New Funnel</h3>
          <input
            autoFocus
            type="text"
            placeholder="Funnel name (e.g. Abandoned Form Recovery)"
            value={newName}
            onChange={e => setNewName(e.target.value)}
            onKeyDown={e => e.key === 'Enter' && handleCreate()}
            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 className="flex gap-2">
            <Button variant="primary" size="sm" onClick={handleCreate} loading={creating} disabled={!newName.trim()}>
              Create &amp; Open Builder
            </Button>
            <Button variant="secondary" size="sm" onClick={() => { setShowCreate(false); setNewName(''); }}>Cancel</Button>
          </div>
        </div>
      )}

      {/* States */}
      {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 funnels…</p></div>
        </div>
      ) : error ? (
        <div className="bg-red-50 border border-red-200 rounded-xl p-4 text-sm text-red-700">{error}</div>
      ) : funnels.length === 0 ? (
        <div className="bg-white border border-dashed border-slate-300 rounded-xl p-16 text-center">
          <div className="text-5xl mb-4">🎯</div>
          <h3 className="font-bold text-slate-900 mb-1 text-lg">Build your first funnel</h3>
          <p className="text-sm text-slate-500 mb-5 max-w-sm mx-auto">Create a visual automation that fires when leads abandon your forms — send emails, add delays, branch on conditions.</p>
          <Button variant="primary" onClick={() => setShowCreate(true)}>+ Create First Funnel</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)' }}>
          <table className="w-full text-sm">
            <thead>
              <tr className="bg-slate-50 border-b border-slate-200">
                <th className="text-left px-5 py-3 text-xs font-semibold text-slate-500 uppercase tracking-wide">Funnel</th>
                <th className="text-left px-4 py-3 text-xs font-semibold text-slate-500 uppercase tracking-wide">Status</th>
                <th className="text-left px-4 py-3 text-xs font-semibold text-slate-500 uppercase tracking-wide">Nodes</th>
                <th className="text-left px-4 py-3 text-xs font-semibold text-slate-500 uppercase tracking-wide">Edges</th>
                <th className="text-right px-5 py-3 text-xs font-semibold text-slate-500 uppercase tracking-wide">Actions</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-slate-100">
              {funnels.map(funnel => {
                const pill = STATUS_PILL[funnel.status] || STATUS_PILL.draft;
                const nodeCount = Array.isArray(funnel.nodes) ? funnel.nodes.length : 0;
                const edgeCount = Array.isArray(funnel.edges) ? funnel.edges.length : 0;
                return (
                  <tr key={funnel.id} className="hover:bg-slate-50 transition-colors group">
                    <td className="px-5 py-4">
                      <button onClick={() => openBuilder(funnel)} className="text-left group-hover:text-indigo-700 transition-colors">
                        <p className="font-semibold text-slate-900 group-hover:text-indigo-700">{funnel.name}</p>
                        {funnel.description && <p className="text-xs text-slate-500 mt-0.5 line-clamp-1">{funnel.description}</p>}
                      </button>
                    </td>
                    <td className="px-4 py-4">
                      <span className={`inline-flex items-center gap-1.5 px-2.5 py-0.5 rounded-full text-xs font-semibold border ${pill.cls}`}>
                        <span style={{ width: 6, height: 6, borderRadius: '50%', background: pill.dot, display: 'inline-block' }} />
                        {funnel.status}
                      </span>
                    </td>
                    <td className="px-4 py-4 text-slate-600 text-xs">{nodeCount} nodes</td>
                    <td className="px-4 py-4 text-slate-600 text-xs">{edgeCount} edges</td>
                    <td className="px-5 py-4">
                      <div className="flex items-center justify-end gap-2">
                        <button onClick={() => openBuilder(funnel)}
                          className="text-xs font-semibold px-3 py-1.5 rounded-lg bg-indigo-50 border border-indigo-200 text-indigo-700 hover:bg-indigo-100 transition-colors">
                          ✏ Edit
                        </button>
                        <button onClick={() => handleToggle(funnel)}
                          className={`text-xs font-medium px-3 py-1.5 rounded-lg border transition-colors ${
                            funnel.status === 'active'
                              ? 'border-amber-300 text-amber-700 hover:bg-amber-50'
                              : 'border-emerald-300 text-emerald-700 hover:bg-emerald-50'
                          }`}>
                          {funnel.status === 'active' ? 'Pause' : 'Activate'}
                        </button>
                        <button onClick={() => handleDelete(funnel.id)} disabled={deletingId === funnel.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 === funnel.id ? '…' : 'Delete'}
                        </button>
                      </div>
                    </td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </div>
      )}

      {/* Tip */}
      <div className="bg-indigo-50 border border-indigo-200 rounded-xl p-4 text-sm text-indigo-800">
        <strong>How funnels work:</strong> When a lead is marked abandoned, all <em>active</em> funnels with a matching Trigger node will enroll that lead automatically. Execution is driven by WP-Cron.
      </div>
    </div>
  );
}
