import { useState, useEffect } from 'react';
import { getConfig, updateConfig, ApiError } from '../../../lib/api';
import type { SiteConfig } from '../../../lib/types';

export default function Settings() {
  const [config, setConfig] = useState<Partial<SiteConfig>>({});
  const [alert, setAlert] = useState<{ msg: string; type: 'success' | 'error' } | null>(null);

  useEffect(() => {
    getConfig()
      .then(setConfig)
      .catch(() => showAlert('Failed to load settings from server.', 'error'));
  }, []);

  function showAlert(msg: string, type: 'success' | 'error') {
    setAlert({ msg, type });
    setTimeout(() => setAlert(null), 5000);
  }

  function update(key: keyof SiteConfig, value: string) {
    setConfig(prev => ({ ...prev, [key]: value }));
  }

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault();
    try {
      await updateConfig(config);
      showAlert('Settings saved. Refresh to see changes.', 'success');
    } catch (e) {
      showAlert(e instanceof ApiError ? `Error: ${e.message}` : 'Failed to save settings.', 'error');
    }
  }

  return (
    <form onSubmit={handleSubmit} className="space-y-10">
      {alert && (
        <div
          className={`p-4 text-sm font-display italic text-center border ${
            alert.type === 'success'
              ? 'bg-[var(--green)]/15 text-[var(--green)] border-[var(--green)]/30'
              : 'bg-[var(--red)]/15 text-[var(--red)] border-[var(--red)]/30'
          }`}
          style={{ borderRadius: 1 }}
        >
          {alert.msg}
        </div>
      )}

      <section className="space-y-6">
        <h2 className="font-display italic text-2xl text-[var(--text)] border-l-2 border-[var(--mauve)] pl-4">Identity</h2>
        <div className="grid md:grid-cols-2 gap-6">
          <Field label="Gallery name (nav)" value={config.title || ''} onChange={v => update('title', v)} />
          <Field label="Nav subtitle" value={config.subtitle || ''} onChange={v => update('subtitle', v)} />
          <Field label="Welcome title (index)" value={config.welcome_title || ''} onChange={v => update('welcome_title', v)} />
          <Field label="Welcome subtitle" value={config.welcome_subtitle || ''} onChange={v => update('welcome_subtitle', v)} />
        </div>
        <Field label="Favicon URL" value={config.favicon || ''} onChange={v => update('favicon', v)} hint="Icon shown in browser tabs." />
      </section>

      <section className="space-y-6">
        <h2 className="font-display italic text-2xl text-[var(--text)] border-l-2 border-[var(--blue)] pl-4">Appearance</h2>
        <div>
          <label className="field-label">Theme</label>
          <select
            value={config.theme || 'salon'}
            onChange={e => update('theme', e.target.value)}
            className="field-input font-display italic"
          >
            <option value="salon">Salon (parchment, default)</option>
            <option value="salon-noir">Salon Noir (black gallery wall)</option>
            <option value="latte">Latte (light)</option>
            <option value="mocha">Mocha (dark)</option>
          </select>
          <p className="text-[10px] font-display italic text-[var(--subtext0)] mt-2 tracking-wider">Salon and Salon Noir are tuned for the gallery aesthetic.</p>
        </div>
        <div>
          <label className="field-label">Custom CSS</label>
          <textarea
            value={config.custom_css || ''}
            onChange={e => update('custom_css', e.target.value)}
            rows={4}
            className="field-input font-mono text-xs"
            placeholder="body { ... }"
          />
          <p className="text-[10px] font-display italic text-[var(--subtext0)] mt-2 tracking-wider">Injected globally — use sparingly.</p>
        </div>
      </section>

      <section className="space-y-6">
        <h2 className="font-display italic text-2xl text-[var(--text)] border-l-2 border-[var(--teal)] pl-4">Footer</h2>
        <Field label="Footer text" value={config.footer || ''} onChange={v => update('footer', v)} />
      </section>

      <button type="submit" className="btn-stamp">
        Save site settings
      </button>
    </form>
  );
}

function Field({ label, value, onChange, hint }: { label: string; value: string; onChange: (v: string) => void; hint?: string }) {
  return (
    <div>
      <label className="field-label">{label}</label>
      <input
        type="text"
        value={value}
        onChange={e => onChange(e.target.value)}
        required
        className="field-input"
      />
      {hint && <p className="text-[10px] font-display italic text-[var(--subtext0)] mt-2 tracking-wider">{hint}</p>}
    </div>
  );
}
