const SOCIAL_PLATFORMS = ['twitter','linkedin','instagram','github','dribbble','facebook','youtube','tiktok','behance'];

function ToggleRow({ label, description, defaultChecked }) {
  const [checked, setChecked] = React.useState(defaultChecked);
  return (
    <div className="toggle-row">
      <div>
        <div className="toggle-row__label">{label}</div>
        {description && <div className="toggle-row__desc">{description}</div>}
      </div>
      <label className="toggle">
        <input type="checkbox" checked={checked} onChange={(e) => setChecked(e.target.checked)} />
        <span className="toggle-slider"></span>
      </label>
    </div>
  );
}

function Settings() {
  const [tab,          setTab]          = React.useState('general');
  const [apiUrl,       setApiUrl]       = React.useState('');
  const [socialLinks,  setSocialLinks]  = React.useState([]);
  const [savingApi,    setSavingApi]    = React.useState(false);
  const [savingSocial, setSavingSocial] = React.useState(false);

  React.useEffect(() => {
    db.from('content_sections')
      .select('section_name, content_json')
      .in('section_name', ['settings', 'social_links'])
      .then(({ data }) => {
        if (!data) return;
        const settings = data.find(r => r.section_name === 'settings');
        const social   = data.find(r => r.section_name === 'social_links');
        if (settings?.content_json?.apiBaseUrl) setApiUrl(settings.content_json.apiBaseUrl);
        if (Array.isArray(social?.content_json)) setSocialLinks(social.content_json);
      });
  }, []);

  const saveApiUrl = async () => {
    setSavingApi(true);
    await saveSection('settings', { apiBaseUrl: apiUrl });
    setTimeout(() => setSavingApi(false), 1600);
  };

  const saveSocialLinks = async () => {
    setSavingSocial(true);
    await saveSection('social_links', socialLinks);
    setTimeout(() => setSavingSocial(false), 1600);
  };

  const addLink    = ()          => setSocialLinks(p => [...p, { id: String(Date.now()), platform: 'twitter', url: '' }]);
  const removeLink = (id)        => setSocialLinks(p => p.filter(l => l.id !== id));
  const updateLink = (id, k, v)  => setSocialLinks(p => p.map(l => l.id === id ? { ...l, [k]: v } : l));

  return (
    <div>
      <h1 className="page-title">Settings</h1>
      <p className="page-subtitle">Workspace configuration, social links, and feature flags</p>

      <div className="tab-bar" style={{ marginBottom: 'var(--space-6)' }}>
        {[['general', 'General'], ['social', 'Social Links'], ['flags', 'Feature Flags']].map(([id, label]) => (
          <button key={id} className={`tab${tab === id ? ' active' : ''}`} onClick={() => setTab(id)}>{label}</button>
        ))}
      </div>

      {/* ── General ── */}
      {tab === 'general' && (
        <>
          <div className="settings-section">
            <div className="settings-section__title">General</div>
            <div className="field"><label>Studio Name</label><input type="text" defaultValue="Blan Studio" /></div>
            <div className="field"><label>Admin Email</label><input type="email" defaultValue="contact.benadra@gmail.com" /></div>
            <div className="field"><label>Contact Phone</label><input type="text" placeholder="+1 (000) 000-0000" /></div>
            <div className="field"><label>Website URL</label><input type="text" defaultValue="https://blan.studio" /></div>
          </div>

          <div className="settings-section">
            <div className="settings-section__title">API</div>
            <div className="field">
              <label>API Base URL</label>
              <input
                type="text"
                value={apiUrl}
                onChange={e => setApiUrl(e.target.value)}
                placeholder="https://your-api.vercel.app"
              />
            </div>
            <button className="btn btn--primary" onClick={saveApiUrl}>
              {savingApi ? 'Saved' : 'Save API URL'}
            </button>
          </div>
        </>
      )}

      {/* ── Social Links ── */}
      {tab === 'social' && (
        <div className="settings-section">
          <div className="settings-section__title">Social Links</div>
          <p style={{ fontSize: 'var(--fs-body-sm)', color: 'var(--fg-secondary)', marginBottom: 'var(--space-5)' }}>
            Links with a URL will appear in the footer. Leave URL empty to hide.
          </p>

          {socialLinks.length === 0 && (
            <p style={{ fontSize: 'var(--fs-body-sm)', color: 'var(--fg-secondary)', marginBottom: 'var(--space-4)' }}>
              No links yet. Click "+ Add link" to start.
            </p>
          )}

          {socialLinks.map(link => (
            <div key={link.id} style={{ display: 'flex', gap: 'var(--space-3)', alignItems: 'flex-end', marginBottom: 'var(--space-3)', flexWrap: 'wrap' }}>
              <div className="field" style={{ width: 130, marginBottom: 0 }}>
                <label>Platform</label>
                <select value={link.platform} onChange={e => updateLink(link.id, 'platform', e.target.value)}>
                  {SOCIAL_PLATFORMS.map(p => <option key={p} value={p}>{p}</option>)}
                </select>
              </div>
              <div className="field" style={{ flex: 1, minWidth: 140, marginBottom: 0 }}>
                <label>URL</label>
                <input type="url" value={link.url} onChange={e => updateLink(link.id, 'url', e.target.value)} placeholder="https://..." />
              </div>
              <div className="field" style={{ width: 120, marginBottom: 0 }}>
                <label>Custom icon <span style={{ fontSize: 'var(--fs-caption)', color: 'var(--fg-secondary)', fontWeight: 'var(--fw-regular)', textTransform: 'none', letterSpacing: 0 }}>URL or base64</span></label>
                {link.icon_url ? (
                  <div style={{ display: 'flex', alignItems: 'center', gap: 'var(--space-2)' }}>
                    <img src={link.icon_url} alt="" style={{ width: 20, height: 20, objectFit: 'contain', borderRadius: 4, border: '1px solid var(--border-subtle)' }} onError={e => e.target.style.display='none'} />
                    <button className="icon-btn" title="Clear" onClick={() => updateLink(link.id, 'icon_url', '')}>×</button>
                  </div>
                ) : (
                  <ImageUpload value={link.icon_url || ''} onChange={v => updateLink(link.id, 'icon_url', v)} uploadLabel="Upload icon" />
                )}
              </div>
              <button className="icon-btn icon-btn--danger" style={{ marginBottom: 1 }} title="Remove" onClick={() => removeLink(link.id)}>
                <svg width="13" height="13" viewBox="0 0 13 13" fill="none">
                  <path d="M1.5 3h10M5 3V1.5h3V3M4 5v5M6.5 5v5M9 5v5M2 3l.8 8.5h7.4L11 3" stroke="currentColor" strokeWidth="1.3" strokeLinecap="round" strokeLinejoin="round"/>
                </svg>
              </button>
            </div>
          ))}

          <div className="editor-actions" style={{ marginTop: 'var(--space-4)' }}>
            <button className="btn btn--ghost" style={{ fontSize: 'var(--fs-caption)', padding: '5px var(--space-3)' }} onClick={addLink}>
              + Add link
            </button>
            <button className="btn btn--primary" onClick={saveSocialLinks}>
              {savingSocial ? 'Saved' : 'Save Social Links'}
            </button>
          </div>
        </div>
      )}

      {/* ── Feature Flags ── */}
      {tab === 'flags' && (
        <div className="settings-section">
          <div className="settings-section__title">Feature Flags</div>
          <ToggleRow label="Request Form"   description="Accept new requests from the landing page"       defaultChecked={true}  />
          <ToggleRow label="Client Portal"  description="Allow clients to log in and track their requests" defaultChecked={false} />
          <ToggleRow label="Talent Access"  description="Allow talent to log in and view assigned work"    defaultChecked={false} />
          <ToggleRow label="Reviews Display" description="Show reviews section on the landing page"        defaultChecked={true}  />
          <ToggleRow label="FAQ Display"    description="Show FAQ section on the landing page"             defaultChecked={true}  />
        </div>
      )}
    </div>
  );
}
