'use client';
import { useEffect, useState } from 'react';
import { Save, CheckCircle2, Check } from 'lucide-react';
import { useAuth } from '@/hooks/useAuth';
import { useApi } from '@/hooks/useApi';
import { themeService, themePresets } from '@/services/theme.service';
import { Card, CardHeader, CardBody } from '@/components/ui/Card';
import { Input } from '@/components/ui/Input';
import { Button } from '@/components/ui/Button';
import { PageHeader } from '@/components/layout/PageHeader';
import { LoadingState } from '@/components/ui/States';
import { cn } from '@/utils/cn';
import type { StoreTheme, ThemeStyle } from '@/types';

export default function TemaPage() {
  const { storeId } = useAuth();
  const { data, loading } = useApi(
    () => (storeId ? themeService.get(storeId) : Promise.resolve(null)),
    [storeId],
  );
  const [theme, setTheme] = useState<StoreTheme | null>(null);
  const [saved, setSaved] = useState(false);

  useEffect(() => { if (data) setTheme(data); }, [data]);

  if (loading || !theme) return <LoadingState />;

  function set<K extends keyof StoreTheme>(key: K, value: StoreTheme[K]) {
    setTheme((t) => (t ? { ...t, [key]: value } : t));
  }
  function applyPreset(style: ThemeStyle) {
    const preset = themePresets.find((p) => p.id === style);
    if (!preset) return;
    setTheme((t) =>
      t ? { ...t, style, primaryColor: preset.primaryColor, secondaryColor: preset.secondaryColor, buttonColor: preset.buttonColor } : t,
    );
  }
  async function save() {
    if (!theme || !storeId) return;
    await themeService.update(storeId, theme);
    setSaved(true);
    setTimeout(() => setSaved(false), 2500);
  }

  return (
    <>
      <PageHeader
        title="Tema da loja"
        subtitle="Personalize a aparência da sua loja pública"
        action={
          <Button onClick={save}>
            {saved ? <><CheckCircle2 className="h-4 w-4" /> Salvo</> : <><Save className="h-4 w-4" /> Salvar</>}
          </Button>
        }
      />

      <div className="grid gap-4 lg:grid-cols-3">
        <div className="space-y-4 lg:col-span-2">
          <Card>
            <CardHeader title="Modelo" />
            <CardBody className="grid gap-3 sm:grid-cols-3">
              {themePresets.map((p) => {
                const active = theme.style === p.id;
                return (
                  <button
                    key={p.id}
                    onClick={() => applyPreset(p.id)}
                    className={cn(
                      'relative rounded-xl border p-4 text-left transition-colors',
                      active ? 'border-brand-500 ring-2 ring-brand-100' : 'border-ink-200 hover:border-ink-300',
                    )}
                  >
                    {active && (
                      <span className="absolute right-3 top-3 flex h-5 w-5 items-center justify-center rounded-full bg-brand-600 text-white">
                        <Check className="h-3 w-3" />
                      </span>
                    )}
                    <div className="mb-3 flex gap-1.5">
                      <span className="h-6 w-6 rounded-full" style={{ background: p.primaryColor }} />
                      <span className="h-6 w-6 rounded-full" style={{ background: p.secondaryColor }} />
                      <span className="h-6 w-6 rounded-full" style={{ background: p.buttonColor }} />
                    </div>
                    <p className="font-medium text-ink-900">{p.name}</p>
                    <p className="mt-1 text-xs text-ink-500">{p.description}</p>
                  </button>
                );
              })}
            </CardBody>
          </Card>

          <Card>
            <CardHeader title="Cores" />
            <CardBody className="grid gap-4 sm:grid-cols-3">
              <ColorField label="Cor primária" value={theme.primaryColor} onChange={(v) => set('primaryColor', v)} />
              <ColorField label="Cor secundária" value={theme.secondaryColor} onChange={(v) => set('secondaryColor', v)} />
              <ColorField label="Cor dos botões" value={theme.buttonColor} onChange={(v) => set('buttonColor', v)} />
            </CardBody>
          </Card>

          <Card>
            <CardHeader title="Exibição" />
            <CardBody className="space-y-3">
              <label className="flex items-center gap-2 text-sm text-ink-700">
                <input type="checkbox" checked={theme.showCategories} onChange={(e) => set('showCategories', e.target.checked)} />
                Mostrar categorias na loja
              </label>
              <label className="flex items-center gap-2 text-sm text-ink-700">
                <input type="checkbox" checked={theme.showFeatured} onChange={(e) => set('showFeatured', e.target.checked)} />
                Mostrar seção de destaques
              </label>
              <Input label="Texto do rodapé" value={theme.footerText ?? ''} onChange={(e) => set('footerText', e.target.value)} />
            </CardBody>
          </Card>
        </div>

        {/* Pré-visualização */}
        <div className="lg:col-span-1">
          <Card>
            <CardHeader title="Pré-visualização" />
            <CardBody>
              <div className="overflow-hidden rounded-xl border border-ink-200">
                <div className="p-4 text-white" style={{ background: theme.primaryColor }}>
                  <p className="text-sm font-semibold">Sua Loja</p>
                  <p className="text-xs opacity-80">catálogo online</p>
                </div>
                <div className="space-y-3 bg-white p-4">
                  {theme.showCategories && (
                    <div className="flex gap-2">
                      {['Tudo', 'Novidades'].map((c) => (
                        <span key={c} className="rounded-full px-2.5 py-0.5 text-xs" style={{ background: `${theme.primaryColor}1a`, color: theme.primaryColor }}>{c}</span>
                      ))}
                    </div>
                  )}
                  <div className="rounded-lg border border-ink-100 p-3">
                    <div className="mb-2 h-20 rounded-md bg-ink-100" />
                    <p className="text-sm font-medium text-ink-900">Produto exemplo</p>
                    <p className="text-sm" style={{ color: theme.secondaryColor }}>R$ 99,90</p>
                    <button className="mt-2 w-full rounded-md py-1.5 text-xs font-medium text-white" style={{ background: theme.buttonColor }}>
                      Comprar
                    </button>
                  </div>
                  <p className="pt-1 text-center text-[10px] text-ink-400">{theme.footerText || 'Rodapé da loja'}</p>
                </div>
              </div>
            </CardBody>
          </Card>
        </div>
      </div>
    </>
  );
}

function ColorField({ label, value, onChange }: { label: string; value: string; onChange: (v: string) => void }) {
  return (
    <div className="space-y-1.5">
      <label className="block text-sm font-medium text-ink-700">{label}</label>
      <div className="flex items-center gap-2">
        <input type="color" value={value} onChange={(e) => onChange(e.target.value)} className="h-10 w-12 cursor-pointer rounded-lg border border-ink-200" />
        <input value={value} onChange={(e) => onChange(e.target.value)} className="h-10 flex-1 rounded-lg border border-ink-200 px-3 font-mono text-sm" />
      </div>
    </div>
  );
}
