import { useState, useEffect, useCallback } from 'react';
import Button from '../UI/Button';
import Modal from '../UI/Modal';
import Badge from '../UI/Badge';
import { fetchLists, createList, updateList, deleteList } from '../../utils/api';

// ── List Form ─────────────────────────────────────────────────────────────────
// Free: name, description, colour only. No auto-assign rules (Pro).

const RULE_TYPES = [
  { value: 'country', label: 'Country Code (e.g. US, GB)' },
  { value: 'city',    label: 'City (partial match)' },
  { value: 'region',  label: 'Region / State (partial match)' },
];

function ListForm({ list, isPro, onSave, onCancel }) {
  const upgradeUrl = window.rescueFill?.upgradeUrl || 'https://themefreex.com/rescuefill-pro';

  // Parse existing auto_assign_rules
  const initialRules = (() => {
    if (!isPro) return [];
    const raw = list?.auto_assign_rules;
    if (Array.isArray(raw)) return raw;
    try { return JSON.parse(raw) || []; } catch { return []; }
  })();

  const [form, setForm] = useState({
    name:               list?.name        || '',
    description:        list?.description || '',
    color:              list?.color       || '#6366f1',
    auto_assign_rules:  initialRules,
  });

  const addRule = () =>
    setForm(f => ({ ...f, auto_assign_rules: [...f.auto_assign_rules, { type: 'country', value: '' }] }));

  const removeRule = (idx) =>
    setForm(f => ({ ...f, auto_assign_rules: f.auto_assign_rules.filter((_, i) => i !== idx) }));

  const updateRule = (idx, key, val) =>
    setForm(f => ({
      ...f,
      auto_assign_rules: f.auto_assign_rules.map((r, i) => i === idx ? { ...r, [key]: val } : r),
    }));
  const [saving, setSaving] = useState(false);
  const [error,  setError]  = useState('');

  const handleSubmit = async (e) => {
    e.preventDefault();
    if (!form.name.trim()) { setError('List name is required.'); return; }
    setSaving(true); setError('');
    try {
      const payload = {
        name:        form.name,
        description: form.description,
        color:       form.color,
      };
      if (isPro) payload.auto_assign_rules = form.auto_assign_rules.filter(r => r.value.trim());
      await onSave(payload);
    }
    catch (err) { setError(err.message || 'Error saving list.'); }
    finally { setSaving(false); }
  };

  return (
    <form onSubmit={handleSubmit} className="space-y-6">
      {error && <p className="text-sm text-red-600 bg-red-50 border-2 border-red-200 rounded-xl px-4 py-3 font-medium">{error}</p>}

      <div className="grid grid-cols-1 md:grid-cols-2 gap-5">
        <div>
          <label className="block text-sm font-semibold text-slate-700 mb-2">List Name <span className="text-red-500">*</span></label>
          <input type="text" value={form.name} onChange={e => setForm(f => ({ ...f, name: e.target.value }))}
            className="w-full border-2 border-slate-300 rounded-xl px-4 py-2.5 text-sm outline-none focus:ring-2 focus:ring-indigo-500"
            placeholder="e.g. US Leads, Hot Prospects" required />
        </div>
        <div>
          <label className="block text-sm font-semibold text-slate-700 mb-2">Colour Tag</label>
          <div className="flex items-center gap-3">
            <input type="color" value={form.color} onChange={e => setForm(f => ({ ...f, color: e.target.value }))}
              className="h-11 w-20 cursor-pointer rounded-xl border-2 border-slate-300" />
            <span className="inline-flex items-center gap-2 text-sm text-slate-600">
              <span className="w-4 h-4 rounded-full border border-slate-200" style={{ background: form.color }} />
              {form.color}
            </span>
          </div>
        </div>
      </div>

      <div>
        <label className="block text-sm font-semibold text-slate-700 mb-2">Description</label>
        <textarea value={form.description} onChange={e => setForm(f => ({ ...f, description: e.target.value }))}
          rows={3} className="w-full border-2 border-slate-300 rounded-xl px-4 py-3 text-sm outline-none focus:ring-2 focus:ring-indigo-500 resize-y"
          placeholder="Optional – describe when leads end up in this list" />
      </div>

      {/* Auto-assign rules: Pro only */}
      <div className="bg-slate-50 border border-slate-200 rounded-xl p-4">
        <h4 className="text-sm font-semibold text-slate-800 mb-1 flex items-center gap-2">
          Auto-Assign Rules (Location)
          <span className="text-[9px] font-bold text-amber-600 bg-amber-50 border border-amber-200 px-1.5 py-0.5 rounded">PRO</span>
        </h4>
        <p className="text-xs text-slate-500 mb-3">Leads matching these rules are automatically placed in this list.</p>

        {!isPro ? (
          <p className="text-xs text-amber-700 bg-amber-50 border border-amber-200 rounded-lg px-3 py-2">
            Upgrade to <a href={upgradeUrl} target="_blank" rel="noopener noreferrer" className="font-bold underline">Pro</a> to configure location-based auto-assign rules per list.
          </p>
        ) : (
          <div className="space-y-2">
            {form.auto_assign_rules.map((rule, idx) => (
              <div key={idx} className="flex items-center gap-2">
                <select
                  value={rule.type}
                  onChange={e => updateRule(idx, 'type', e.target.value)}
                  className="border border-slate-300 rounded-lg px-2 py-1.5 text-xs outline-none focus:ring-2 focus:ring-indigo-500 bg-white">
                  {RULE_TYPES.map(t => <option key={t.value} value={t.value}>{t.label}</option>)}
                </select>
                <input
                  type="text"
                  value={rule.value}
                  onChange={e => updateRule(idx, 'value', e.target.value)}
                  placeholder={rule.type === 'country' ? 'US' : rule.type === 'city' ? 'New York' : 'California'}
                  className="flex-1 border border-slate-300 rounded-lg px-2 py-1.5 text-xs outline-none focus:ring-2 focus:ring-indigo-500"
                />
                <button type="button" onClick={() => removeRule(idx)}
                  className="text-red-500 hover:text-red-700 text-xs font-bold px-2 py-1.5 rounded border border-red-200 hover:bg-red-50 transition-colors">
                  ✕
                </button>
              </div>
            ))}
            <button type="button" onClick={addRule}
              className="text-xs font-semibold text-indigo-600 hover:text-indigo-800 border border-indigo-200 rounded-lg px-3 py-1.5 bg-indigo-50 hover:bg-indigo-100 transition-colors">
              + Add Rule
            </button>
            {form.auto_assign_rules.length > 0 && (
              <p className="text-xs text-slate-500 mt-1">Rules are evaluated in order. First match wins. Country codes are case-insensitive (US, GB, DE…).</p>
            )}
          </div>
        )}
      </div>

      <div className="flex gap-3 pt-2">
        <Button type="submit" variant="primary" loading={saving}>{list ? 'Update List' : 'Create List'}</Button>
        <Button type="button" variant="secondary" onClick={onCancel}>Cancel</Button>
      </div>
    </form>
  );
}

// ── Main Component ─────────────────────────────────────────────────────────────

export default function Lists({ isPro }) {
  const [lists,        setLists]        = useState([]);
  const [loading,      setLoading]      = useState(true);
  const [formOpen,     setFormOpen]     = useState(false);
  const [editingList,  setEditingList]  = useState(null);
  const [deleteTarget, setDeleteTarget] = useState(null);
  const [deleting,     setDeleting]     = useState(false);
  const [search,       setSearch]       = useState('');
  const [error,        setError]        = useState('');

  const load = useCallback(() => {
    setLoading(true);
    fetchLists()
      .then(d => setLists(d.data || []))
      .catch(e => setError(e.message))
      .finally(() => setLoading(false));
  }, []);

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

  const handleSave = async (formData) => {
    if (editingList) await updateList(editingList.id, formData);
    else             await createList(formData);
    setFormOpen(false); setEditingList(null); load();
  };

  const handleDelete = async () => {
    if (!deleteTarget) return;
    setDeleting(true);
    try { await deleteList(deleteTarget.id); setDeleteTarget(null); load(); }
    catch (e) { alert(e.message || 'Error deleting list'); }
    finally { setDeleting(false); }
  };

  const filtered = lists.filter(l =>
    !search || l.name.toLowerCase().includes(search.toLowerCase()) || (l.description || '').toLowerCase().includes(search.toLowerCase())
  );

  return (
    <div className="space-y-6 animate-fade-in">
      {/* Header */}
      <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4">
        <div>
          <h2 className="text-3xl font-extrabold text-slate-900">Audience Lists</h2>
          <p className="text-slate-600 text-sm mt-1 font-medium">Organise leads into targeted lists for campaigns.</p>
        </div>
        <div className="flex gap-2">
          <Button variant="primary" onClick={() => { setEditingList(null); setFormOpen(true); }}>+ New List</Button>
        </div>
      </div>

      {(lists.length > 0 || search) && (
        <div className="relative max-w-xs">
          <svg className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-slate-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z" />
          </svg>
          <input type="text" placeholder="Search lists…" value={search} onChange={e => setSearch(e.target.value)}
            className="w-full pl-9 pr-3 py-2 text-sm border border-slate-300 rounded-lg outline-none focus:ring-2 focus:ring-indigo-500" />
        </div>
      )}

      {error && <p className="text-sm text-red-600 bg-red-50 border border-red-200 rounded-lg px-4 py-3">{error}</p>}

      {/* Table */}
      <div className="bg-white rounded-2xl border-2 border-slate-200 overflow-hidden">
        {loading ? (
          <div className="py-16 flex flex-col items-center gap-3 text-slate-500">
            <div className="animate-spin w-8 h-8 border-2 border-indigo-500 border-t-transparent rounded-full" />
            <span className="text-sm">Loading lists…</span>
          </div>
        ) : filtered.length === 0 ? (
          <div style={{ display:'flex', flexDirection:'column', alignItems:'center', justifyContent:'center', padding:'4rem 2rem', textAlign:'center' }}>
            <div style={{ fontSize:'3rem', marginBottom:'0.75rem', lineHeight:1 }}>📋</div>
            <p style={{ fontSize:'1rem', fontWeight:600, color:'#374151', margin:'0 0 0.375rem 0' }}>
              {search ? 'No lists match your search.' : 'No lists created yet.'}
            </p>
            {!search && (
              <button onClick={() => { setEditingList(null); setFormOpen(true); }}
                style={{ marginTop:'0.875rem', color:'#4f46e5', fontSize:'0.875rem', fontWeight:600, background:'none', border:'none', cursor:'pointer' }}>
                Create your first list →
              </button>
            )}
          </div>
        ) : (
          <div className="overflow-x-auto">
            <table className="w-full text-left text-sm" style={{ minWidth:'500px' }}>
              <thead className="bg-slate-50 border-b border-slate-200">
                <tr>
                  <th className="px-5 py-3 font-semibold text-slate-700">List</th>
                  <th className="px-5 py-3 font-semibold text-slate-700">Leads</th>
                  <th className="px-5 py-3 font-semibold text-slate-700 hidden sm:table-cell">Description</th>
                  <th className="px-5 py-3 font-semibold text-slate-700" style={{ textAlign:'right' }}>Actions</th>
                </tr>
              </thead>
              <tbody className="divide-y divide-slate-100">
                {filtered.map(list => (
                  <tr key={list.id} className="hover:bg-slate-50 transition-colors">
                    <td className="px-5 py-4">
                      <div className="flex items-center gap-2.5">
                        <span className="w-3 h-3 rounded-full shrink-0" style={{ background: list.color || '#6366f1' }} />
                        <span className="font-semibold text-slate-900">{list.name}</span>
                      </div>
                    </td>
                    <td className="px-5 py-4">
                      <Badge color="indigo">{list.lead_count || 0}</Badge>
                    </td>
                    <td className="px-5 py-4 hidden sm:table-cell text-slate-500 text-xs">{list.description || '—'}</td>
                    <td className="px-5 py-4" style={{ textAlign:'right' }}>
                      <div className="flex items-center justify-end gap-3">
                        <button onClick={() => { setEditingList(list); setFormOpen(true); }}
                          className="text-xs font-semibold text-slate-600 hover:text-slate-900">Edit</button>
                        <button onClick={() => setDeleteTarget(list)}
                          className="text-xs font-semibold text-red-600 hover:text-red-800">Delete</button>
                      </div>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}
      </div>

      {/* Create / Edit Modal */}
      <Modal isOpen={formOpen} onClose={() => { setFormOpen(false); setEditingList(null); }}
        title={editingList ? `Edit List: ${editingList.name}` : 'Create New List'} size="lg">
        <ListForm list={editingList} isPro={isPro} onSave={handleSave} onCancel={() => { setFormOpen(false); setEditingList(null); }} />
      </Modal>

      {/* Delete Confirm */}
      <Modal isOpen={!!deleteTarget} onClose={() => setDeleteTarget(null)} title="Delete List" size="sm">
        <div className="space-y-4">
          <p className="text-sm text-slate-600">
            Delete <strong>"{deleteTarget?.name}"</strong>? All leads will become unassigned but will not be deleted.
          </p>
          <div className="flex gap-3">
            <Button variant="danger" onClick={handleDelete} loading={deleting}>Delete List</Button>
            <Button variant="secondary" onClick={() => setDeleteTarget(null)}>Cancel</Button>
          </div>
        </div>
      </Modal>
    </div>
  );
}
