import { useState, useEffect } from 'react';
import { clickup } from '../lib/api';
import TasksKanban from './TasksKanban';

/**
 * FolderGroupTasks
 *
 * Shows tasks grouped by named folder sets.
 * Groups are stored in localStorage per site as:
 *   cu_groups_{site} = JSON array of { name, color, folderIds[] }
 *
 * Example:
 *   [
 *     { name: "Content", color: "#378ADD", folderIds: ["90123","90124"] },
 *     { name: "Off-page", color: "#1D9E75", folderIds: ["90125"] }
 *   ]
 */

const GROUP_COLORS = ['#378ADD','#1D9E75','#D85A30','#7F77DD','#BA7517','#D4537E'];

function loadGroups(site) {
  try {
    const raw = localStorage.getItem(`cu_groups_${site}`);
    return raw ? JSON.parse(raw) : [];
  } catch { return []; }
}

function saveGroups(site, groups) {
  try { localStorage.setItem(`cu_groups_${site}`, JSON.stringify(groups)); } catch {}
}

// ── Group editor modal ────────────────────────────────────────
function GroupEditor({ site, groups, folders, onSave, onClose }) {
  const [draft, setDraft] = useState(groups.length > 0
    ? JSON.parse(JSON.stringify(groups))
    : [{ name: 'Content', color: '#378ADD', folderIds: [] }]
  );

  const addGroup = () => setDraft(d => [...d, { name: 'New group', color: GROUP_COLORS[d.length % GROUP_COLORS.length], folderIds: [] }]);
  const removeGroup = (i) => setDraft(d => d.filter((_, idx) => idx !== i));
  const updateGroup = (i, key, val) => setDraft(d => d.map((g, idx) => idx === i ? { ...g, [key]: val } : g));

  const toggleFolder = (groupIdx, folderId) => {
    setDraft(d => d.map((g, idx) => {
      if (idx !== groupIdx) return g;
      const ids = g.folderIds.includes(folderId)
        ? g.folderIds.filter(id => id !== folderId)
        : [...g.folderIds, folderId];
      return { ...g, folderIds: ids };
    }));
  };

  return (
    <div style={{ position: 'fixed', inset: 0, zIndex: 200, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
      <div onClick={onClose} style={{ position: 'absolute', inset: 0, background: 'rgba(0,0,0,.35)', backdropFilter: 'blur(2px)' }} />
      <div style={{ position: 'relative', background: 'var(--surface)', border: '0.5px solid var(--border)', borderRadius: 14, padding: 24, width: 580, maxWidth: '94vw', maxHeight: '82vh', overflowY: 'auto', boxShadow: '0 20px 60px rgba(0,0,0,.2)' }}>

        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 18 }}>
          <div>
            <div style={{ fontWeight: 600, fontSize: 15 }}>Task folder groups</div>
            <div style={{ fontSize: 12, color: 'var(--text2)', marginTop: 3 }}>Group folders into named boards — e.g. Content, Off-page</div>
          </div>
          <button onClick={onClose} style={{ fontSize: 22, background: 'none', border: 'none', cursor: 'pointer', color: 'var(--text2)', lineHeight: 1 }}>×</button>
        </div>

        {draft.map((group, gi) => (
          <div key={gi} style={{ background: 'var(--surface2)', border: '0.5px solid var(--border)', borderRadius: 10, padding: 14, marginBottom: 12 }}>
            {/* Group name + color + remove */}
            <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 12 }}>
              {/* Color picker */}
              <div style={{ display: 'flex', gap: 4 }}>
                {GROUP_COLORS.map(c => (
                  <div key={c} onClick={() => updateGroup(gi, 'color', c)}
                    style={{ width: 16, height: 16, borderRadius: '50%', background: c, cursor: 'pointer', border: group.color === c ? '2px solid var(--text)' : '2px solid transparent', transition: 'border .1s' }} />
                ))}
              </div>
              <input value={group.name} onChange={e => updateGroup(gi, 'name', e.target.value)}
                placeholder="Group name"
                style={{ flex: 1, fontSize: 13, fontWeight: 500, padding: '4px 8px', borderRadius: 6, border: '0.5px solid var(--border2)', background: 'var(--surface)', color: 'var(--text)' }} />
              {draft.length > 1 && (
                <button onClick={() => removeGroup(gi)}
                  style={{ fontSize: 11, color: 'var(--red-text)', background: 'none', border: 'none', cursor: 'pointer', padding: '2px 4px' }}>
                  Remove
                </button>
              )}
            </div>

            {/* Folder picker */}
            <div style={{ fontSize: 10, fontWeight: 600, color: 'var(--text3)', textTransform: 'uppercase', letterSpacing: '.05em', marginBottom: 6 }}>
              Select folders / lists for this group
            </div>
            {folders.length === 0
              ? <div style={{ fontSize: 12, color: 'var(--text3)' }}>No folders found. Make sure ClickUp is connected.</div>
              : [...new Set(folders.map(f => f.spaceName))].map(spaceName => (
                <div key={spaceName} style={{ marginBottom: 8 }}>
                  <div style={{ fontSize: 10, color: 'var(--text3)', marginBottom: 4 }}>{spaceName}</div>
                  <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
                    {folders.filter(f => f.spaceName === spaceName).map(folder => {
                      const selected = group.folderIds.includes(folder.id);
                      return (
                        <button key={folder.id} onClick={() => toggleFolder(gi, folder.id)}
                          style={{ fontSize: 11, padding: '3px 10px', borderRadius: 20, cursor: 'pointer',
                            border: `0.5px solid ${selected ? group.color : 'var(--border2)'}`,
                            background: selected ? group.color + '22' : 'transparent',
                            color: selected ? group.color : 'var(--text2)',
                            fontWeight: selected ? 500 : 400, transition: 'all .12s' }}>
                          {folder.type === 'list' ? '📋 ' : '📁 '}{folder.name}
                          {selected && ' ✓'}
                        </button>
                      );
                    })}
                  </div>
                </div>
              ))
            }
            <div style={{ fontSize: 11, color: 'var(--text3)', marginTop: 4 }}>
              {group.folderIds.length} folder{group.folderIds.length !== 1 ? 's' : ''} selected
            </div>
          </div>
        ))}

        <button onClick={addGroup}
          style={{ width: '100%', fontSize: 12, padding: '7px 0', borderRadius: 8, border: '1px dashed var(--border2)', background: 'transparent', color: 'var(--text2)', cursor: 'pointer', marginBottom: 16 }}>
          + Add another group
        </button>

        <div style={{ display: 'flex', gap: 8, justifyContent: 'flex-end' }}>
          <button onClick={onClose}
            style={{ fontSize: 12, padding: '7px 16px', borderRadius: 8, border: '0.5px solid var(--border2)', background: 'transparent', color: 'var(--text2)', cursor: 'pointer' }}>
            Cancel
          </button>
          <button onClick={() => onSave(draft)}
            style={{ fontSize: 12, fontWeight: 500, padding: '7px 18px', borderRadius: 8, border: 'none', background: 'var(--blue)', color: '#fff', cursor: 'pointer' }}>
            Save groups
          </button>
        </div>
      </div>
    </div>
  );
}

// ── Main component ────────────────────────────────────────────
export default function FolderGroupTasks({ site, defaultFolderIds }) {
  const [groups, setGroups]         = useState([]);
  const [activeGroup, setActiveGroup] = useState('all');
  const [folders, setFolders]       = useState([]);
  const [editorOpen, setEditorOpen] = useState(false);
  const [groupTasks, setGroupTasks] = useState({});   // { groupIdx: tasks }
  const [loadingGroup, setLoadingGroup] = useState({});

  // Load saved groups for this site
  useEffect(() => {
    if (!site) return;
    const saved = loadGroups(site);
    setGroups(saved);
    setActiveGroup(saved.length > 0 ? 0 : 'all');
  }, [site]);

  // Fetch folders for editor
  useEffect(() => {
    clickup.folders().then(setFolders).catch(() => setFolders([]));
  }, []);

  // Fetch tasks for each group
  useEffect(() => {
    if (!site) return;
    groups.forEach((g, i) => {
      if (g.folderIds.length === 0) return;
      setLoadingGroup(p => ({ ...p, [i]: true }));
      clickup.tasks(g.folderIds.join(','))
        .then(data => setGroupTasks(p => ({ ...p, [i]: data })))
        .catch(() => setGroupTasks(p => ({ ...p, [i]: null })))
        .finally(() => setLoadingGroup(p => ({ ...p, [i]: false })));
    });
  }, [site, groups]);

  // "All" tasks uses the default folder filter from site settings
  const [allTasks, setAllTasks]     = useState(null);
  const [allLoading, setAllLoading] = useState(false);
  useEffect(() => {
    if (!site) return;
    setAllLoading(true);
    clickup.tasks(defaultFolderIds || '')
      .then(setAllTasks)
      .catch(() => setAllTasks(null))
      .finally(() => setAllLoading(false));
  }, [site, defaultFolderIds]);

  const handleSave = (draft) => {
    saveGroups(site, draft);
    setGroups(draft);
    setActiveGroup(draft.length > 0 ? 0 : 'all');
    setEditorOpen(false);
    // Re-fetch tasks for new groups
    setGroupTasks({});
    draft.forEach((g, i) => {
      if (g.folderIds.length === 0) return;
      setLoadingGroup(p => ({ ...p, [i]: true }));
      clickup.tasks(g.folderIds.join(','))
        .then(data => setGroupTasks(p => ({ ...p, [i]: data })))
        .finally(() => setLoadingGroup(p => ({ ...p, [i]: false })));
    });
  };

  const activeTasks   = activeGroup === 'all' ? allTasks   : groupTasks[activeGroup];
  const activeLoading = activeGroup === 'all' ? allLoading : !!loadingGroup[activeGroup];
  const activeColor   = activeGroup === 'all' ? 'var(--text2)' : (groups[activeGroup]?.color || 'var(--blue)');

  return (
    <div>
      {/* Group tabs + edit button */}
      <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginBottom: 16, flexWrap: 'wrap' }}>
        {/* All tasks tab */}
        <button onClick={() => setActiveGroup('all')}
          style={{ fontSize: 12, padding: '5px 14px', borderRadius: 20, cursor: 'pointer',
            border: `0.5px solid ${activeGroup === 'all' ? 'var(--border)' : 'var(--border2)'}`,
            background: activeGroup === 'all' ? 'var(--surface)' : 'transparent',
            color: activeGroup === 'all' ? 'var(--text)' : 'var(--text2)',
            fontWeight: activeGroup === 'all' ? 500 : 400, boxShadow: activeGroup === 'all' ? '0 1px 4px rgba(0,0,0,.08)' : 'none' }}>
          All tasks
          {allTasks && <span style={{ fontSize: 10, color: 'var(--text3)', marginLeft: 5 }}>{allTasks.total}</span>}
        </button>

        {/* Group tabs */}
        {groups.map((g, i) => (
          <button key={i} onClick={() => setActiveGroup(i)}
            style={{ fontSize: 12, padding: '5px 14px', borderRadius: 20, cursor: 'pointer',
              border: `0.5px solid ${activeGroup === i ? g.color : 'var(--border2)'}`,
              background: activeGroup === i ? g.color + '18' : 'transparent',
              color: activeGroup === i ? g.color : 'var(--text2)',
              fontWeight: activeGroup === i ? 500 : 400,
              display: 'flex', alignItems: 'center', gap: 6 }}>
            <span style={{ width: 7, height: 7, borderRadius: '50%', background: g.color, flexShrink: 0 }} />
            {g.name}
            {groupTasks[i] && <span style={{ fontSize: 10, opacity: 0.7 }}>{groupTasks[i].total}</span>}
          </button>
        ))}

        {/* Edit button */}
        <button onClick={() => setEditorOpen(true)}
          style={{ fontSize: 11, padding: '4px 10px', borderRadius: 20, border: '1px dashed var(--border2)', background: 'transparent', color: 'var(--text3)', cursor: 'pointer', marginLeft: 'auto' }}>
          ⚙ Edit groups
        </button>
      </div>

      {/* Active group label */}
      {activeGroup !== 'all' && groups[activeGroup] && (
        <div style={{ display: 'flex', alignItems: 'center', gap: 7, marginBottom: 10 }}>
          <span style={{ width: 8, height: 8, borderRadius: '50%', background: groups[activeGroup].color }} />
          <span style={{ fontSize: 12, fontWeight: 500, color: groups[activeGroup].color }}>{groups[activeGroup].name}</span>
          <span style={{ fontSize: 11, color: 'var(--text3)' }}>
            · {groups[activeGroup].folderIds.length} folder{groups[activeGroup].folderIds.length !== 1 ? 's' : ''}
          </span>
        </div>
      )}

      {/* No groups configured yet */}
      {groups.length === 0 && (
        <div style={{ background: 'var(--surface2)', border: '0.5px solid var(--border)', borderRadius: 10, padding: '14px 16px', marginBottom: 14, fontSize: 12, color: 'var(--text2)', lineHeight: 1.6 }}>
          💡 <strong>Tip:</strong> Click <strong>⚙ Edit groups</strong> to create folder groups — e.g. one for <em>Content</em> tasks and another for <em>Off-page / backlinks</em>. Each group gets its own Kanban board.
        </div>
      )}

      {/* Kanban board */}
      <TasksKanban
        tasks={activeTasks}
        loading={activeLoading}
        onTaskUpdate={() => {
          // Refresh the active group
          if (activeGroup === 'all') {
            setAllLoading(true);
            clickup.tasks(defaultFolderIds || '').then(setAllTasks).finally(() => setAllLoading(false));
          } else {
            const g = groups[activeGroup];
            if (g) {
              setLoadingGroup(p => ({ ...p, [activeGroup]: true }));
              clickup.tasks(g.folderIds.join(',')).then(data => setGroupTasks(p => ({ ...p, [activeGroup]: data }))).finally(() => setLoadingGroup(p => ({ ...p, [activeGroup]: false })));
            }
          }
        }}
      />

      {/* Editor modal */}
      {editorOpen && (
        <GroupEditor
          site={site}
          groups={groups}
          folders={folders}
          onSave={handleSave}
          onClose={() => setEditorOpen(false)}
        />
      )}
    </div>
  );
}
