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

const CONTACT_KINDS: { value: string; label: string; placeholder: string }[] = [
  { value: 'email', label: 'Email', placeholder: 'you@example.com' },
  { value: 'mastodon', label: 'Mastodon', placeholder: 'https://mastodon.social/@you' },
  { value: 'bluesky', label: 'Bluesky', placeholder: 'https://bsky.app/profile/you.bsky.social' },
  { value: 'github', label: 'GitHub', placeholder: 'https://github.com/you' },
  { value: 'instagram', label: 'Instagram', placeholder: 'https://instagram.com/you' },
  { value: 'url', label: 'Other link', placeholder: 'https://…' },
];

export default function Settings() {
  const [config, setConfig] = useState<Partial<SiteConfig>>({});
  useEffect(() => {
    getConfig()
      .then(setConfig)
      .catch(() => showAlert('Failed to load settings from server.', 'error'));
  }, []);

  function showAlert(msg: string, type: 'success' | 'error') {
    notify(msg, type);
  }

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

  const contactLinks: ContactLink[] = config.contact_links ?? [];

  function updateContactLink(index: number, patch: Partial<ContactLink>) {
    const next = contactLinks.map((row, i) => (i === index ? { ...row, ...patch } : row));
    update('contact_links', next);
  }
  function addContactLink() {
    update('contact_links', [...contactLinks, { kind: 'email', label: 'Email', value: '' }]);
  }
  function removeContactLink(index: number) {
    update('contact_links', contactLinks.filter((_, i) => i !== index));
  }
  function moveContactLink(index: number, dir: -1 | 1) {
    const target = index + dir;
    if (target < 0 || target >= contactLinks.length) return;
    const next = [...contactLinks];
    [next[index], next[target]] = [next[target], next[index]];
    update('contact_links', next);
  }

  async function handleSubmit(e: React.SyntheticEvent) {
    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">
      <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="gothic">Gothic (cathedral nightfall)</option>
            <option value="breakcore">Breakcore (Y2K rot + neon glitch)</option>
            <option value="cybersigil">Cybersigil (dark frostbite + glitch)</option>
          </select>
          <p className="text-[10px] font-display italic text-[var(--subtext0)] mt-2 tracking-wider">Salon trio tuned for the gallery aesthetic. Breakcore swaps that for early-2000s web rot — hot magenta on CRT violet, acid green, scanline noise. Cybersigil is the moody cut — near-black ground, ice-cyan barbed sigil linework, bruised-magenta on contact, lingering chromatic glitch.</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(--peach)] pl-4">Contact</h2>
        <div>
          <label className="field-label">Intro text (shown above links)</label>
          <textarea
            value={config.contact_intro || ''}
            onChange={e => update('contact_intro', e.target.value)}
            rows={3}
            className="field-input"
            placeholder="A short note for visitors who want to reach out."
          />
        </div>

        <div className="space-y-4">
          <label className="field-label">Contact links</label>
          {contactLinks.length === 0 && (
            <p className="text-[11px] font-display italic text-[var(--subtext0)] tracking-wider">
              No links yet. Add one below to populate the contact page.
            </p>
          )}
          {contactLinks.map((row, i) => (
            <div
              key={i}
              className="grid md:grid-cols-[160px_1fr_1fr_auto] gap-3 items-end p-3 border border-[var(--surface2)]/60"
              style={{ borderRadius: 1 }}
            >
              <div>
                <label className="field-label">Kind</label>
                <select
                  value={row.kind}
                  onChange={e => updateContactLink(i, { kind: e.target.value })}
                  className="field-input font-display italic"
                >
                  {CONTACT_KINDS.map(k => (
                    <option key={k.value} value={k.value}>{k.label}</option>
                  ))}
                </select>
              </div>
              <div>
                <label className="field-label">Label</label>
                <input
                  type="text"
                  value={row.label}
                  onChange={e => updateContactLink(i, { label: e.target.value })}
                  className="field-input"
                  placeholder="Displayed name"
                />
              </div>
              <div>
                <label className="field-label">{row.kind === 'email' ? 'Address' : 'URL'}</label>
                <input
                  type="text"
                  value={row.value}
                  onChange={e => updateContactLink(i, { value: e.target.value })}
                  className="field-input"
                  placeholder={CONTACT_KINDS.find(k => k.value === row.kind)?.placeholder ?? ''}
                />
              </div>
              <div className="flex gap-1 items-center pb-1">
                <button
                  type="button"
                  onClick={() => moveContactLink(i, -1)}
                  disabled={i === 0}
                  className="chip disabled:opacity-30"
                  aria-label="Move up"
                  title="Move up"
                >↑</button>
                <button
                  type="button"
                  onClick={() => moveContactLink(i, 1)}
                  disabled={i === contactLinks.length - 1}
                  className="chip disabled:opacity-30"
                  aria-label="Move down"
                  title="Move down"
                >↓</button>
                <button
                  type="button"
                  onClick={() => removeContactLink(i)}
                  className="chip text-[var(--red)]"
                  aria-label="Remove link"
                  title="Remove"
                >✕</button>
              </div>
            </div>
          ))}
          <button
            type="button"
            onClick={addContactLink}
            className="btn btn--ghost btn--sm"
          >
            + Add contact link
          </button>
        </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 btn--primary">
        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>
  );
}
