'use client';

import { EditorFeedback, LoadState } from '@/components/content/feedback';
import { ImageField } from '@/components/content/image-field';
import { apiSend, useAdminQuery } from '@/lib/api';
import { zodResolver } from '@hookform/resolvers/zod';
import { Button, Card, Group, Stack, Text, Textarea, TextInput, Title } from '@mantine/core';
import { useEffect, useState, type FormEvent, type ReactNode } from 'react';
import { useFieldArray, useForm, type FieldValues } from 'react-hook-form';
import { z } from 'zod';

const required = (label: string, max: number) =>
  z.string().min(2, { error: `${label} precisa ter entre 2 e ${max} caracteres.` }).max(max, { error: `${label} precisa ter entre 2 e ${max} caracteres.` });

const href = z
  .string()
  .min(1, { error: 'Informe o link.' })
  .max(200, { error: 'O link está longo demais.' })
  .refine((value) => value.trim().startsWith('/') || value.trim().startsWith('#'), { error: 'O link precisa começar com / ou #.' });

function Block({ title, hint, children }: { title: string; hint: string; children: ReactNode }) {
  return (
    <Card className="border border-line bg-elevated" padding="lg" radius="md" withBorder>
      <Stack gap="lg">
        <Stack gap={4}>
          <Title order={2} size="h4">
            Bloco - {title}
          </Title>
          <Text c="var(--mantine-color-muted)" size="sm">
            {hint}
          </Text>
        </Stack>
        {children}
      </Stack>
    </Card>
  );
}

function SaveBar({ saving }: { saving: boolean }) {
  return (
    <Button loading={saving} radius="md" type="submit">
      Salvar bloco
    </Button>
  );
}

export function AboutBlockEditor() {
  const query = useAdminQuery<{
    eyebrow: string;
    title: string;
    lead: string;
    ctaLabel: string;
    ctaHref: string;
    imageUrl: string;
    imageAlt: string;
  }>('/admin/home/about');
  const [file, setFile] = useState<File | null>(null);
  const [error, setError] = useState('');
  const [saved, setSaved] = useState(false);
  const [saving, setSaving] = useState(false);
  const form = useForm({
    defaultValues: { eyebrow: '', title: '', lead: '', ctaLabel: '', ctaHref: '', imageUrl: '', imageAlt: '' },
    resolver: zodResolver(
      z.object({
        eyebrow: required('O texto de apoio', 80),
        title: required('O título', 200),
        lead: required('O texto', 800),
        ctaLabel: required('O botão', 80),
        ctaHref: href,
        imageUrl: z.string(),
        imageAlt: required('A descrição da imagem', 240),
      }),
    ),
  });

  useEffect(() => {
    if (!query.data) return;
    form.reset(query.data);
    setFile(null);
  }, [query.data, form]);

  async function onSubmit(values: FieldValues) {
    if (!values.imageUrl && !file) {
      setError('A imagem do bloco é obrigatória.');
      return;
    }
    const body = new FormData();
    for (const [key, value] of Object.entries(values)) body.set(key, String(value ?? ''));
    if (file) body.set('image', file);
    await send('/admin/home/about', query, body, setSaving, setError, setSaved);
  }

  return (
    <Block title="Sobre a Hidrotintas" hint="Texto e foto da seção sobre a marca. Uma quebra de linha no título vira uma nova linha no site.">
      <LoadState error={query.error} loading={query.loading} />
      {query.data && (
        <Form form={form as never} onSubmit={onSubmit} error={error} setError={setError} saved={saved}>
          <TextInput label="Texto de apoio" {...form.register('eyebrow')} error={form.formState.errors.eyebrow?.message} />
          <Textarea label="Título" minRows={3} {...form.register('title')} error={form.formState.errors.title?.message} />
          <Textarea label="Texto" minRows={4} {...form.register('lead')} error={form.formState.errors.lead?.message} />
          <TextInput label="Botão" {...form.register('ctaLabel')} error={form.formState.errors.ctaLabel?.message} />
          <TextInput label="Link do botão" {...form.register('ctaHref')} error={form.formState.errors.ctaHref?.message} />
          <Textarea label="Descrição da imagem" minRows={2} {...form.register('imageAlt')} error={form.formState.errors.imageAlt?.message} />
          <ImageField file={file} imageUrl={form.watch('imageUrl')} onFile={setFile} />
          <SaveBar saving={saving} />
        </Form>
      )}
    </Block>
  );
}

export function ProductsBlockEditor() {
  const query = useAdminQuery<{ eyebrow: string; title: string; allLabel: string; allHref: string; moreLabel: string }>('/admin/home/products');
  const [error, setError] = useState('');
  const [saved, setSaved] = useState(false);
  const [saving, setSaving] = useState(false);
  const form = useForm({
    defaultValues: { eyebrow: '', title: '', allLabel: '', allHref: '', moreLabel: '' },
    resolver: zodResolver(
      z.object({
        eyebrow: required('O texto de apoio', 80),
        title: required('O título', 200),
        allLabel: required('O link', 80),
        allHref: href,
        moreLabel: required('O texto do card', 80),
      }),
    ),
  });

  useEffect(() => {
    if (query.data) form.reset(query.data);
  }, [query.data, form]);

  async function onSubmit(values: FieldValues) {
    await send('/admin/home/products', query, JSON.stringify(values), setSaving, setError, setSaved);
  }

  return (
    <Block title="Nossos produtos" hint="Os cards vêm das categorias. Aqui ficam o título da seção e os textos dos links.">
      <LoadState error={query.error} loading={query.loading} />
      {query.data && (
        <Form form={form as never} onSubmit={onSubmit} error={error} setError={setError} saved={saved}>
          <TextInput label="Texto de apoio" {...form.register('eyebrow')} error={form.formState.errors.eyebrow?.message} />
          <Textarea label="Título" minRows={2} {...form.register('title')} error={form.formState.errors.title?.message} />
          <TextInput label="Link" {...form.register('allLabel')} error={form.formState.errors.allLabel?.message} />
          <TextInput label="Endereço do link" {...form.register('allHref')} error={form.formState.errors.allHref?.message} />
          <TextInput label="Texto do card" {...form.register('moreLabel')} error={form.formState.errors.moreLabel?.message} />
          <SaveBar saving={saving} />
        </Form>
      )}
    </Block>
  );
}

export function SimulatorBlockEditor() {
  const query = useAdminQuery<{
    eyebrow: string;
    title: string;
    titleHighlight: string;
    lead: string;
    ctaLabel: string;
    ctaHref: string;
    imageUrl: string;
    pickerLabel: string;
    swatches: { name: string; hex: string }[];
  }>('/admin/home/simulator');
  const [file, setFile] = useState<File | null>(null);
  const [error, setError] = useState('');
  const [saved, setSaved] = useState(false);
  const [saving, setSaving] = useState(false);
  const form = useForm({
    defaultValues: { eyebrow: '', title: '', titleHighlight: '', lead: '', ctaLabel: '', ctaHref: '', imageUrl: '', pickerLabel: '', swatches: [] as { name: string; hex: string }[] },
    resolver: zodResolver(
      z.object({
        eyebrow: required('O texto de apoio', 80),
        title: required('O título', 200),
        titleHighlight: z.string().max(80),
        lead: required('O texto', 600),
        ctaLabel: required('O botão', 80),
        ctaHref: href,
        imageUrl: z.string(),
        pickerLabel: required('O rótulo das cores', 40),
        swatches: z.array(z.object({ name: required('O nome da cor', 40), hex: z.string().regex(/^#[0-9a-fA-F]{6}$/, { error: 'Use um hexadecimal, como #e07a32.' }) })).min(1).max(8),
      }),
    ),
  });
  const swatches = useFieldArray({ control: form.control, name: 'swatches' });

  useEffect(() => {
    if (!query.data) return;
    form.reset({ ...query.data, swatches: query.data.swatches.map((item) => ({ name: item.name, hex: item.hex })) });
    setFile(null);
  }, [query.data, form]);

  async function onSubmit(values: FieldValues) {
    if (!values.imageUrl && !file) {
      setError('A imagem do bloco é obrigatória.');
      return;
    }
    const body = new FormData();
    for (const key of ['eyebrow', 'title', 'titleHighlight', 'lead', 'ctaLabel', 'ctaHref', 'imageUrl', 'pickerLabel']) {
      body.set(key, String(values[key] ?? ''));
    }
    body.set('swatches', JSON.stringify(values.swatches));
    if (file) body.set('image', file);
    await send('/admin/home/simulator', query, body, setSaving, setError, setSaved);
  }

  return (
    <Block title="Simulador de ambientes" hint="Foto, textos e cores. O trecho em destaque fica na cor clara do título.">
      <LoadState error={query.error} loading={query.loading} />
      {query.data && (
        <Form form={form as never} onSubmit={onSubmit} error={error} setError={setError} saved={saved}>
          <TextInput label="Texto de apoio" {...form.register('eyebrow')} error={form.formState.errors.eyebrow?.message} />
          <Textarea label="Título" minRows={2} {...form.register('title')} error={form.formState.errors.title?.message} />
          <TextInput label="Trecho em destaque" {...form.register('titleHighlight')} error={form.formState.errors.titleHighlight?.message} />
          <Textarea label="Texto" minRows={3} {...form.register('lead')} error={form.formState.errors.lead?.message} />
          <TextInput label="Botão" {...form.register('ctaLabel')} error={form.formState.errors.ctaLabel?.message} />
          <TextInput label="Link do botão" {...form.register('ctaHref')} error={form.formState.errors.ctaHref?.message} />
          <TextInput label="Rótulo das cores" {...form.register('pickerLabel')} error={form.formState.errors.pickerLabel?.message} />
          <ImageField file={file} imageUrl={form.watch('imageUrl')} onFile={setFile} />
          {swatches.fields.map((item, index) => (
            <Group align="flex-end" grow key={item.id}>
              <TextInput label={`Cor ${index + 1}`} {...form.register(`swatches.${index}.name`)} error={form.formState.errors.swatches?.[index]?.name?.message} />
              <TextInput label="Hexadecimal" {...form.register(`swatches.${index}.hex`)} error={form.formState.errors.swatches?.[index]?.hex?.message} />
              <Button color="red" onClick={() => swatches.remove(index)} radius="md" type="button" variant="subtle">
                Remover
              </Button>
            </Group>
          ))}
          <Group>
            <Button onClick={() => swatches.append({ name: '', hex: '#000000' })} radius="md" type="button" variant="default">
              Adicionar cor
            </Button>
            <SaveBar saving={saving} />
          </Group>
        </Form>
      )}
    </Block>
  );
}

export function CalculatorBlockEditor() {
  const query = useAdminQuery<{
    eyebrow: string;
    title: string;
    lead: string;
    ctaLabel: string;
    ctaHref: string;
    imageUrl: string;
    imageAlt: string;
    infos: { label: string; value: string }[];
  }>('/admin/home/calculator');
  const [file, setFile] = useState<File | null>(null);
  const [error, setError] = useState('');
  const [saved, setSaved] = useState(false);
  const [saving, setSaving] = useState(false);
  const form = useForm({
    defaultValues: { eyebrow: '', title: '', lead: '', ctaLabel: '', ctaHref: '', imageUrl: '', imageAlt: '', infos: [] as { label: string; value: string }[] },
    resolver: zodResolver(
      z.object({
        eyebrow: required('O texto de apoio', 80),
        title: required('O título', 200),
        lead: required('O texto', 800),
        ctaLabel: required('O botão', 80),
        ctaHref: href,
        imageUrl: z.string(),
        imageAlt: required('A descrição da imagem', 240),
        infos: z.array(z.object({ label: required('O rótulo', 40), value: required('O valor', 40) })).min(1).max(4),
      }),
    ),
  });
  const infos = useFieldArray({ control: form.control, name: 'infos' });

  useEffect(() => {
    if (!query.data) return;
    form.reset({ ...query.data, infos: query.data.infos.map((item) => ({ label: item.label, value: item.value })) });
    setFile(null);
  }, [query.data, form]);

  async function onSubmit(values: FieldValues) {
    if (!values.imageUrl && !file) {
      setError('A imagem do bloco é obrigatória.');
      return;
    }
    const body = new FormData();
    for (const key of ['eyebrow', 'title', 'lead', 'ctaLabel', 'ctaHref', 'imageUrl', 'imageAlt']) body.set(key, String(values[key] ?? ''));
    body.set('infos', JSON.stringify(values.infos));
    if (file) body.set('image', file);
    await send('/admin/home/calculator', query, body, setSaving, setError, setSaved);
  }

  return (
    <Block title="Calculadora de rendimento" hint="Os ícones do cartão continuam os da página. Aqui entram rótulo, valor, texto e foto.">
      <LoadState error={query.error} loading={query.loading} />
      {query.data && (
        <Form form={form as never} onSubmit={onSubmit} error={error} setError={setError} saved={saved}>
          <TextInput label="Texto de apoio" {...form.register('eyebrow')} error={form.formState.errors.eyebrow?.message} />
          <Textarea label="Título" minRows={2} {...form.register('title')} error={form.formState.errors.title?.message} />
          <Textarea label="Texto" minRows={3} {...form.register('lead')} error={form.formState.errors.lead?.message} />
          <TextInput label="Botão" {...form.register('ctaLabel')} error={form.formState.errors.ctaLabel?.message} />
          <TextInput label="Link do botão" {...form.register('ctaHref')} error={form.formState.errors.ctaHref?.message} />
          <Textarea label="Descrição da imagem" minRows={2} {...form.register('imageAlt')} error={form.formState.errors.imageAlt?.message} />
          <ImageField file={file} imageUrl={form.watch('imageUrl')} onFile={setFile} />
          {infos.fields.map((item, index) => (
            <Group align="flex-end" grow key={item.id}>
              <TextInput label={`Rótulo ${index + 1}`} {...form.register(`infos.${index}.label`)} error={form.formState.errors.infos?.[index]?.label?.message} />
              <TextInput label="Valor" {...form.register(`infos.${index}.value`)} error={form.formState.errors.infos?.[index]?.value?.message} />
              <Button color="red" onClick={() => infos.remove(index)} radius="md" type="button" variant="subtle">
                Remover
              </Button>
            </Group>
          ))}
          <Group>
            <Button disabled={infos.fields.length >= 4} onClick={() => infos.append({ label: '', value: '' })} radius="md" type="button" variant="default">
              Adicionar informação
            </Button>
            <SaveBar saving={saving} />
          </Group>
        </Form>
      )}
    </Block>
  );
}

export function InspireBlockEditor() {
  const query = useAdminQuery<{
    eyebrow: string;
    title: string;
    allLabel: string;
    allHref: string;
    moreLabel: string;
    items: { name: string; text: string; href: string; imageUrl: string }[];
  }>('/admin/home/inspire');
  const [files, setFiles] = useState<Record<number, File | null>>({});
  const [error, setError] = useState('');
  const [saved, setSaved] = useState(false);
  const [saving, setSaving] = useState(false);
  const form = useForm({
    defaultValues: { eyebrow: '', title: '', allLabel: '', allHref: '', moreLabel: '', items: [] as { name: string; text: string; href: string; imageUrl: string }[] },
    resolver: zodResolver(
      z.object({
        eyebrow: required('O texto de apoio', 80),
        title: required('O título', 200),
        allLabel: required('O link', 80),
        allHref: href,
        moreLabel: required('O texto do card', 40),
        items: z
          .array(z.object({ name: required('O título do conteúdo', 120), text: required('O texto do conteúdo', 240), href, imageUrl: z.string() }))
          .min(1)
          .max(8),
      }),
    ),
  });
  const items = useFieldArray({ control: form.control, name: 'items' });

  useEffect(() => {
    if (!query.data) return;
    form.reset({ ...query.data, items: query.data.items.map((item) => ({ name: item.name, text: item.text, href: item.href, imageUrl: item.imageUrl })) });
    setFiles({});
  }, [query.data, form]);

  async function onSubmit(values: FieldValues) {
    const rows = values.items as { name: string; text: string; href: string; imageUrl: string }[];
    if (rows.some((item, index) => !item.imageUrl && !files[index])) {
      setError('Cada conteúdo precisa de uma imagem.');
      return;
    }
    const body = new FormData();
    for (const key of ['eyebrow', 'title', 'allLabel', 'allHref', 'moreLabel']) body.set(key, String(values[key] ?? ''));
    body.set(
      'items',
      JSON.stringify(
        rows.map((item, index) => {
          const fileKey = files[index] ? `item-${index}` : undefined;
          if (fileKey && files[index]) body.set(fileKey, files[index] as File);
          return { ...item, fileKey };
        }),
      ),
    );
    await send('/admin/home/inspire', query, body, setSaving, setError, setSaved);
  }

  return (
    <Block title="Inspire-se" hint="Título da seção e os cards de conteúdo. JPG, PNG ou WebP, até 8 MB.">
      <LoadState error={query.error} loading={query.loading} />
      {query.data && (
        <Form form={form as never} onSubmit={onSubmit} error={error} setError={setError} saved={saved}>
          <TextInput label="Texto de apoio" {...form.register('eyebrow')} error={form.formState.errors.eyebrow?.message} />
          <Textarea label="Título" minRows={2} {...form.register('title')} error={form.formState.errors.title?.message} />
          <TextInput label="Link" {...form.register('allLabel')} error={form.formState.errors.allLabel?.message} />
          <TextInput label="Endereço do link" {...form.register('allHref')} error={form.formState.errors.allHref?.message} />
          <TextInput label="Texto do card" {...form.register('moreLabel')} error={form.formState.errors.moreLabel?.message} />
          {items.fields.map((item, index) => (
            <Stack className="rounded-md border border-line p-4" gap="sm" key={item.id}>
              <Group justify="space-between">
                <Text fw={600} size="sm">
                  Conteúdo {index + 1}
                </Text>
                <Button color="red" onClick={() => items.remove(index)} radius="md" size="xs" type="button" variant="subtle">
                  Remover
                </Button>
              </Group>
              <TextInput label="Título" {...form.register(`items.${index}.name`)} error={form.formState.errors.items?.[index]?.name?.message} />
              <Textarea label="Texto" minRows={2} {...form.register(`items.${index}.text`)} error={form.formState.errors.items?.[index]?.text?.message} />
              <TextInput label="Link" {...form.register(`items.${index}.href`)} error={form.formState.errors.items?.[index]?.href?.message} />
              <ImageField file={files[index] ?? null} imageUrl={form.watch(`items.${index}.imageUrl`)} onFile={(next) => setFiles((current) => ({ ...current, [index]: next }))} />
            </Stack>
          ))}
          <Group>
            <Button
              disabled={items.fields.length >= 8}
              onClick={() => items.append({ name: '', text: '', href: '#inspire', imageUrl: '' })}
              radius="md"
              type="button"
              variant="default"
            >
              Adicionar conteúdo
            </Button>
            <SaveBar saving={saving} />
          </Group>
        </Form>
      )}
    </Block>
  );
}

function Form({
  form,
  onSubmit,
  error,
  setError,
  saved,
  children,
}: {
  form: {
    handleSubmit: (handler: (values: FieldValues) => Promise<void>) => (event: FormEvent<HTMLFormElement>) => void;
  };
  onSubmit: (values: FieldValues) => Promise<void>;
  error: string;
  setError: (value: string) => void;
  saved: boolean;
  children: ReactNode;
}) {
  return (
    <form
      onSubmit={(event) => {
        setError('');
        void form.handleSubmit(onSubmit)(event);
      }}
    >
      <Stack gap="md">
        {children}
        <EditorFeedback error={error} saved={saved} />
      </Stack>
    </form>
  );
}

async function send(
  path: string,
  query: { setData: (value: never) => void },
  body: BodyInit,
  setSaving: (value: boolean) => void,
  setError: (value: string) => void,
  setSaved: (value: boolean) => void,
) {
  setSaving(true);
  setError('');
  setSaved(false);
  try {
    const updated = await apiSend(path, { method: 'PUT', body });
    query.setData(updated as never);
    setSaved(true);
  } catch (cause) {
    setError(cause instanceof Error ? cause.message : 'Não foi possível salvar.');
  } finally {
    setSaving(false);
  }
}
