'use client';

import { EditorFeedback, LoadState } from '@/components/content/feedback';
import { apiSend, useAdminQuery } from '@/lib/api';
import { zodResolver } from '@hookform/resolvers/zod';
import { Button, Card, ColorInput, ColorSwatch, Group, SimpleGrid, Stack, Text, Textarea, TextInput, Title } from '@mantine/core';
import { useEffect, useState } from 'react';
import { Controller, useFieldArray, useForm } from 'react-hook-form';
import { z } from 'zod';

const limited = (min: number, max: number, message: string) => z.string().trim().min(min, { error: message }).max(max, { error: message });

const colorSchema = z.object({
  key: z.string(),
  name: limited(2, 40, 'O nome da cor precisa ter entre 2 e 40 caracteres.'),
  hex: z
    .string()
    .trim()
    .regex(/^#[0-9a-fA-F]{6}$/, { error: 'Informe a cor no formato #RRGGBB.' }),
});

const schema = z.object({
  title: limited(2, 80, 'O título precisa ter entre 2 e 80 caracteres.'),
  description: limited(2, 240, 'A descrição precisa ter entre 2 e 240 caracteres.'),
  colors: z
    .array(colorSchema)
    .min(1, { error: 'Inclua ao menos uma cor.' })
    .max(50, { error: 'A paleta pode ter no máximo 50 cores.' })
    .superRefine((colors, ctx) => {
      const seen = new Set<string>();
      colors.forEach((color, index) => {
        const hex = color.hex.toUpperCase();
        if (seen.has(hex)) {
          ctx.addIssue({ code: 'custom', message: 'Cada cor da paleta precisa de um código diferente.', path: [index, 'hex'] });
        }
        seen.add(hex);
      });
    }),
});

type SimulatorForm = z.infer<typeof schema>;
type SimulatorResponse = { title: string; description: string; colors: { name: string; hex: string }[] };

function freshHex(colors: { hex: string }[]) {
  const used = new Set(colors.map((color) => color.hex.toUpperCase()));
  for (let index = 0; index < 256; index += 1) {
    const channel = index.toString(16).padStart(2, '0');
    const hex = `#${channel}${channel}${channel}`.toUpperCase();
    if (!used.has(hex)) return hex;
  }
  return '#C8C8C8';
}

export function SimulatorEditor() {
  const query = useAdminQuery<SimulatorResponse>('/admin/pages/simulator');
  const [error, setError] = useState('');
  const [saved, setSaved] = useState(false);
  const [saving, setSaving] = useState(false);
  const form = useForm<SimulatorForm>({
    defaultValues: { title: '', description: '', colors: [] },
    resolver: zodResolver(schema),
  });
  const { reset } = form;
  const colors = useFieldArray({ control: form.control, name: 'colors', keyName: 'fieldId' });
  const watched = form.watch('colors');

  useEffect(() => {
    if (!query.data) return;
    reset({
      title: query.data.title,
      description: query.data.description,
      colors: query.data.colors.map((color) => ({ ...color, key: color.hex })),
    });
  }, [query.data, reset]);

  async function onSubmit(values: SimulatorForm) {
    setSaving(true);
    setError('');
    setSaved(false);
    try {
      const updated = await apiSend<SimulatorResponse>('/admin/pages/simulator', {
        method: 'PUT',
        body: JSON.stringify({
          title: values.title,
          description: values.description,
          colors: values.colors.map(({ name, hex }) => ({ name, hex: hex.toUpperCase() })),
        }),
      });
      query.setData(updated);
      reset({
        title: updated.title,
        description: updated.description,
        colors: updated.colors.map((color) => ({ ...color, key: color.hex })),
      });
      setSaved(true);
    } catch (cause) {
      setError(cause instanceof Error ? cause.message : 'Não foi possível salvar.');
    } finally {
      setSaving(false);
    }
  }

  return (
    <Card className="border border-line bg-elevated" padding="lg" radius="md" withBorder>
      <form
        onSubmit={(event) => {
          setError('');
          void form.handleSubmit(onSubmit)(event);
        }}
      >
        <Stack gap="lg">
          <Stack gap={4}>
            <Title order={2} size="h4">
              Cabeçalho e paleta
            </Title>
            <Text c="var(--mantine-color-muted)" size="sm">
              Título, descrição e cores da página do simulador. Os ambientes e os botões continuam fixos.
            </Text>
          </Stack>
          <LoadState error={query.error} loading={query.loading} />
          {query.data && (
            <>
              <TextInput label="Título" {...form.register('title')} error={form.formState.errors.title?.message} />
              <Textarea label="Descrição" minRows={2} {...form.register('description')} error={form.formState.errors.description?.message} />
              <Stack gap="sm">
                <Group justify="space-between">
                  <Text fw={600}>Paleta</Text>
                  <Button
                    disabled={colors.fields.length >= 50}
                    onClick={() => colors.append({ key: crypto.randomUUID(), name: '', hex: freshHex(watched) })}
                    radius="md"
                    size="xs"
                    type="button"
                    variant="light"
                  >
                    Adicionar cor
                  </Button>
                </Group>
                <SimpleGrid cols={{ base: 4, sm: 8 }} spacing="xs">
                  {watched.map((color, index) => (
                    <div className="aspect-square" key={colors.fields[index]?.fieldId ?? index}>
                      <ColorSwatch color={/^#[0-9a-fA-F]{6}$/.test(color.hex) ? color.hex : '#d6d3ce'} radius="sm" size="100%" />
                    </div>
                  ))}
                </SimpleGrid>
                {colors.fields.map((item, index) => (
                  <Stack className="rounded-md border border-line p-4" gap="sm" key={item.fieldId}>
                    <Group justify="space-between">
                      <Text fw={600} size="sm">
                        Cor {index + 1}
                      </Text>
                      <Button color="red" disabled={colors.fields.length === 1} onClick={() => colors.remove(index)} radius="md" size="xs" type="button" variant="subtle">
                        Remover
                      </Button>
                    </Group>
                    <SimpleGrid cols={{ base: 1, sm: 2 }}>
                      <TextInput label="Nome" {...form.register(`colors.${index}.name`)} error={form.formState.errors.colors?.[index]?.name?.message} />
                      <Controller
                        control={form.control}
                        name={`colors.${index}.hex`}
                        render={({ field }) => (
                          <ColorInput
                            error={form.formState.errors.colors?.[index]?.hex?.message}
                            format="hex"
                            label="Código"
                            onChange={field.onChange}
                            value={field.value}
                            withEyeDropper={false}
                          />
                        )}
                      />
                    </SimpleGrid>
                  </Stack>
                ))}
                {form.formState.errors.colors?.message && (
                  <Text c="red" size="sm">
                    {form.formState.errors.colors.message}
                  </Text>
                )}
              </Stack>
              <Button className="self-end" loading={saving} radius="md" type="submit">
                Salvar página
              </Button>
              <EditorFeedback error={error} saved={saved} />
            </>
          )}
        </Stack>
      </form>
    </Card>
  );
}
