'use client';

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

const states = [
  ['AC', 'Acre'],
  ['AL', 'Alagoas'],
  ['AP', 'Amapá'],
  ['AM', 'Amazonas'],
  ['BA', 'Bahia'],
  ['CE', 'Ceará'],
  ['DF', 'Distrito Federal'],
  ['ES', 'Espírito Santo'],
  ['GO', 'Goiás'],
  ['MA', 'Maranhão'],
  ['MT', 'Mato Grosso'],
  ['MS', 'Mato Grosso do Sul'],
  ['MG', 'Minas Gerais'],
  ['PA', 'Pará'],
  ['PB', 'Paraíba'],
  ['PR', 'Paraná'],
  ['PE', 'Pernambuco'],
  ['PI', 'Piauí'],
  ['RJ', 'Rio de Janeiro'],
  ['RN', 'Rio Grande do Norte'],
  ['RS', 'Rio Grande do Sul'],
  ['RO', 'Rondônia'],
  ['RR', 'Roraima'],
  ['SC', 'Santa Catarina'],
  ['SP', 'São Paulo'],
  ['SE', 'Sergipe'],
  ['TO', 'Tocantins'],
].map(([value, label]) => ({ value, label }));

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

const areaSchema = z.object({
  city: z.string(),
  neighborhoods: z.string(),
});

const itemSchema = z
  .object({
    key: z.string(),
    id: z.string(),
    name: limited(2, 120, 'O nome precisa ter entre 2 e 120 caracteres.'),
    representative: limited(2, 80, 'O representante precisa ter entre 2 e 80 caracteres.'),
    address: z
      .string()
      .trim()
      .max(160, { error: 'O endereço pode ter no máximo 160 caracteres.' })
      .refine((value) => value.length === 0 || value.length >= 2, { error: 'O endereço precisa ter entre 2 e 160 caracteres.' }),
    state: z.string().length(2, { error: 'Selecione um estado.' }),
    email: z.email({ error: 'Informe um e-mail válido.' }),
    phone: z
      .string()
      .trim()
      .max(40, { error: 'O telefone pode ter no máximo 40 caracteres.' })
      .refine((value) => {
        const digits = value.replace(/\D/g, '');
        return digits.length >= 8 && digits.length <= 20;
      }, { error: 'Informe o telefone com DDD.' }),
    construtora: z.boolean(),
    entireState: z.boolean(),
    areas: z.array(areaSchema),
    status: z.enum(['DRAFT', 'PUBLISHED']),
  })
  .superRefine((item, ctx) => {
    if (item.entireState) return;
    if (item.areas.length === 0) {
      ctx.addIssue({ code: 'custom', message: 'Informe ao menos uma cidade ou marque todo o estado.', path: ['areas'] });
      return;
    }
    const cities = new Set<string>();
    item.areas.forEach((area, index) => {
      const city = area.city.trim();
      if (city.length < 2 || city.length > 80) {
        ctx.addIssue({ code: 'custom', message: 'A cidade precisa ter entre 2 e 80 caracteres.', path: ['areas', index, 'city'] });
      }
      const cityKey = city.toLocaleLowerCase('pt-BR');
      if (city && cities.has(cityKey)) {
        ctx.addIssue({ code: 'custom', message: 'Essa cidade já foi informada.', path: ['areas', index, 'city'] });
      }
      if (city) cities.add(cityKey);
      for (const part of area.neighborhoods.split(',')) {
        const name = part.trim();
        if (!name) continue;
        if (name.length < 2 || name.length > 80) {
          ctx.addIssue({ code: 'custom', message: 'Cada bairro precisa ter entre 2 e 80 caracteres.', path: ['areas', index, 'neighborhoods'] });
          break;
        }
      }
    });
  });

const schema = z.object({
  items: z.array(itemSchema),
});

type RepresentativesForm = z.infer<typeof schema>;
type AreaForm = RepresentativesForm['items'][number]['areas'][number];
type RepresentativeRecord = Omit<RepresentativesForm['items'][number], 'key' | 'areas'> & {
  areas: { city: string; neighborhoods: string[] }[];
};

const emptyArea = (): AreaForm => ({ city: '', neighborhoods: '' });

const emptyItem = (): RepresentativesForm['items'][number] => ({
  key: crypto.randomUUID(),
  id: '',
  name: '',
  representative: '',
  address: '',
  state: '',
  email: '',
  phone: '',
  construtora: false,
  entireState: false,
  areas: [emptyArea()],
  status: 'PUBLISHED',
});

function areaMessage(error: unknown, index: number, field: 'city' | 'neighborhoods') {
  if (!Array.isArray(error)) return undefined;
  const item = error[index] as { city?: { message?: string }; neighborhoods?: { message?: string } } | undefined;
  return item?.[field]?.message;
}

function areasMessage(error: unknown) {
  if (!error || typeof error !== 'object') return undefined;
  const record = error as { message?: string; root?: { message?: string } };
  return record.message || record.root?.message;
}

function AreaFields({ areas, error, onChange }: { areas: AreaForm[]; error: unknown; onChange: (areas: AreaForm[]) => void }) {
  function update(index: number, patch: Partial<AreaForm>) {
    onChange(areas.map((area, areaIndex) => (areaIndex === index ? { ...area, ...patch } : area)));
  }

  function splitCity(index: number) {
    const parts = areas[index].city
      .split(',')
      .map((part) => part.trim())
      .filter(Boolean);
    if (parts.length <= 1) {
      update(index, { city: areas[index].city.trim() });
      return;
    }
    onChange([
      ...areas.slice(0, index),
      ...parts.map((city, partIndex) => ({ city, neighborhoods: partIndex === 0 ? areas[index].neighborhoods : '' })),
      ...areas.slice(index + 1),
    ]);
  }

  return (
    <Stack gap="sm">
      <Text c="var(--mantine-color-muted)" size="sm">
        Cada cidade leva os próprios bairros, separados por vírgula. Para incluir várias cidades de uma vez, separe os nomes por vírgula.
      </Text>
      {areas.map((area, index) => (
        <Stack gap="xs" key={index}>
          <SimpleGrid cols={{ base: 1, sm: 2 }}>
            <TextInput
              error={areaMessage(error, index, 'city')}
              label="Cidade"
              value={area.city}
              onBlur={() => splitCity(index)}
              onChange={(event) => update(index, { city: event.currentTarget.value })}
            />
            <TextInput
              description="Opcional. Separe vários por vírgula."
              error={areaMessage(error, index, 'neighborhoods')}
              label="Bairros"
              value={area.neighborhoods}
              onChange={(event) => update(index, { neighborhoods: event.currentTarget.value })}
            />
          </SimpleGrid>
          {areas.length > 1 && (
            <Button className="self-start" onClick={() => onChange(areas.filter((_, areaIndex) => areaIndex !== index))} px={0} type="button" variant="subtle">
              Remover cidade
            </Button>
          )}
        </Stack>
      ))}
      {areasMessage(error) && (
        <Text c="red" size="sm">
          {areasMessage(error)}
        </Text>
      )}
      <Button className="self-start" onClick={() => onChange([...areas, emptyArea()])} radius="md" type="button" variant="default">
        Adicionar cidade
      </Button>
    </Stack>
  );
}

function toPayload(items: RepresentativesForm['items']) {
  return items.map(({ id, name, representative, address, state, email, phone, construtora, entireState, areas, status }) => ({
    id: id || undefined,
    name,
    representative,
    address,
    state,
    email,
    phone,
    construtora,
    entireState,
    areas: entireState ? [] : areas.map(({ city, neighborhoods }) => ({ city: city.trim(), neighborhoods })),
    status,
  }));
}

export function RepresentativesEditor() {
  const query = useAdminQuery<RepresentativeRecord[]>('/admin/representatives');
  const [error, setError] = useState('');
  const [saved, setSaved] = useState(false);
  const [saving, setSaving] = useState(false);
  const [selectedIndex, setSelectedIndex] = useState<number | null>(null);
  const form = useForm<RepresentativesForm>({ defaultValues: { items: [] }, resolver: zodResolver(schema) });
  const { reset } = form;
  const items = useFieldArray({ control: form.control, name: 'items', keyName: 'fieldId' });

  useEffect(() => {
    if (!query.data) return;
    reset({
      items: query.data.map((item) => ({
        ...item,
        construtora: item.construtora === true,
        entireState: item.entireState === true,
        areas: item.areas.length ? item.areas.map((area) => ({ city: area.city, neighborhoods: area.neighborhoods.join(', ') })) : [emptyArea()],
        key: item.id,
      })),
    });
  }, [query.data, reset]);

  const names = form.watch('items');
  const selected = selectedIndex !== null ? items.fields[selectedIndex] : undefined;

  function backToList() {
    if (selectedIndex === null) return;
    const current = form.getValues(`items.${selectedIndex}`);
    const untouched =
      !current.id &&
      !current.name &&
      !current.representative &&
      !current.address &&
      !current.state &&
      !current.entireState &&
      !current.construtora &&
      current.areas.every((area) => !area.city.trim() && !area.neighborhoods.trim()) &&
      !current.email &&
      !current.phone;
    if (untouched) items.remove(selectedIndex);
    setSelectedIndex(null);
    setSaved(false);
    setError('');
  }

  function openNew() {
    const next = items.fields.length;
    items.append(emptyItem());
    setSelectedIndex(next);
    setSaved(false);
    setError('');
  }

  function onInvalid(errors: FieldErrors<RepresentativesForm>) {
    if (!Array.isArray(errors.items)) return;
    const index = errors.items.findIndex((item) => item);
    if (index >= 0) setSelectedIndex(index);
  }

  async function onSubmit(values: RepresentativesForm) {
    setSaving(true);
    setError('');
    setSaved(false);
    try {
      const updated = await apiSend<RepresentativeRecord[]>('/admin/representatives', {
        method: 'PUT',
        body: JSON.stringify({
          items: toPayload(values.items),
        }),
      });
      query.setData(updated);
      setSaved(true);
    } catch (cause) {
      setError(cause instanceof Error ? cause.message : 'Não foi possível salvar.');
    } finally {
      setSaving(false);
    }
  }

  async function removeSelected() {
    if (selectedIndex === null) return;
    const next = form.getValues('items').filter((_, index) => index !== selectedIndex);
    items.remove(selectedIndex);
    setSelectedIndex(null);
    setSaving(true);
    setError('');
    setSaved(false);
    try {
      const updated = await apiSend<RepresentativeRecord[]>('/admin/representatives', {
        method: 'PUT',
        body: JSON.stringify({
          items: toPayload(next),
        }),
      });
      query.setData(updated);
    } catch (cause) {
      setError(cause instanceof Error ? cause.message : 'Não foi possível remover.');
      query.reload();
    } finally {
      setSaving(false);
    }
  }

  return (
    <Card className="border border-line bg-elevated" padding="lg" radius="md" withBorder>
      <form
        onSubmit={(event) => {
          setError('');
          void form.handleSubmit(onSubmit, onInvalid)(event);
        }}
      >
        <Stack gap="lg">
          <LoadState error={query.error} loading={query.loading} />
          {query.data && selectedIndex === null && (
            <>
              <Stack gap={4}>
                <Title order={2} size="h4">
                  Representantes
                </Title>
                <Text c="var(--mantine-color-muted)" size="sm">
                  Escolha um nome para editar os dados exibidos na página Onde encontrar.
                </Text>
              </Stack>
              {items.fields.length === 0 && (
                <Text c="var(--mantine-color-muted)" size="sm">
                  Nenhum representante cadastrado.
                </Text>
              )}
              <Stack gap="xs">
                {items.fields.map((item, index) => (
                  <button
                    className="rounded-md border border-line bg-elevated px-4 py-3 text-left transition-shadow hover:shadow-soft focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-orange"
                    key={item.fieldId}
                    onClick={() => {
                      setSelectedIndex(index);
                      setSaved(false);
                      setError('');
                    }}
                    type="button"
                  >
                    <Text fw={600}>{names[index]?.name || 'Novo representante'}</Text>
                  </button>
                ))}
              </Stack>
              <Button className="self-start" onClick={openNew} radius="md" type="button" variant="default">
                Adicionar representante
              </Button>
              <EditorFeedback error={error} saved={false} />
            </>
          )}
          {query.data && selected && selectedIndex !== null && (
            <>
              <Stack gap={4}>
                <Button className="self-start" onClick={backToList} px={0} radius="md" type="button" variant="subtle">
                  Voltar para a lista
                </Button>
                <Title order={2} size="h4">
                  {names[selectedIndex]?.name || 'Novo representante'}
                </Title>
              </Stack>
              <TextInput label="Nome" {...form.register(`items.${selectedIndex}.name`)} error={form.formState.errors.items?.[selectedIndex]?.name?.message} />
              <TextInput
                label="Representante"
                {...form.register(`items.${selectedIndex}.representative`)}
                error={form.formState.errors.items?.[selectedIndex]?.representative?.message}
              />
              <TextInput label="Endereço" {...form.register(`items.${selectedIndex}.address`)} error={form.formState.errors.items?.[selectedIndex]?.address?.message} />
              <Select
                allowDeselect={false}
                data={states}
                error={form.formState.errors.items?.[selectedIndex]?.state?.message}
                label="Estado"
                searchable
                value={form.watch(`items.${selectedIndex}.state`) || null}
                onChange={(value) => form.setValue(`items.${selectedIndex}.state`, value ?? '', { shouldValidate: true })}
              />
              <Checkbox
                checked={form.watch(`items.${selectedIndex}.construtora`)}
                label="Construtora"
                onChange={(event) => form.setValue(`items.${selectedIndex}.construtora`, event.currentTarget.checked)}
              />
              <Checkbox
                checked={form.watch(`items.${selectedIndex}.entireState`)}
                description="A busca mostra este representante em qualquer cidade do estado."
                label="Representa todo o estado"
                onChange={(event) => form.setValue(`items.${selectedIndex}.entireState`, event.currentTarget.checked, { shouldValidate: true })}
              />
              {!form.watch(`items.${selectedIndex}.entireState`) && (
                <AreaFields
                  areas={form.watch(`items.${selectedIndex}.areas`) ?? []}
                  error={form.formState.errors.items?.[selectedIndex]?.areas}
                  onChange={(areas) => form.setValue(`items.${selectedIndex}.areas`, areas, { shouldValidate: true })}
                />
              )}
              <TextInput label="E-mail" {...form.register(`items.${selectedIndex}.email`)} error={form.formState.errors.items?.[selectedIndex]?.email?.message} />
              <TextInput label="Telefone" {...form.register(`items.${selectedIndex}.phone`)} error={form.formState.errors.items?.[selectedIndex]?.phone?.message} />
              <Select
                allowDeselect={false}
                data={[
                  { value: 'PUBLISHED', label: 'Publicado' },
                  { value: 'DRAFT', label: 'Rascunho' },
                ]}
                label="Exibição"
                value={form.watch(`items.${selectedIndex}.status`)}
                onChange={(value) => form.setValue(`items.${selectedIndex}.status`, value === 'DRAFT' ? 'DRAFT' : 'PUBLISHED')}
              />
              <Group justify="space-between">
                <Button color="red" loading={saving} onClick={() => void removeSelected()} radius="md" type="button" variant="subtle">
                  Remover
                </Button>
                <Group>
                  <Button onClick={backToList} radius="md" type="button" variant="default">
                    Voltar
                  </Button>
                  <Button onClick={openNew} radius="md" type="button" variant="default">
                    Novo representante
                  </Button>
                  <Button loading={saving} radius="md" type="submit">
                    Salvar
                  </Button>
                </Group>
              </Group>
              <EditorFeedback error={error} saved={saved} />
            </>
          )}
        </Stack>
      </form>
    </Card>
  );
}
