import React, { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import {
  getDefaultLightTheme,
  getDefaultDarkTheme,
  getStoredThemes,
  getPresetThemes,
  saveThemes,
  applyTheme,
  applyStoredTheme,
} from '../../../utils/themeUtils';
import { useTheme } from '../../../contexts/ThemeContext';
import './styles/ThemeManagement.css';

const FONT_PRESETS = [
  { value: '', label: 'Custom' },
  { value: "Inter, -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif", label: 'Inter' },
  { value: 'system-ui, -apple-system, sans-serif', label: 'System UI' },
  { value: "'Segoe UI', Tahoma, Geneva, Verdana, sans-serif", label: 'Segoe UI' },
  { value: "'Roboto', 'Helvetica Neue', Arial, sans-serif", label: 'Roboto' },
  { value: "'Open Sans', 'Helvetica Neue', sans-serif", label: 'Open Sans' },
  { value: 'Georgia, serif', label: 'Georgia' },
];

const SECTION_IDS = ['presets', 'preview', 'header', 'sidebar', 'content', 'cards', 'typography', 'accent', 'feedback', 'layout', 'shadows', 'transitions'];

function applyModeToPage(editMode, theme) {
  if (!theme) return;
  document.body.classList.remove('light-mode', 'night-mode');
  document.body.classList.add(editMode === 'light' ? 'light-mode' : 'night-mode');
  applyTheme(theme);
}

const ColorRow = ({ value, onChange }) => {
  const hexForPicker = value && /^#[0-9A-Fa-f]{6}$/.test(value) ? value : '#000000';
  return (
    <div className="theme-color-row">
      <input type="color" value={hexForPicker} onChange={(e) => onChange(e.target.value)} />
      <input type="text" value={value || ''} onChange={(e) => onChange(e.target.value)} className="theme-input-text" placeholder="#hex or rgba()" />
    </div>
  );
};

const ThemeManagement = () => {
  const navigate = useNavigate();
  const { theme: appMode } = useTheme();
  const [editMode, setEditMode] = useState('light');
  const [themes, setThemes] = useState(() => {
    const stored = getStoredThemes();
    if (stored) return stored;
    return { light: getDefaultLightTheme(), dark: getDefaultDarkTheme() };
  });
  const [saved, setSaved] = useState(false);
  const [expanded, setExpanded] = useState(() => SECTION_IDS.reduce((acc, id) => ({ ...acc, [id]: true }), {}));
  const presets = getPresetThemes();

  const currentTheme = themes[editMode] || (editMode === 'light' ? getDefaultLightTheme() : getDefaultDarkTheme());

  // Apply the theme for the tab we're editing so changes are visible immediately
  useEffect(() => {
    applyModeToPage(editMode, currentTheme);
    return () => {
      document.body.classList.remove('light-mode', 'night-mode');
      document.body.classList.add(appMode === 'light' ? 'light-mode' : 'night-mode');
      applyStoredTheme();
    };
  }, [editMode, currentTheme, appMode]);

  const update = (mode, key, value) => {
    const next = { ...themes, [mode]: { ...themes[mode], [key]: value } };
    setThemes(next);
    saveThemes(next);
    applyTheme(next[mode]);
    document.body.classList.remove('light-mode', 'night-mode');
    document.body.classList.add(mode === 'light' ? 'light-mode' : 'night-mode');
    setSaved(true);
    setTimeout(() => setSaved(false), 2000);
  };

  const toggleSection = (id) => {
    setExpanded((prev) => ({ ...prev, [id]: !prev[id] }));
  };

  const reset = () => {
    const def = editMode === 'light' ? getDefaultLightTheme() : getDefaultDarkTheme();
    const next = { ...themes, [editMode]: def };
    setThemes(next);
    saveThemes(next);
    applyModeToPage(editMode, def);
    setSaved(true);
    setTimeout(() => setSaved(false), 2000);
  };

  const applyPreset = (preset) => {
    const themeToApply = editMode === 'light' ? preset.light : preset.dark;
    const next = { ...themes, [editMode]: { ...themeToApply } };
    setThemes(next);
    saveThemes(next);
    applyModeToPage(editMode, themeToApply);
    setSaved(true);
    setTimeout(() => setSaved(false), 2000);
  };

  const renderSection = (id, title, children, extraClass = '') => (
    <section className={`theme-section ${extraClass} ${expanded[id] ? 'theme-section-open' : ''}`}>
      <h2 className="theme-section-head" onClick={() => toggleSection(id)}>
        <span>{title}</span>
        <span className="theme-section-toggle" aria-hidden>{expanded[id] ? '▼' : '▶'}</span>
      </h2>
      {expanded[id] ? <div className="theme-section-body">{children}</div> : null}
    </section>
  );

  return (
    <div className="theme-management">
      <header className="theme-management-header">
        <h1 className="theme-management-title">Theme Management</h1>
        <p className="theme-management-subtitle">
          Change colours and typography for Light or Dark mode. The whole page updates as you edit. Saved in your browser.
        </p>
        <div className="theme-management-actions">
          <button type="button" className="theme-btn theme-btn-secondary" onClick={() => navigate('/dashboard')}>
            Back to Dashboard
          </button>
          <button type="button" className="theme-btn theme-btn-primary" onClick={reset}>
            Reset to default
          </button>
          {saved && <span className="theme-saved-badge">Saved</span>}
        </div>
      </header>

      <div className="theme-mode-tabs">
        <button type="button" className={`theme-mode-tab ${editMode === 'light' ? 'active' : ''}`} onClick={() => setEditMode('light')}>
          Light mode
        </button>
        <button type="button" className={`theme-mode-tab ${editMode === 'dark' ? 'active' : ''}`} onClick={() => setEditMode('dark')}>
          Dark mode
        </button>
      </div>
      <p className="theme-edit-hint">Editing: <strong>{editMode === 'light' ? 'Light' : 'Dark'}</strong>. Changes apply to this mode and update the page immediately.</p>

      {renderSection('presets', 'Preset themes', (
        <>
          <p className="theme-presets-desc">Click a preset to apply it to the current tab. Then tweak below if needed.</p>
          <div className="theme-presets-grid">
            {presets.map((preset) => (
              <button key={preset.id} type="button" className="theme-preset-card" onClick={() => applyPreset(preset)} title={`Apply ${preset.name}`}>
                <span className="theme-preset-swatch" style={{ background: preset.accent }} />
                <span className="theme-preset-name">{preset.name}</span>
              </button>
            ))}
          </div>
        </>
      ), 'theme-presets-section')}

      {renderSection('preview', 'Live preview', (
        <div className="theme-preview">
          <div className="theme-preview-card" style={{
            background: currentTheme.cardBg,
            borderColor: currentTheme.borderColor,
            borderRadius: currentTheme.borderRadius,
            boxShadow: currentTheme.shadowMd,
            color: currentTheme.textPrimary,
            fontFamily: currentTheme.fontFamily,
            fontSize: currentTheme.fontSizeBody,
            lineHeight: currentTheme.lineHeight,
          }}>
            <h3 style={{ color: currentTheme.textPrimary, fontWeight: currentTheme.fontWeightHeading, fontSize: currentTheme.fontSizeH1 }}>Preview</h3>
            <p style={{ color: currentTheme.textSecondary }}>Sample text. Buttons and badges below.</p>
            <div className="theme-preview-badges">
              <span className="theme-preview-badge" style={{ background: currentTheme.successColor }}>Success</span>
              <span className="theme-preview-badge" style={{ background: currentTheme.errorColor }}>Error</span>
              <span className="theme-preview-badge" style={{ background: currentTheme.warningColor }}>Warning</span>
            </div>
            <div className="theme-preview-actions">
              <button type="button" className="theme-preview-btn primary" style={{ background: currentTheme.primaryColor, color: currentTheme.buttonPrimaryText, borderRadius: currentTheme.borderRadius }}>Primary</button>
              <button type="button" className="theme-preview-btn secondary" style={{ background: currentTheme.contentBg, color: currentTheme.buttonSecondaryText, border: `1px solid ${currentTheme.borderColor}`, borderRadius: currentTheme.borderRadius }}>Secondary</button>
            </div>
          </div>
        </div>
      ), 'theme-preview-section')}

      <div className="theme-sections">
        {renderSection('header', 'Header (Navbar)', (
          <div className="theme-grid">
            <label><span>Background</span><input type="text" value={currentTheme.headerBg} onChange={(e) => update(editMode, 'headerBg', e.target.value)} placeholder="e.g. rgba(0,0,0,0.92)" /></label>
            <label><span>Text / icon colour</span><ColorRow value={currentTheme.headerText} onChange={(v) => update(editMode, 'headerText', v)} /></label>
            <label><span>Brand / logo colour</span><ColorRow value={currentTheme.headerBrandColor} onChange={(v) => update(editMode, 'headerBrandColor', v)} /></label>
          </div>
        ))}

        {renderSection('sidebar', 'Sidebar', (
          <div className="theme-grid">
            <label><span>Background</span><input type="text" value={currentTheme.sidebarBg} onChange={(e) => update(editMode, 'sidebarBg', e.target.value)} /></label>
            <label><span>Text colour</span><ColorRow value={currentTheme.sidebarText} onChange={(v) => update(editMode, 'sidebarText', v)} /></label>
            <label><span>Active item background</span><ColorRow value={currentTheme.sidebarActiveBg} onChange={(v) => update(editMode, 'sidebarActiveBg', v)} /></label>
            <label><span>Active item text</span><ColorRow value={currentTheme.sidebarActiveText} onChange={(v) => update(editMode, 'sidebarActiveText', v)} /></label>
            <label><span>Hover background</span><ColorRow value={currentTheme.sidebarHoverBg} onChange={(v) => update(editMode, 'sidebarHoverBg', v)} /></label>
          </div>
        ))}

        {renderSection('content', 'Main content & body', (
          <div className="theme-grid">
            <label><span>Content area background</span><input type="text" value={currentTheme.contentBg} onChange={(e) => update(editMode, 'contentBg', e.target.value)} /></label>
            <label><span>Page background (body)</span><input type="text" value={currentTheme.bodyBg} onChange={(e) => update(editMode, 'bodyBg', e.target.value)} placeholder="e.g. #e5e5e5" /></label>
          </div>
        ))}

        {renderSection('cards', 'Cards & surfaces', (
          <div className="theme-grid">
            <label><span>Card background</span><input type="text" value={currentTheme.cardBg} onChange={(e) => update(editMode, 'cardBg', e.target.value)} /></label>
            <label><span>Input background</span><ColorRow value={currentTheme.inputBg} onChange={(v) => update(editMode, 'inputBg', v)} /></label>
            <label><span>Border colour</span><ColorRow value={currentTheme.borderColor} onChange={(v) => update(editMode, 'borderColor', v)} /></label>
          </div>
        ))}

        {renderSection('typography', 'Typography', (
          <div className="theme-grid">
            <label><span>Primary text colour</span><ColorRow value={currentTheme.textPrimary} onChange={(v) => update(editMode, 'textPrimary', v)} /></label>
            <label><span>Secondary text colour</span><ColorRow value={currentTheme.textSecondary} onChange={(v) => update(editMode, 'textSecondary', v)} /></label>
            <label><span>Muted text colour</span><ColorRow value={currentTheme.textMuted} onChange={(v) => update(editMode, 'textMuted', v)} /></label>
            <label><span>Base font size (%)</span><input type="number" min="75" max="150" value={currentTheme.fontSize} onChange={(e) => update(editMode, 'fontSize', e.target.value)} /></label>
            <label><span>Body font size</span><input type="text" value={currentTheme.fontSizeBody} onChange={(e) => update(editMode, 'fontSizeBody', e.target.value)} placeholder="e.g. 1rem" /></label>
            <label><span>Heading 1 size</span><input type="text" value={currentTheme.fontSizeH1} onChange={(e) => update(editMode, 'fontSizeH1', e.target.value)} placeholder="1.75rem" /></label>
            <label><span>Heading 2 size</span><input type="text" value={currentTheme.fontSizeH2} onChange={(e) => update(editMode, 'fontSizeH2', e.target.value)} placeholder="1.5rem" /></label>
            <label><span>Heading 3 size</span><input type="text" value={currentTheme.fontSizeH3} onChange={(e) => update(editMode, 'fontSizeH3', e.target.value)} placeholder="1.25rem" /></label>
            <label><span>Font family</span>
              <select value={FONT_PRESETS.find((p) => p.value === currentTheme.fontFamily) ? currentTheme.fontFamily : ''} onChange={(e) => { const v = e.target.value; if (v) update(editMode, 'fontFamily', v); }}>
                {FONT_PRESETS.map((p) => <option key={p.label} value={p.value}>{p.label}</option>)}
              </select>
            </label>
            <label className="theme-full-width"><span>Font family (custom)</span><input type="text" value={currentTheme.fontFamily} onChange={(e) => update(editMode, 'fontFamily', e.target.value)} placeholder="e.g. Inter, sans-serif" /></label>
            <label><span>Heading weight</span>
              <select value={currentTheme.fontWeightHeading} onChange={(e) => update(editMode, 'fontWeightHeading', e.target.value)}>
                <option value="400">400</option><option value="500">500</option><option value="600">600</option><option value="700">700</option><option value="800">800</option>
              </select>
            </label>
            <label><span>Body weight</span>
              <select value={currentTheme.fontWeightBody} onChange={(e) => update(editMode, 'fontWeightBody', e.target.value)}>
                <option value="300">300</option><option value="400">400</option><option value="500">500</option><option value="600">600</option>
              </select>
            </label>
            <label><span>Letter spacing</span>
              <select value={currentTheme.letterSpacing} onChange={(e) => update(editMode, 'letterSpacing', e.target.value)}>
                <option value="-0.02em">Tight</option><option value="normal">Normal</option><option value="0.02em">Wide</option><option value="0.05em">Wider</option>
              </select>
            </label>
            <label><span>Line height</span>
              <select value={currentTheme.lineHeight} onChange={(e) => update(editMode, 'lineHeight', e.target.value)}>
                <option value="1.25">1.25</option><option value="1.4">1.4</option><option value="1.5">1.5</option><option value="1.6">1.6</option><option value="1.75">1.75</option>
              </select>
            </label>
          </div>
        ))}

        {renderSection('accent', 'Accent & UI', (
          <div className="theme-grid">
            <label><span>Primary (accent) colour</span><ColorRow value={currentTheme.primaryColor} onChange={(v) => update(editMode, 'primaryColor', v)} /></label>
            <label><span>Primary dark (hover)</span><ColorRow value={currentTheme.primaryDark} onChange={(v) => update(editMode, 'primaryDark', v)} /></label>
            <label><span>Border radius</span><input type="text" value={currentTheme.borderRadius} onChange={(e) => update(editMode, 'borderRadius', e.target.value)} placeholder="0.5rem" /></label>
            <label><span>Link colour</span><ColorRow value={currentTheme.linkColor} onChange={(v) => update(editMode, 'linkColor', v)} /></label>
          </div>
        ))}

        {renderSection('feedback', 'Feedback colours', (
          <div className="theme-grid">
            <label><span>Success</span><ColorRow value={currentTheme.successColor} onChange={(v) => update(editMode, 'successColor', v)} /></label>
            <label><span>Error</span><ColorRow value={currentTheme.errorColor} onChange={(v) => update(editMode, 'errorColor', v)} /></label>
            <label><span>Warning</span><ColorRow value={currentTheme.warningColor} onChange={(v) => update(editMode, 'warningColor', v)} /></label>
            <label><span>Info</span><ColorRow value={currentTheme.infoColor} onChange={(v) => update(editMode, 'infoColor', v)} /></label>
          </div>
        ))}

        {renderSection('layout', 'Layout', (
          <div className="theme-grid">
            <label><span>Sidebar width</span><input type="text" value={currentTheme.sidebarWidth} onChange={(e) => update(editMode, 'sidebarWidth', e.target.value)} placeholder="260px" /></label>
            <label><span>Border width</span><input type="text" value={currentTheme.borderWidth} onChange={(e) => update(editMode, 'borderWidth', e.target.value)} placeholder="1px" /></label>
            <label><span>Focus ring colour</span><ColorRow value={currentTheme.focusRingColor} onChange={(v) => update(editMode, 'focusRingColor', v)} /></label>
            <label><span>Table header background</span><ColorRow value={currentTheme.tableHeaderBg} onChange={(v) => update(editMode, 'tableHeaderBg', v)} /></label>
            <label><span>Primary button text</span><ColorRow value={currentTheme.buttonPrimaryText} onChange={(v) => update(editMode, 'buttonPrimaryText', v)} /></label>
            <label><span>Secondary button text</span><ColorRow value={currentTheme.buttonSecondaryText} onChange={(v) => update(editMode, 'buttonSecondaryText', v)} /></label>
          </div>
        ))}

        {renderSection('shadows', 'Shadows', (
          <div className="theme-grid">
            <label className="theme-full-width"><span>Shadow small</span><input type="text" value={currentTheme.shadowSm} onChange={(e) => update(editMode, 'shadowSm', e.target.value)} /></label>
            <label className="theme-full-width"><span>Shadow medium</span><input type="text" value={currentTheme.shadowMd} onChange={(e) => update(editMode, 'shadowMd', e.target.value)} /></label>
            <label className="theme-full-width"><span>Shadow large</span><input type="text" value={currentTheme.shadowLg} onChange={(e) => update(editMode, 'shadowLg', e.target.value)} /></label>
          </div>
        ))}

        {renderSection('transitions', 'Transitions', (
          <div className="theme-grid">
            <label><span>Fast</span><input type="text" value={currentTheme.transitionFast} onChange={(e) => update(editMode, 'transitionFast', e.target.value)} placeholder="0.2s ease" /></label>
            <label><span>Normal</span><input type="text" value={currentTheme.transitionNormal} onChange={(e) => update(editMode, 'transitionNormal', e.target.value)} placeholder="0.3s ease" /></label>
            <label><span>Slow</span><input type="text" value={currentTheme.transitionSlow} onChange={(e) => update(editMode, 'transitionSlow', e.target.value)} placeholder="0.5s ease" /></label>
          </div>
        ))}
      </div>
    </div>
  );
};

export default ThemeManagement;
