'use client';

import { useActionState, useState } from 'react';
import { guardarTema, type LogoResult } from '@/app/panel/empresa/actions';
import {
  THEME_LIST,
  isHexColor,
  type ThemePresetId,
} from '@/lib/funnel/themes';

export default function ThemePicker({
  themePreset,
  themeColor,
}: {
  themePreset: string;
  themeColor: string | null;
}) {
  const [state, formAction, pending] = useActionState<LogoResult | null, FormData>(
    guardarTema,
    null
  );

  const [preset, setPreset] = useState<ThemePresetId>(
    (THEME_LIST.find((t) => t.id === themePreset)?.id ?? 'pizarra') as ThemePresetId
  );
  const [usarColor, setUsarColor] = useState<boolean>(isHexColor(themeColor));
  const [color, setColor] = useState<string>(isHexColor(themeColor) ? themeColor : '#0066ff');

  const presetActual = THEME_LIST.find((t) => t.id === preset) ?? THEME_LIST[0];
  const colorEfectivo = usarColor && isHexColor(color) ? color : presetActual.primary;

  return (
    <form action={formAction} className="flex flex-col gap-5">
      <div className="grid grid-cols-2 sm:grid-cols-3 gap-3">
        {THEME_LIST.map((t) => {
          const activo = preset === t.id;
          return (
            <label
              key={t.id}
              className={
                'cursor-pointer rounded-xl border p-3 transition ' +
                (activo
                  ? 'border-primary-700 ring-1 ring-primary-700'
                  : 'border-gray-200 hover:border-gray-400')
              }
            >
              <input
                type="radio"
                name="themePreset"
                value={t.id}
                checked={activo}
                onChange={() => setPreset(t.id)}
                className="sr-only"
              />
              <span className="flex items-center gap-2">
                <span
                  className="h-6 w-6 shrink-0 rounded-full border border-black/10"
                  style={{ backgroundColor: t.primary }}
                  aria-hidden="true"
                />
                <span className="text-sm font-semibold text-gray-900">{t.label}</span>
              </span>
              <span className="mt-1.5 block text-xs leading-snug text-gray-500">
                {t.descripcion}
              </span>
              <span
                className={
                  'mt-1.5 inline-block text-[11px] font-medium ' +
                  (t.heading === 'serif' ? 'text-gray-400' : 'text-transparent')
                }
              >
                Titulares en serif
              </span>
            </label>
          );
        })}
      </div>

      <div className="rounded-xl border border-gray-200 p-4">
        <label className="flex items-center gap-2">
          <input
            type="checkbox"
            name="usarColor"
            checked={usarColor}
            onChange={(e) => setUsarColor(e.target.checked)}
            className="h-4 w-4 accent-[#2f5c46]"
          />
          <span className="text-sm font-medium text-gray-700">
            Usar un color de marca personalizado
          </span>
        </label>
        {usarColor && (
          <div className="mt-3 flex items-center gap-3">
            <input
              type="color"
              name="themeColor"
              value={color}
              onChange={(e) => setColor(e.target.value)}
              className="h-10 w-14 cursor-pointer rounded-lg border border-gray-200 bg-white p-1"
            />
            <span className="font-mono text-sm text-gray-600">{color}</span>
            <span className="text-xs text-gray-400">
              Sustituye el color del preset por el tuyo.
            </span>
          </div>
        )}
      </div>

      <div className="rounded-xl border border-gray-200 bg-gray-50 p-4">
        <p className="mb-3 text-xs font-medium uppercase tracking-wide text-gray-400">
          Vista previa
        </p>
        <div className="flex flex-wrap items-center gap-3">
          <span
            className="inline-flex items-center rounded-full px-3 py-1 text-xs font-semibold"
            style={{ backgroundColor: colorEfectivo, color: '#fff' }}
          >
            Presupuesto en 2 minutos
          </span>
          <button
            type="button"
            className="rounded-full px-4 py-2 text-sm font-semibold"
            style={{ backgroundColor: colorEfectivo, color: '#fff' }}
          >
            Pedir presupuesto
          </button>
          <span
            className={
              'text-lg font-black tracking-tight text-gray-900 ' +
              (presetActual.heading === 'serif' ? 'font-serif' : '')
            }
            style={presetActual.heading === 'serif' ? { fontFamily: 'Georgia, serif' } : undefined}
          >
            Tu cocina, reformada
          </span>
        </div>
      </div>

      <div className="flex items-center gap-3">
        <button
          type="submit"
          disabled={pending}
          className="inline-flex items-center justify-center rounded-lg bg-primary-700 px-4 py-2 text-sm font-semibold text-white transition hover:bg-primary-900 disabled:opacity-50"
        >
          {pending ? 'Guardando…' : 'Guardar tema'}
        </button>
        {state?.error && <span className="text-sm text-red-600">{state.error}</span>}
        {state?.ok && <span className="text-sm text-green-600">Tema guardado ✓</span>}
      </div>
    </form>
  );
}
