import { useState, useEffect } from 'react';
import Button from '../UI/Button';
import { fetchLists, assignLeadList, sendReminder, updateLead, deleteLead } from '../../utils/api';
import { LEAD_STATUS_COLORS } from '../../utils/constants';

export default function LeadModal({ lead, onClose, onUpdate, isPro }) {
  const [lists,        setLists]        = useState([]);
  const [saving,       setSaving]       = useState(false);
  const [selectedList, setSelectedList] = useState(lead.list_id || '');
  const [status,       setStatus]       = useState(lead.status || 'abandoned');
  const [sending,      setSending]      = useState(false);
  const [sent,         setSent]         = useState(false);
  const [deleting,     setDeleting]     = useState(false);
  const [activeTab,    setActiveTab]    = useState('details');

  useEffect(() => {
    fetchLists().then(d => setLists(d.data || [])).catch(() => {});
  }, []);

  const handleAssignList = async () => {
    setSaving(true);
    try {
      await assignLeadList(lead.id, selectedList || null);
      onUpdate();
    } catch (e) {
      alert(e.message || 'Error assigning list');
    } finally {
      setSaving(false);
    }
  };

  const handleStatusChange = async (newStatus) => {
    setStatus(newStatus);
    try {
      await updateLead(lead.id, { status: newStatus });
      onUpdate();
    } catch (e) {
      alert(e.message);
    }
  };

  const handleSendReminder = async () => {
    if (!window.confirm(`Send a recovery email to ${lead.email}?`)) return;
    setSending(true);
    try {
      await sendReminder(lead.id);
      setSent(true);
      setTimeout(() => setSent(false), 3000);
    } catch (e) {
      alert(e.message || 'Error sending reminder');
    } finally {
      setSending(false);
    }
  };

  const handleDelete = async () => {
    if (!window.confirm(`Permanently delete lead "${lead.email}"? This cannot be undone.`)) return;
    setDeleting(true);
    try {
      await deleteLead(lead.id);
      onClose();
      onUpdate();
    } catch (e) {
      alert(e.message);
    } finally {
      setDeleting(false);
    }
  };

  const TABS = [
    { id: 'details',  label: 'Details' },
    { id: 'formdata', label: 'Form Data' },
    { id: 'actions',  label: 'Actions' },
  ];

  const assignedList = lists.find(l => l.id == lead.list_id);

  return (
    <>
      <div className="flex border-b border-slate-100 bg-slate-50">
        {TABS.map(t => (
          <button key={t.id} onClick={() => setActiveTab(t.id)}
            className={`px-5 py-2.5 text-sm font-medium transition-colors ${
              activeTab === t.id ? 'text-indigo-700 border-b-2 border-indigo-500 bg-white -mb-px' : 'text-slate-600 hover:text-slate-900'
            }`}>
            {t.label}
          </button>
        ))}
      </div>

      <div className="p-6 overflow-y-auto flex-1">
        {activeTab === 'details' && (
          <div className="space-y-5">
            <div className="grid grid-cols-2 gap-4">
              {[
                { label: 'Email',         value: lead.email },
                { label: 'Status',        value: lead.status?.charAt(0).toUpperCase() + lead.status?.slice(1) },
                { label: 'Form',          value: lead.form_name || lead.form_id || '—' },
                { label: 'Page URL',      value: lead.page_url ? <a href={lead.page_url} target="_blank" rel="noopener noreferrer" className="text-indigo-600 underline text-xs truncate block max-w-full">{lead.page_url}</a> : '—' },
                { label: 'Country',       value: isPro ? (lead.country_name ? `${lead.country_name} (${lead.country_code})` : '—') : '— (Pro)' },
                { label: 'City / Region', value: isPro ? ([lead.city, lead.region].filter(Boolean).join(', ') || '—') : '— (Pro)' },
                { label: 'IP Address',    value: isPro ? (lead.ip_address || '—') : '— (Pro)' },
                { label: 'Started',       value: lead.started_at ? new Date(lead.started_at).toLocaleString() : '—' },
                { label: 'Last Activity', value: lead.last_activity ? new Date(lead.last_activity).toLocaleString() : '—' },
                { label: 'Recovered At',  value: lead.recovered_at ? new Date(lead.recovered_at).toLocaleString() : '—' },
              ].map(({ label, value }) => (
                <div key={label}>
                  <p className="text-[10px] font-bold text-slate-400 uppercase tracking-widest mb-0.5">{label}</p>
                  <div className="text-sm font-medium text-slate-900 break-words">{value}</div>
                </div>
              ))}
            </div>

            <div className="bg-indigo-50 border border-indigo-100 rounded-xl p-4">
              <h4 className="text-sm font-semibold text-slate-800 mb-3">List Assignment</h4>
              <div className="flex gap-2">
                <select value={selectedList} onChange={e => setSelectedList(e.target.value)}
                  className="flex-1 border border-slate-300 rounded-lg px-3 py-2 text-sm outline-none focus:ring-2 focus:ring-indigo-500">
                  <option value="">— No List —</option>
                  {lists.map(l => (
                    <option key={l.id} value={l.id}>{l.name} ({l.lead_count || 0})</option>
                  ))}
                </select>
                <Button variant="primary" size="sm" onClick={handleAssignList} loading={saving}>
                  Assign
                </Button>
              </div>
            </div>
          </div>
        )}

        {activeTab === 'formdata' && (
          <div className="space-y-3">
            {Object.keys(lead.form_data || {}).length === 0 ? (
              <p className="text-sm text-slate-400 italic text-center py-8">No form data captured.</p>
            ) : (
              <div className="space-y-2">
                {Object.entries(lead.form_data || {}).map(([key, value]) => (
                  <div key={key} className="flex gap-3 bg-slate-50 border border-slate-200 rounded-lg px-4 py-2.5">
                    <span className="text-xs font-semibold text-slate-500 uppercase tracking-wide w-32 flex-shrink-0 mt-0.5">{key}</span>
                    <span className="text-sm text-slate-900 flex-1 break-words">{String(value || '')}</span>
                  </div>
                ))}
              </div>
            )}
          </div>
        )}

        {activeTab === 'actions' && (
          <div className="space-y-4">
            <div className="bg-white border border-slate-200 rounded-xl p-4">
              <h4 className="text-sm font-semibold text-slate-800 mb-3">Change Status</h4>
              <div className="flex flex-wrap gap-2">
                {['active', 'abandoned', 'recovered', 'submitted'].map(s => (
                  <button key={s} onClick={() => handleStatusChange(s)}
                    className={`px-3 py-1.5 rounded-lg text-xs font-semibold border transition-all ${
                      status === s
                        ? 'border-indigo-500 bg-indigo-600 text-white'
                        : 'border-slate-300 text-slate-700 hover:border-indigo-400 hover:bg-indigo-50'
                    }`}>
                    {s.charAt(0).toUpperCase() + s.slice(1)}
                  </button>
                ))}
              </div>
            </div>

            <div className="bg-white border border-slate-200 rounded-xl p-4">
              <h4 className="text-sm font-semibold text-slate-800 mb-1">Send Recovery Email</h4>
              <p className="text-xs text-slate-500 mb-3">Manually trigger a recovery email to this lead.</p>
              <Button variant="secondary" onClick={handleSendReminder} loading={sending}>
                📧 Send Reminder Now
              </Button>
              {sent && <p className="text-xs text-emerald-600 mt-2 font-medium">✓ Reminder sent successfully!</p>}
            </div>

            <div className="bg-red-50 border border-red-200 rounded-xl p-4">
              <h4 className="text-sm font-semibold text-red-900 mb-1">Danger Zone</h4>
              <p className="text-xs text-red-700 mb-3">Permanently delete this lead and all associated data.</p>
              <Button variant="danger" onClick={handleDelete} loading={deleting}>
                🗑 Delete Lead
              </Button>
            </div>
          </div>
        )}
      </div>
    </>
  );
}
