'use client';

import { useMemo, useState } from 'react';
import { useRouter } from 'next/navigation';
import toast from 'react-hot-toast';
import { Check, ExternalLink, RotateCcw, Undo2, AlertTriangle, XCircle, Loader2 } from 'lucide-react';
import { getApiErrorMessage } from '@/lib/utils/apiError';
import { themeFontVariables } from '@/lib/theme/fonts';
import {
  COLOR_META, DEFAULT_THEME, FONT_KEYS, FONT_OPTIONS, HEX_RE, PRESET_CATEGORIES, RADIUS_KEYS, RADIUS_OPTIONS,
  THEME_COLOR_KEYS, THEME_PRESETS, normalizeHex, presetToTheme, validateThemeContrast,
  type FontKey, type PresetCategory, type RadiusKey, type StorefrontTheme, type ThemeColorKey,
} from '@/lib/theme/storefrontTheme';
import ThemePreview from './ThemePreview';

interface ThemeSettingsFormProps {
  initialTheme: StorefrontTheme;
  updatedAt: string | null;
  canUpdate: boolean;
}

const CARD_STYLE = {
  background: 'var(--color-surface)',
  border: '1px solid var(--color-border)',
  borderRadius: 'var(--radius-card)',
} as const;
const LABEL_STYLE = { color: 'var(--color-text-secondary)' } as const;
const HINT_STYLE = { color: 'var(--color-text-tertiary)' } as const;
const INPUT_STYLE = {
  background: 'var(--color-surface-alt)',
  border: '1px solid var(--color-border)',
  color: 'var(--color-text)',
} as const;

const GROUPS = ['Brand', 'Base', 'Status'] as const;

function themesEqual(a: StorefrontTheme, b: StorefrontTheme): boolean {
  return JSON.stringify(a) === JSON.stringify(b);
}

// Which preset (if any) the current values exactly match.
function matchingPreset(theme: StorefrontTheme): string {
  const found = THEME_PRESETS.find((p) => {
    const t = presetToTheme(p);
    return themesEqual({ ...t, preset: '' }, { ...theme, preset: '' });
  });
  return found?.key ?? 'custom';
}

function SectionCard({ title, description, children }: { title: string; description?: string; children: React.ReactNode }) {
  return (
    <section className="p-5 md:p-6" style={CARD_STYLE}>
      <h2 className="text-base font-semibold" style={{ color: 'var(--color-text)' }}>{title}</h2>
      {description && <p className="text-xs mt-0.5 mb-4" style={HINT_STYLE}>{description}</p>}
      {!description && <div className="mb-4" />}
      {children}
    </section>
  );
}

export default function ThemeSettingsForm({ initialTheme, updatedAt, canUpdate }: ThemeSettingsFormProps) {
  const router = useRouter();
  const [saved, setSaved] = useState<StorefrontTheme>(initialTheme);
  const [savedAt, setSavedAt] = useState<string | null>(updatedAt);
  const [theme, setTheme] = useState<StorefrontTheme>(initialTheme);
  // Raw text of each hex field, so half-typed values don't fight the picker.
  const [hexDraft, setHexDraft] = useState<Record<ThemeColorKey, string>>({ ...initialTheme.colors });
  const [saving, setSaving] = useState(false);
  const [presetFilter, setPresetFilter] = useState<'All' | PresetCategory>('All');
  const visiblePresets = presetFilter === 'All'
    ? THEME_PRESETS
    : THEME_PRESETS.filter((p) => p.category === presetFilter);

  const issues = useMemo(() => validateThemeContrast(theme.colors), [theme.colors]);
  const issuesByField = useMemo(() => {
    const map: Partial<Record<ThemeColorKey, typeof issues>> = {};
    for (const i of issues) (map[i.field] ??= []).push(i);
    return map;
  }, [issues]);
  const hasErrors = issues.some((i) => i.severity === 'error');
  const dirty = !themesEqual(theme, saved);

  const applyTheme = (next: StorefrontTheme) => {
    const withPreset = { ...next, preset: matchingPreset(next) };
    setTheme(withPreset);
    setHexDraft({ ...withPreset.colors });
  };

  const setColor = (key: ThemeColorKey, value: string) => {
    setHexDraft((d) => ({ ...d, [key]: value }));
    if (HEX_RE.test(value.trim())) {
      applyTheme({ ...theme, colors: { ...theme.colors, [key]: normalizeHex(value) } });
    }
  };

  const handleSave = async () => {
    if (!canUpdate || hasErrors) return;
    setSaving(true);
    try {
      const res = await fetch('/api/theme-settings', {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(theme),
      });
      const data = await res.json();
      if (!res.ok || !data.success) {
        toast.error(getApiErrorMessage(data, 'Failed to save theme'));
        return;
      }
      setSaved(data.data.theme);
      setSavedAt(data.data.updatedAt);
      applyTheme(data.data.theme);
      toast.success(data.message || 'Theme saved');
      router.refresh();
    } catch {
      toast.error('Network error — please try again');
    } finally {
      setSaving(false);
    }
  };

  return (
    <div className={`${themeFontVariables} space-y-6`}>
      {/* Action bar */}
      <div className="sticky top-0 z-20 flex flex-wrap items-center justify-between gap-3 px-4 py-3 shadow-sm" style={CARD_STYLE}>
        <div className="text-sm" style={LABEL_STYLE}>
          {dirty ? (
            <span className="inline-flex items-center gap-2 font-medium" style={{ color: 'var(--color-warning)' }}>
              <span className="w-2 h-2 rounded-full" style={{ background: 'var(--color-warning)' }} />
              Unsaved changes — the store still shows the saved theme
            </span>
          ) : (
            <span className="inline-flex items-center gap-2">
              <Check size={15} style={{ color: 'var(--color-success)' }} />
              Live on the store{savedAt ? ` · saved ${new Date(savedAt).toLocaleString()}` : ''}
            </span>
          )}
        </div>
        <div className="flex flex-wrap items-center gap-2">
          <a
            href="/"
            target="_blank"
            rel="noopener noreferrer"
            className="inline-flex items-center gap-1.5 px-3 py-2 rounded-lg text-sm font-medium hover:opacity-80"
            style={{ ...INPUT_STYLE }}
          >
            <ExternalLink size={14} /> View store
          </a>
          {canUpdate && (
            <>
              <button
                type="button"
                onClick={() => applyTheme(presetToTheme(THEME_PRESETS[0]))}
                className="inline-flex items-center gap-1.5 px-3 py-2 rounded-lg text-sm font-medium hover:opacity-80"
                style={INPUT_STYLE}
                title="Load the original default theme (not saved until you click Save)"
              >
                <RotateCcw size={14} /> Reset to default
              </button>
              <button
                type="button"
                onClick={() => applyTheme(saved)}
                disabled={!dirty}
                className="inline-flex items-center gap-1.5 px-3 py-2 rounded-lg text-sm font-medium hover:opacity-80 disabled:opacity-40"
                style={INPUT_STYLE}
              >
                <Undo2 size={14} /> Discard
              </button>
              <button
                type="button"
                onClick={handleSave}
                disabled={!dirty || hasErrors || saving}
                className="inline-flex items-center gap-2 px-5 py-2 rounded-lg text-sm font-semibold text-white hover:opacity-90 disabled:opacity-40"
                style={{ background: 'var(--color-cta)' }}
                title={hasErrors ? 'Fix the highlighted colors first' : undefined}
              >
                {saving && <Loader2 size={14} className="animate-spin" />}
                {saving ? 'Saving…' : 'Save & publish'}
              </button>
            </>
          )}
        </div>
      </div>

      {!canUpdate && (
        <p className="text-sm px-4 py-3" style={{ ...CARD_STYLE, color: 'var(--color-text-secondary)' }}>
          You can view the theme but don&apos;t have permission to change it.
        </p>
      )}

      <div className="grid grid-cols-1 xl:grid-cols-[minmax(0,1fr)_420px] gap-6 items-start">
        <div className="space-y-6">
          {/* Presets */}
          <SectionCard title="Presets" description="Start from a ready-made look for your kind of store, then fine-tune anything below.">
            <div className="flex flex-wrap gap-2 mb-4" role="tablist" aria-label="Filter presets by store type">
              {(['All', ...PRESET_CATEGORIES] as const).map((category) => {
                const count = category === 'All'
                  ? THEME_PRESETS.length
                  : THEME_PRESETS.filter((p) => p.category === category).length;
                const active = presetFilter === category;
                return (
                  <button
                    key={category}
                    type="button"
                    role="tab"
                    aria-selected={active}
                    onClick={() => setPresetFilter(category)}
                    className="px-3 py-1.5 rounded-full text-xs font-medium transition"
                    style={active
                      ? { background: 'var(--color-cta)', color: 'white' }
                      : { ...INPUT_STYLE }}
                  >
                    {category} <span className="opacity-70">({count})</span>
                  </button>
                );
              })}
            </div>
            <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-3">
              {visiblePresets.map((preset) => {
                const active = theme.preset === preset.key;
                return (
                  <button
                    key={preset.key}
                    type="button"
                    disabled={!canUpdate}
                    onClick={() => applyTheme(presetToTheme(preset))}
                    className="text-left p-3 rounded-xl transition hover:shadow-md disabled:cursor-default"
                    style={{
                      background: 'var(--color-surface)',
                      border: active ? '2px solid var(--color-cta)' : '1px solid var(--color-border)',
                    }}
                  >
                    <div className="flex h-8 rounded-lg overflow-hidden mb-2.5">
                      {(['primary', 'secondary', 'text', 'background'] as const).map((k) => (
                        <span key={k} className="flex-1" style={{ background: preset.colors[k], boxShadow: 'inset 0 0 0 1px rgba(0,0,0,0.06)' }} />
                      ))}
                    </div>
                    <div className="flex items-center justify-between gap-2">
                      <span className="text-sm font-semibold" style={{ color: 'var(--color-text)' }}>{preset.name}</span>
                      {active && <Check size={15} style={{ color: 'var(--color-cta)' }} />}
                    </div>
                    <p className="text-[11px] leading-snug mt-0.5" style={HINT_STYLE}>{preset.description}</p>
                    <p className="text-[11px] mt-1" style={LABEL_STYLE}>
                      {FONT_OPTIONS[preset.fontHeading].label} · {RADIUS_OPTIONS[preset.radius].label}
                    </p>
                    {presetFilter === 'All' && (
                      <p className="text-[10px] mt-1 uppercase tracking-wide" style={HINT_STYLE}>{preset.category}</p>
                    )}
                  </button>
                );
              })}
            </div>
            {theme.preset === 'custom' && (
              <p className="text-xs mt-3" style={HINT_STYLE}>Current settings: <strong>Custom</strong> (based on your own choices).</p>
            )}
          </SectionCard>

          {/* Colors */}
          <SectionCard
            title="Colors"
            description="8 base colors. Hover shades, light tints, grays, borders and the footer color are generated from these automatically."
          >
            <div className="space-y-6">
              {GROUPS.map((group) => (
                <div key={group}>
                  <h3 className="text-xs font-semibold uppercase tracking-wider mb-3" style={HINT_STYLE}>{group}</h3>
                  <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                    {THEME_COLOR_KEYS.filter((k) => COLOR_META[k].group === group).map((key) => {
                      const fieldIssues = issuesByField[key] ?? [];
                      const invalidHex = !HEX_RE.test(hexDraft[key].trim());
                      const hasError = invalidHex || fieldIssues.some((i) => i.severity === 'error');
                      return (
                        <div key={key}>
                          <label htmlFor={`theme-${key}`} className="block text-sm font-medium" style={LABEL_STYLE}>
                            {COLOR_META[key].label}
                          </label>
                          <p className="text-[11px] mb-1.5" style={HINT_STYLE}>{COLOR_META[key].help}</p>
                          <div
                            className="flex items-center gap-2 rounded-lg p-1.5"
                            style={{ ...INPUT_STYLE, border: hasError ? '1px solid var(--color-danger)' : INPUT_STYLE.border }}
                          >
                            <input
                              type="color"
                              aria-label={`${COLOR_META[key].label} color picker`}
                              value={theme.colors[key].toLowerCase()}
                              disabled={!canUpdate}
                              onChange={(e) => setColor(key, e.target.value)}
                              className="w-9 h-9 shrink-0 cursor-pointer rounded-md border-0 bg-transparent p-0"
                            />
                            <input
                              id={`theme-${key}`}
                              type="text"
                              value={hexDraft[key]}
                              disabled={!canUpdate}
                              maxLength={7}
                              spellCheck={false}
                              onChange={(e) => setColor(key, e.target.value.startsWith('#') ? e.target.value : `#${e.target.value}`)}
                              onBlur={() => invalidHex && setHexDraft((d) => ({ ...d, [key]: theme.colors[key] }))}
                              className="w-full min-w-0 bg-transparent px-1 text-sm font-mono uppercase outline-none"
                              style={{ color: 'var(--color-text)' }}
                            />
                            {theme.colors[key] !== DEFAULT_THEME.colors[key] && canUpdate && (
                              <button
                                type="button"
                                onClick={() => setColor(key, DEFAULT_THEME.colors[key])}
                                className="shrink-0 p-1.5 rounded hover:opacity-70"
                                title={`Reset to default (${DEFAULT_THEME.colors[key]})`}
                                style={HINT_STYLE}
                              >
                                <RotateCcw size={13} />
                              </button>
                            )}
                          </div>
                          {invalidHex && (
                            <p className="text-xs mt-1" style={{ color: 'var(--color-danger)' }}>Enter a 6-digit hex color, e.g. #FF7A00</p>
                          )}
                          {fieldIssues.map((issue) => (
                            <p
                              key={issue.message}
                              className="flex items-start gap-1.5 text-xs mt-1"
                              style={{ color: issue.severity === 'error' ? 'var(--color-danger)' : 'var(--color-warning)' }}
                            >
                              {issue.severity === 'error' ? <XCircle size={13} className="shrink-0 mt-px" /> : <AlertTriangle size={13} className="shrink-0 mt-px" />}
                              {issue.message}
                            </p>
                          ))}
                        </div>
                      );
                    })}
                  </div>
                </div>
              ))}
            </div>
          </SectionCard>

          {/* Typography */}
          <SectionCard title="Typography" description="Fonts load only when selected — there's no cost to offering them.">
            <div className="grid grid-cols-1 md:grid-cols-2 gap-5">
              {([
                ['fontHeading', 'Headings font', 'The quick brown fox'],
                ['fontBody', 'Body font', 'Fresh products delivered to your door, every day.'],
              ] as const).map(([field, label, sample]) => (
                <div key={field}>
                  <label htmlFor={`theme-${field}`} className="block text-sm font-medium mb-1.5" style={LABEL_STYLE}>{label}</label>
                  <select
                    id={`theme-${field}`}
                    value={theme[field]}
                    disabled={!canUpdate}
                    onChange={(e) => applyTheme({ ...theme, [field]: e.target.value as FontKey })}
                    className="w-full px-3 py-2.5 rounded-lg text-sm outline-none"
                    style={INPUT_STYLE}
                  >
                    {(['Sans-serif', 'Serif'] as const).map((category) => (
                      <optgroup key={category} label={category}>
                        {FONT_KEYS.filter((k) => FONT_OPTIONS[k].category === category).map((k) => (
                          <option key={k} value={k}>{FONT_OPTIONS[k].label}</option>
                        ))}
                      </optgroup>
                    ))}
                  </select>
                  <p
                    className={`mt-2 px-3 py-2.5 rounded-lg ${field === 'fontHeading' ? 'text-xl font-bold' : 'text-sm'}`}
                    style={{ ...INPUT_STYLE, fontFamily: `var(${FONT_OPTIONS[theme[field]].cssVar}), sans-serif` }}
                  >
                    {sample}
                  </p>
                </div>
              ))}
            </div>
            <p className="text-[11px] mt-3" style={HINT_STYLE}>
              Urdu and Arabic text keeps using the device&apos;s native script font, since these fonts cover Latin only.
            </p>
          </SectionCard>

          {/* Radius */}
          <SectionCard title="Corners" description="How rounded buttons, cards, inputs and images are across the store.">
            <div className="grid grid-cols-2 sm:grid-cols-5 gap-3">
              {RADIUS_KEYS.map((key) => {
                const active = theme.radius === key;
                const r = `${0.75 * RADIUS_OPTIONS[key].scale}rem`;
                return (
                  <button
                    key={key}
                    type="button"
                    disabled={!canUpdate}
                    onClick={() => applyTheme({ ...theme, radius: key as RadiusKey })}
                    className="flex flex-col items-center gap-2 p-3 rounded-xl transition disabled:cursor-default"
                    style={{ background: 'var(--color-surface)', border: active ? '2px solid var(--color-cta)' : '1px solid var(--color-border)' }}
                  >
                    <span className="w-12 h-9" style={{ background: 'var(--color-surface-alt)', border: '2px solid var(--color-text-tertiary)', borderRadius: r }} />
                    <span className="text-xs font-medium" style={{ color: 'var(--color-text)' }}>{RADIUS_OPTIONS[key].label}</span>
                  </button>
                );
              })}
            </div>
          </SectionCard>
        </div>

        {/* Live preview */}
        <aside className="xl:sticky xl:top-20 space-y-2">
          <div className="flex items-center justify-between">
            <h2 className="text-sm font-semibold" style={{ color: 'var(--color-text)' }}>Live preview</h2>
            <span className="text-[11px]" style={HINT_STYLE}>Updates as you edit · not saved yet</span>
          </div>
          <ThemePreview theme={theme} fontClassName="" />
        </aside>
      </div>
    </div>
  );
}
