'use client';

import { useState } from 'react';
import type { StoreSite, StoreSiteTheme } from '@alqove/api-client';
import { DEFAULT_THEME } from '@/components/storefront/theme';
import { firstError, useSiteMutations } from './use-store-site';
import { ErrorText, Field, inputCls, Panel, PrimaryButton } from './ui';

const COLOR_FIELDS: { key: keyof StoreSiteTheme; label: string; hint?: string }[] = [
  { key: 'primary_color', label: 'Primary', hint: 'Buttons and links.' },
  { key: 'accent_color', label: 'Accent', hint: 'Badges and highlights.' },
  { key: 'background_color', label: 'Page background' },
  { key: 'text_color', label: 'Text' },
];

export function DesignPanel({ storeId, site }: { storeId: string; site: StoreSite }) {
  const { updateSite } = useSiteMutations(storeId);
  const [theme, setTheme] = useState<StoreSiteTheme>({ ...DEFAULT_THEME, ...(site.theme ?? {}) });
  const [savedAt, setSavedAt] = useState<string | null>(null);

  function save() {
    updateSite.mutate(
      { theme },
      { onSuccess: () => setSavedAt(new Date().toLocaleTimeString()) },
    );
  }

  return (
    <Panel
      title="Design"
      description="Colours and type for your whole site. Changes apply to every page."
      actions={
        <div className="flex items-center gap-3">
          {savedAt && <span className="text-xs text-ink/60">Saved at {savedAt}</span>}
          <PrimaryButton onClick={save} disabled={updateSite.isPending}>
            {updateSite.isPending ? 'Saving…' : 'Save design'}
          </PrimaryButton>
        </div>
      }
    >
      <div className="grid gap-4 sm:grid-cols-2">
        {COLOR_FIELDS.map(({ key, label, hint }) => (
          <Field key={key} label={label} hint={hint}>
            <div className="flex items-center gap-2">
              <input
                type="color"
                aria-label={`${label} colour`}
                value={(theme[key] as string) ?? '#000000'}
                onChange={(e) => setTheme({ ...theme, [key]: e.target.value })}
                className="h-9 w-12 cursor-pointer rounded border border-forest/20"
              />
              <input
                className={inputCls}
                value={(theme[key] as string) ?? ''}
                onChange={(e) => setTheme({ ...theme, [key]: e.target.value })}
              />
            </div>
          </Field>
        ))}

        <Field label="Typeface">
          <select
            className={inputCls}
            value={theme.font ?? 'sans'}
            onChange={(e) => setTheme({ ...theme, font: e.target.value as StoreSiteTheme['font'] })}
          >
            <option value="sans">Sans-serif</option>
            <option value="serif">Serif</option>
            <option value="mono">Monospace</option>
          </select>
        </Field>

        <Field label="Corner style">
          <select
            className={inputCls}
            value={theme.corner_radius ?? 'md'}
            onChange={(e) =>
              setTheme({ ...theme, corner_radius: e.target.value as StoreSiteTheme['corner_radius'] })
            }
          >
            <option value="none">Square</option>
            <option value="sm">Slightly rounded</option>
            <option value="md">Rounded</option>
            <option value="lg">Very rounded</option>
          </select>
        </Field>

        <Field label="Header style">
          <select
            className={inputCls}
            value={theme.header_style ?? 'solid'}
            onChange={(e) =>
              setTheme({ ...theme, header_style: e.target.value as StoreSiteTheme['header_style'] })
            }
          >
            <option value="solid">Solid with a border</option>
            <option value="minimal">Minimal, no border</option>
            <option value="transparent">Transparent over the hero</option>
          </select>
        </Field>
      </div>

      <ErrorText>{firstError(updateSite.error)}</ErrorText>
    </Panel>
  );
}
