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

export function loadSiteFolderIds(site) {
  try { return localStorage.getItem(`cu_folder_${site}`) || ''; } catch { return ''; }
}

export function saveSiteFolderIds(site, ids) {
  try { localStorage.setItem(`cu_folder_${site}`, ids); } catch {}
}

export default function SiteSettings({ sites = [], open, onClose }) {
  const [folders, setFolders]       = useState([]);
  const [loading, setLoading]       = useState(false);
  const [hasClickUp, setHasClickUp] = useState(null); // null = unknown, true/false after fetch
  const [mapping, setMapping]       = useState({});
  const [fetchError, setFetchError] = useState(null);

  useEffect(() => {
    if (!open) return;
    // Load saved mappings
    const saved = {};
    (sites || []).forEach(s => { saved[s.url] = loadSiteFolderIds(s.url); });
    setMapping(saved);
    // Fetch folders
    setLoading(true);
    setHasClickUp(null);
    setFetchError(null);
    clickup.folders()
      .then(data => {
        setFolders(Array.isArray(data) ? data : []);
        setHasClickUp(true);
      })
      .catch(e => {
        setFolders([]);
        setHasClickUp(false);
        setFetchError(e?.response?.data?.error || e.message || 'Connection failed');
      })
      .finally(() => setLoading(false));
  }, [open]);

  const save = () => {
    Object.entries(mapping).forEach(([site, ids]) => saveSiteFolderIds(site, ids));
    onClose(true);
  };

  const toggle = (siteUrl, folderId) => {
    setMapping(prev => {
      const current = (prev[siteUrl] || '').split(',').filter(Boolean);
      const idx = current.indexOf(folderId);
      if (idx === -1) current.push(folderId);
      else current.splice(idx, 1);
      return { ...prev, [siteUrl]: current.join(',') };
    });
  };

  if (!open) return null;

  return (
    <div style={{ position: 'fixed', inset: 0, zIndex: 200, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
      {/* Backdrop */}
      <div onClick={() => onClose(false)}
        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: 560, maxWidth: '92vw', maxHeight: '80vh',
        overflowY: 'auto', boxShadow: '0 20px 60px rgba(0,0,0,.2)',
      }}>
        {/* Header */}
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 18 }}>
          <div>
            <div style={{ fontWeight: 600, fontSize: 15 }}>ClickUp folder mapping</div>
            <div style={{ fontSize: 12, color: 'var(--text2)', marginTop: 3 }}>
              Choose which folders / lists to show per site
            </div>
          </div>
          <button onClick={() => onClose(false)}
            style={{ fontSize: 22, background: 'none', border: 'none', cursor: 'pointer', color: 'var(--text2)', lineHeight: 1, padding: '0 4px' }}>
            ×
          </button>
        </div>

        {/* Loading */}
        {loading && (
          <div style={{ textAlign: 'center', padding: '40px 0' }}>
            <div style={{ fontSize: 13, color: 'var(--text2)', marginBottom: 8 }}>Loading ClickUp folders…</div>
            <div style={{ fontSize: 11, color: 'var(--text3)' }}>Connecting to your workspace</div>
          </div>
        )}

        {/* Error / not connected */}
        {!loading && hasClickUp === false && (
          <div>
            <div style={{ background: 'var(--amber-bg)', border: '0.5px solid var(--amber-text)', borderRadius: 10, padding: 16, marginBottom: 20 }}>
              <div style={{ fontWeight: 500, fontSize: 13, color: 'var(--amber-text)', marginBottom: 6 }}>
                ⚠ Could not connect to ClickUp
              </div>
              <div style={{ fontSize: 12, color: 'var(--text2)', lineHeight: 1.6 }}>
                {fetchError && <div style={{ marginBottom: 6, fontFamily: 'monospace', fontSize: 11 }}>{fetchError}</div>}
                Make sure <code style={{ background: 'var(--surface2)', padding: '1px 5px', borderRadius: 4 }}>CLICKUP_API_TOKEN</code> and <code style={{ background: 'var(--surface2)', padding: '1px 5px', borderRadius: 4 }}>CLICKUP_TEAM_ID</code> are set in your .env file, then restart the server.
              </div>
            </div>

            <div style={{ fontSize: 13, fontWeight: 500, marginBottom: 12 }}>Setup steps:</div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
              {[
                { n: 1, title: 'Get your API token', body: 'ClickUp → click your avatar (bottom left) → Settings → Apps → API Token → copy the token starting with pk_' },
                { n: 2, title: 'Get your Team ID', body: 'Look at the URL: app.clickup.com/43327669/... — the number is your Team ID' },
                { n: 3, title: 'Add to .env file', code: 'CLICKUP_API_TOKEN=pk_xxxxxxxxxx\nCLICKUP_TEAM_ID=12345678' },
                { n: 4, title: 'Restart', body: 'Press Ctrl+C in PowerShell then run npm run dev again' },
              ].map(step => (
                <div key={step.n} style={{ display: 'flex', gap: 12 }}>
                  <div style={{ width: 24, height: 24, borderRadius: '50%', background: 'var(--blue)', color: '#fff', fontSize: 11, fontWeight: 700, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0, marginTop: 1 }}>
                    {step.n}
                  </div>
                  <div>
                    <div style={{ fontSize: 12, fontWeight: 500, marginBottom: 3 }}>{step.title}</div>
                    {step.body && <div style={{ fontSize: 12, color: 'var(--text2)', lineHeight: 1.5 }}>{step.body}</div>}
                    {step.code && <pre style={{ margin: 0, fontSize: 11, background: 'var(--surface2)', borderRadius: 7, padding: '8px 12px', color: 'var(--text)', lineHeight: 1.7, whiteSpace: 'pre-wrap', fontFamily: 'monospace' }}>{step.code}</pre>}
                  </div>
                </div>
              ))}
            </div>

            <button onClick={() => onClose(false)}
              style={{ marginTop: 20, width: '100%', fontSize: 12, padding: '8px 0', borderRadius: 8, border: '0.5px solid var(--border2)', background: 'transparent', color: 'var(--text2)', cursor: 'pointer' }}>
              Close
            </button>
          </div>
        )}

        {/* Connected — folder mapping */}
        {!loading && hasClickUp === true && (
          <div>
            {folders.length === 0 ? (
              <div style={{ fontSize: 12, color: 'var(--text2)', padding: '16px 0' }}>
                No folders found in your ClickUp workspace.
              </div>
            ) : (
              (sites || []).map(site => {
                const selected = (mapping[site.url] || '').split(',').filter(Boolean);
                return (
                  <div key={site.url} style={{ marginBottom: 20, paddingBottom: 20, borderBottom: '0.5px solid var(--border)' }}>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 7, marginBottom: 10 }}>
                      <span style={{ width: 9, height: 9, borderRadius: '50%', background: site.color, flexShrink: 0 }} />
                      <span style={{ fontWeight: 500, fontSize: 13 }}>{site.label}</span>
                      {selected.length > 0 && (
                        <span style={{ fontSize: 11, color: 'var(--green-text)', background: 'var(--green-bg)', padding: '1px 7px', borderRadius: 10 }}>
                          {selected.length} selected
                        </span>
                      )}
                    </div>
                    <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
                      {[...new Set(folders.map(f => f.spaceName))].map(spaceName => (
                        <div key={spaceName}>
                          <div style={{ fontSize: 10, fontWeight: 600, color: 'var(--text3)', textTransform: 'uppercase', letterSpacing: '.05em', marginBottom: 5 }}>
                            {spaceName}
                          </div>
                          <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
                            {folders.filter(f => f.spaceName === spaceName).map(folder => {
                              const isSelected = selected.includes(folder.id);
                              return (
                                <button key={folder.id} onClick={() => toggle(site.url, folder.id)}
                                  style={{
                                    fontSize: 11, padding: '4px 10px', borderRadius: 20, cursor: 'pointer',
                                    border: `0.5px solid ${isSelected ? 'var(--blue)' : 'var(--border2)'}`,
                                    background: isSelected ? 'var(--blue-bg)' : 'transparent',
                                    color: isSelected ? 'var(--blue-text)' : 'var(--text2)',
                                    fontWeight: isSelected ? 500 : 400, transition: 'all .12s',
                                  }}>
                                  {folder.type === 'list' ? '📋 ' : '📁 '}{folder.name}
                                </button>
                              );
                            })}
                          </div>
                        </div>
                      ))}
                      <button onClick={() => setMapping(p => ({ ...p, [site.url]: '' }))}
                        style={{ alignSelf: 'flex-start', fontSize: 11, color: 'var(--text3)', background: 'none', border: 'none', cursor: 'pointer', padding: '2px 0' }}>
                        Clear (show all tasks)
                      </button>
                    </div>
                  </div>
                );
              })
            )}

            <div style={{ display: 'flex', gap: 8, justifyContent: 'flex-end', marginTop: 8 }}>
              <button onClick={() => onClose(false)}
                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={save}
                style={{ fontSize: 12, fontWeight: 500, padding: '7px 18px', borderRadius: 8, border: 'none', background: 'var(--blue)', color: '#fff', cursor: 'pointer' }}>
                Save & apply
              </button>
            </div>
          </div>
        )}
      </div>
    </div>
  );
}
