/* global React, Icons */
const { useState, useMemo } = React;

const FLOW_DEFAULT_STATUSES = [
  { id: 'leads',       label: 'Leads',       color: '#4cc9f0', iconId: 'bookmark' },
  { id: 'requested',   label: 'Requested',   color: '#a855f7', iconId: 'mail' },
  { id: 'followed_up', label: 'Followed Up', color: '#f59e0b', iconId: 'arrow' },
  { id: 'to_buy',      label: 'To Buy',      color: '#22d3ee', iconId: 'tag' },
  { id: 'in_transit',  label: 'In Transit',  color: '#10b981', iconId: 'package' },
  { id: 'done',        label: 'Done',        color: '#84cc16', iconId: 'check' },
];

const STATUS_ICON_MAP = {
  bookmark: Icons.bookmark, mail: Icons.mail,     arrow: Icons.arrow,
  tag: Icons.tag,           package: Icons.package, check: Icons.check,
  bolt: Icons.bolt,         trend: Icons.trend,   cart: Icons.cart,
  calendar: Icons.calendar, video: Icons.video,   dollar: Icons.dollar,
  star: Icons.star,         folder: Icons.folder, link: Icons.link,
  users: Icons.users,       edit: Icons.edit,     eye: Icons.eye,
  list: Icons.list,         chart: Icons.chart,   diamond: Icons.diamond,
  zap: Icons.zap,           download: Icons.download, upload: Icons.upload,
  filter: Icons.filter,     copy: Icons.copy,     reset: Icons.reset,
  trash: Icons.trash,       kanban: Icons.kanban, sort: Icons.sort,
};
const getStatusIcon = (iconId) => STATUS_ICON_MAP[iconId] || Icons.tag;

// All 30 unique icons available for stage customization
const STAGE_ICON_OPTIONS = [
  'bookmark','mail','arrow','tag','package','check',
  'bolt','trend','cart','calendar','video','dollar',
  'star','folder','link','users','edit','eye',
  'list','chart','diamond','zap','download','upload',
  'filter','copy','reset','trash','kanban','sort',
];

// 30-color palette shared with list color picker
const STAGE_COLORS = [
  '#4cc9f0','#a855f7','#f59e0b','#22d3ee','#10b981','#84cc16',
  '#f43f5e','#3b82f6','#f97316','#6366f1','#ec4899','#eab308',
  '#14b8a6','#8b5cf6','#ef4444','#7c5cff','#22c55e','#fb7185',
  '#60a5fa','#fbbf24','#34d399','#c084fc','#38bdf8','#f87171',
  '#a3e635','#e879f9','#2dd4bf','#facc15','#4ade80','#06b6d4',
];

const FlowPage = ({ leads, setLeads, setPage }) => {
  const [dragId, setDragId] = useState(null);
  const [dragOverCol, setDragOverCol] = useState(null);
  const [addingStatus, setAddingStatus] = useState(false);
  const [newStatusName, setNewStatusName] = useState('');
  const [newStatusColor, setNewStatusColor] = useState(STAGE_COLORS[0]);
  const [newStatusIconId, setNewStatusIconId] = useState('tag');

  const activeStatuses = leads.flowStatuses || FLOW_DEFAULT_STATUSES;
  const defaultStatusId = activeStatuses[0]?.id;

  // ── Status CRUD ────────────────────────────────────────────────────────────
  const setStatuses = (statuses) => {
    setLeads(prev => ({ ...prev, flowStatuses: statuses }));
  };

  const addStatus = () => {
    const name = newStatusName.trim();
    if (!name) return;
    const id = 'st_' + Date.now();
    setStatuses([...activeStatuses, { id, label: name, color: newStatusColor, iconId: newStatusIconId }]);
    setNewStatusName('');
    setNewStatusColor(STAGE_COLORS[activeStatuses.length % STAGE_COLORS.length]);
    setNewStatusIconId('tag');
    setAddingStatus(false);
  };

  const deleteStatus = (statusId) => {
    if (activeStatuses.length <= 1) return; // can't delete last
    const fallbackId = activeStatuses.find(s => s.id !== statusId)?.id || defaultStatusId;
    // Move any lists in the deleted status to the fallback
    setLeads(prev => ({
      ...prev,
      flowStatuses: prev.flowStatuses
        ? prev.flowStatuses.filter(s => s.id !== statusId)
        : FLOW_DEFAULT_STATUSES.filter(s => s.id !== statusId),
      lists: prev.lists.map(l =>
        (l.status || defaultStatusId) === statusId ? { ...l, status: fallbackId } : l
      ),
    }));
  };

  const setListStatus = (listId, status) => {
    setLeads(prev => ({ ...prev, lists: prev.lists.map(l => l.id === listId ? { ...l, status } : l) }));
  };

  // ── Derived data ───────────────────────────────────────────────────────────
  const listStats = useMemo(() => {
    const stats = {};
    leads.lists.forEach(l => {
      const prods = leads.products.filter(p => (p.lists || []).includes(l.id));
      stats[l.id] = { count: prods.length };
    });
    return stats;
  }, [leads.products, leads.lists]);

  const listsForStatus = (statusId) =>
    leads.lists.filter(l => l.id !== 'inbox' && (l.status || defaultStatusId) === statusId);

  const handleCardClick = (listId) => {
    localStorage.setItem('aip_active_list', listId);
    setPage('leads');
  };

  // ── Render ─────────────────────────────────────────────────────────────────
  return (
    <div className="page" style={{ padding: '24px 28px 16px', display: 'flex', flexDirection: 'column', minHeight: 0, overflow: 'hidden' }}>
      {/* Header */}
      <div className="page-header" style={{ flexShrink: 0 }}>
        <div className="page-title-block">
          <h1>Flow</h1>
          <div className="subtitle">Drag lists between stages to track your review pipeline</div>
        </div>
      </div>

      {/* Board — fills remaining width, scrolls if very narrow */}
      <div style={{
        display: 'flex', gap: 12, flex: 1, overflow: 'auto',
        alignItems: 'flex-start', paddingBottom: 8,
      }}>
        {activeStatuses.map(status => {
          const lists = listsForStatus(status.id);
          const isOver = dragOverCol === status.id && dragId !== null;
          const StatusIcon = getStatusIcon(status.iconId);

          return (
            <div
              key={status.id}
              style={{ flex: '1 1 0', minWidth: 155, display: 'flex', flexDirection: 'column', gap: 8 }}
              onDragOver={e => { e.preventDefault(); setDragOverCol(status.id); }}
              onDragLeave={e => { if (!e.currentTarget.contains(e.relatedTarget)) setDragOverCol(null); }}
              onDrop={() => {
                if (dragId) setListStatus(dragId, status.id);
                setDragId(null);
                setDragOverCol(null);
              }}
            >
              {/* Column header */}
              <div style={{
                display: 'flex', alignItems: 'center', gap: 8,
                padding: '9px 12px 9px 14px',
                background: 'var(--bg-2)',
                borderRadius: 8,
                borderLeft: `3px solid ${status.color}`,
                transition: 'background 0.15s',
                ...(isOver ? { background: `color-mix(in srgb, var(--bg-2) 80%, ${status.color} 20%)` } : {}),
              }}>
                <span style={{ color: status.color, display: 'flex', alignItems: 'center', flexShrink: 0 }}>
                  <StatusIcon size={13}/>
                </span>
                <span style={{ fontSize: 12, fontWeight: 600, color: 'var(--text-1)', flex: 1, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
                  {status.label}
                </span>
                <span style={{ fontSize: 11, color: 'var(--text-3)', fontWeight: 600, flexShrink: 0,
                  background: 'var(--bg-1)', borderRadius: 10, padding: '1px 6px' }}>
                  {lists.length}
                </span>
                {activeStatuses.length > 1 && (
                  <button
                    onClick={() => deleteStatus(status.id)}
                    title="Remove stage"
                    style={{
                      display: 'flex', alignItems: 'center', justifyContent: 'center',
                      width: 16, height: 16, flexShrink: 0,
                      border: 'none', background: 'transparent', cursor: 'pointer',
                      color: 'var(--text-3)', padding: 0, borderRadius: 3,
                      opacity: 0.6,
                    }}
                    onMouseEnter={e => { e.currentTarget.style.color = 'var(--danger)'; e.currentTarget.style.opacity = '1'; }}
                    onMouseLeave={e => { e.currentTarget.style.color = 'var(--text-3)'; e.currentTarget.style.opacity = '0.6'; }}
                  >
                    <Icons.close size={9}/>
                  </button>
                )}
              </div>

              {/* Cards */}
              <div style={{
                display: 'flex', flexDirection: 'column', gap: 7,
                minHeight: 80,
                borderRadius: 8,
                border: isOver ? `2px dashed ${status.color}60` : '2px dashed transparent',
                padding: isOver ? 4 : 0,
                transition: 'border-color 0.15s, padding 0.15s',
              }}>
                {lists.map(list => {
                  const s = listStats[list.id] || {};
                  const isDragging = dragId === list.id;
                  return (
                    <div
                      key={list.id}
                      draggable
                      onDragStart={() => setDragId(list.id)}
                      onDragEnd={() => { setDragId(null); setDragOverCol(null); }}
                      onClick={() => handleCardClick(list.id)}
                      style={{
                        padding: '11px 13px', borderRadius: 8,
                        background: 'var(--bg-elev)',
                        border: '1px solid var(--line)',
                        cursor: 'grab', userSelect: 'none',
                        opacity: isDragging ? 0.3 : 1,
                        transition: 'opacity 0.15s, border-color 0.15s, box-shadow 0.15s',
                        display: 'flex', flexDirection: 'column', gap: 7,
                      }}
                      onMouseEnter={e => {
                        if (!isDragging) {
                          e.currentTarget.style.borderColor = list.color + '70';
                          e.currentTarget.style.boxShadow = `0 4px 14px -4px rgba(0,0,0,0.45)`;
                        }
                      }}
                      onMouseLeave={e => {
                        e.currentTarget.style.borderColor = 'var(--line)';
                        e.currentTarget.style.boxShadow = 'none';
                      }}
                    >
                      {/* List name row */}
                      <div style={{ display: 'flex', alignItems: 'center', gap: 7 }}>
                        <span style={{
                          width: 9, height: 9, borderRadius: 2, flexShrink: 0,
                          background: list.color, boxShadow: `0 0 5px ${list.color}50`,
                        }}/>
                        <span style={{
                          fontSize: 13, fontWeight: 600, flex: 1,
                          overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap',
                          color: 'var(--text-0)',
                        }}>
                          {list.name}
                        </span>
                        <Icons.arrow size={11} style={{ color: 'var(--text-3)', flexShrink: 0 }}/>
                      </div>
                      {/* Product count */}
                      <div style={{ fontSize: 11, color: 'var(--text-3)' }}>
                        {s.count || 0} product{s.count !== 1 ? 's' : ''}
                      </div>
                    </div>
                  );
                })}

                {/* Empty state */}
                {lists.length === 0 && !isOver && (
                  <div style={{
                    minHeight: 60, borderRadius: 8,
                    border: '1px dashed var(--line)',
                    display: 'flex', alignItems: 'center', justifyContent: 'center',
                    color: 'var(--text-3)', fontSize: 12,
                  }}>
                    No lists
                  </div>
                )}
              </div>
            </div>
          );
        })}

        {/* Add stage column */}
        <div style={{ flex: '0 0 auto', width: 200, display: 'flex', flexDirection: 'column', gap: 8, paddingTop: 2 }}>
          {addingStatus ? (
            <div style={{
              padding: '12px', background: 'var(--bg-2)', borderRadius: 8,
              border: '1px solid var(--line-strong)',
              display: 'flex', flexDirection: 'column', gap: 10,
            }}>
              {/* Name */}
              <input
                autoFocus
                className="field-input"
                placeholder="Stage name"
                value={newStatusName}
                onChange={e => setNewStatusName(e.target.value)}
                onKeyDown={e => {
                  if (e.key === 'Enter') addStatus();
                  if (e.key === 'Escape') { setAddingStatus(false); setNewStatusName(''); }
                }}
                style={{ padding: '5px 8px', fontSize: 12 }}
              />

              {/* Color picker */}
              <div>
                <div style={{ fontSize: 10, color: 'var(--text-3)', fontWeight: 600, letterSpacing: '0.05em', marginBottom: 6 }}>COLOR</div>
                <div style={{ display: 'flex', flexWrap: 'wrap', gap: 5 }}>
                  {STAGE_COLORS.map(c => (
                    <span
                      key={c}
                      onClick={() => setNewStatusColor(c)}
                      style={{
                        width: 18, height: 18, borderRadius: 5, background: c,
                        cursor: 'pointer', flexShrink: 0,
                        boxShadow: newStatusColor === c
                          ? `0 0 0 2px var(--bg-2), 0 0 0 3.5px ${c}`
                          : `0 0 4px ${c}50`,
                      }}
                    />
                  ))}
                </div>
              </div>

              {/* Icon picker */}
              <div>
                <div style={{ fontSize: 10, color: 'var(--text-3)', fontWeight: 600, letterSpacing: '0.05em', marginBottom: 6 }}>ICON</div>
                <div style={{ display: 'grid', gridTemplateColumns: 'repeat(6, 1fr)', gap: 4 }}>
                  {STAGE_ICON_OPTIONS.map(iconId => {
                    const IconComp = getStatusIcon(iconId);
                    const isSelected = newStatusIconId === iconId;
                    return (
                      <button
                        key={iconId}
                        onClick={() => setNewStatusIconId(iconId)}
                        title={iconId}
                        style={{
                          display: 'flex', alignItems: 'center', justifyContent: 'center',
                          width: 28, height: 28, borderRadius: 6, border: 'none',
                          background: isSelected ? newStatusColor + '30' : 'var(--bg-1)',
                          color: isSelected ? newStatusColor : 'var(--text-2)',
                          cursor: 'pointer',
                          outline: isSelected ? `2px solid ${newStatusColor}80` : 'none',
                          outlineOffset: 1,
                        }}
                      >
                        <IconComp size={13}/>
                      </button>
                    );
                  })}
                </div>
              </div>

              {/* Buttons */}
              <div style={{ display: 'flex', gap: 6 }}>
                <button className="btn btn-primary btn-sm" style={{ flex: 1, justifyContent: 'center', fontSize: 11 }} onClick={addStatus}>Add stage</button>
                <button className="btn btn-sm btn-ghost" onClick={() => { setAddingStatus(false); setNewStatusName(''); }}>
                  <Icons.close size={10}/>
                </button>
              </div>
            </div>
          ) : (
            <button
              onClick={() => setAddingStatus(true)}
              style={{
                display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 6,
                padding: '9px 12px', borderRadius: 8,
                background: 'transparent', border: '1px dashed var(--line-strong)',
                cursor: 'pointer', color: 'var(--text-3)',
                fontSize: 12, fontWeight: 500, width: '100%',
              }}
              onMouseEnter={e => { e.currentTarget.style.color = 'var(--text-1)'; e.currentTarget.style.borderColor = 'var(--text-3)'; }}
              onMouseLeave={e => { e.currentTarget.style.color = 'var(--text-3)'; e.currentTarget.style.borderColor = 'var(--line-strong)'; }}
            >
              <Icons.plus size={13}/> Add stage
            </button>
          )}
        </div>
      </div>
    </div>
  );
};

window.FlowPage = FlowPage;
