import { useState, useEffect } from 'react';
import {
  Modal,
  TextInput,
  Button,
  Group,
  Stack,
  NumberInput,
  Divider,
} from '@mantine/core';
import { useForm } from '@mantine/form';
import { IconPlus } from '@tabler/icons-react';
import { useTranslation } from 'react-i18next';
import {
  useGetLocationTypesQuery,
  useCreateLocationTypeMutation,
  useUpdateLocationTypeMutation,
  useDeleteLocationTypeMutation,
} from '../../api/location-api';
import { AdvancedTable, notify, useErrorHandler, useServerTable } from '@ema-platform/ui';
import type { LocationType } from '../../types/location';
import { locationTypeColumns } from './columns';
import { locationTypeColumnActions } from './actions';

interface LocationTypeFormValues {
  code: string;
  namesEn: string;
  namesAm: string;
  level: number;
}

export function LocationTypeModal({ opened, onClose }: { opened: boolean; onClose: () => void }) {
  const { t, i18n } = useTranslation();
  const locale = i18n.language as 'en' | 'am';
  const { handleError } = useErrorHandler();
  const { data: locationTypes, isLoading, refetch } = useGetLocationTypesQuery();
  const table = useServerTable();
  const [createType] = useCreateLocationTypeMutation();
  const [updateType] = useUpdateLocationTypeMutation();
  const [deleteType] = useDeleteLocationTypeMutation();

  const [editingId, setEditingId] = useState<string | null>(null);
  const [showForm, setShowForm] = useState(false);

  const form = useForm<LocationTypeFormValues>({
    initialValues: {
      code: '',
      namesEn: '',
      namesAm: '',
      level: 1,
    },
    validate: {
      code: (v) => (!v ? t('location.validation.codeRequired') : null),
      namesEn: (v) => (!v ? t('location.validation.nameEnRequired') : null),
      namesAm: (v) => (!v ? t('location.validation.nameAmRequired') : null),
      level: (v) => (v < 1 ? 'Level must be at least 1' : null),
    },
  });

  useEffect(() => {
    if (!opened) {
      resetForm();
    }
  }, [opened]);

  const resetForm = () => {
    form.reset();
    setEditingId(null);
    setShowForm(false);
  };

  const handleEdit = (type: LocationType) => {
    setEditingId(type.id);
    form.setValues({
      code: type.code,
      // The form's inputs are controlled strings; a locale the row never had
      // must edit as empty rather than reading back "undefined".
      namesEn: type.names.en ?? '',
      namesAm: type.names.am ?? '',
      level: type.level,
    });
    setShowForm(true);
  };

  const handleDelete = async (id: string) => {
    try {
      await deleteType(id).unwrap();
      notify.success(t('location.typeDeleted'));
    } catch (e) {
      handleError(e);
    }
  };

  const handleSubmit = form.onSubmit(async (values) => {
    try {
      if (editingId) {
        await updateType({ id: editingId, ...values, names: { en: values.namesEn, am: values.namesAm } }).unwrap();
        notify.success(t('location.typeUpdated'));
      } else {
        await createType({ code: values.code, names: { en: values.namesEn, am: values.namesAm }, level: values.level }).unwrap();
        notify.success(t('location.typeCreated'));
      }
      resetForm();
    } catch (e) {
      handleError(e);
    }
  });

  const sortedTypes = locationTypes?.items
    ? [...locationTypes.items].sort((a, b) => a.level - b.level)
    : [];
  const paged = table.paginate(sortedTypes);

  return (
    <Modal
      opened={opened}
      onClose={onClose}
      title={t('location.manageTypes')}
      size="lg"
    >
      {!showForm && (
        <Button
          variant="light"
          leftSection={<IconPlus size={16} />}
          onClick={() => setShowForm(true)}
          mt="md"
          mb="md"
          size="sm"
        >
          {t('location.addType')}
        </Button>
      )}

      {showForm && (
        <form onSubmit={handleSubmit}>
          <Stack gap="sm" mb="md">
            <TextInput
              label={t('location.code')}
              placeholder="e.g., COUNTRY, REGION, CITY"
              {...form.getInputProps('code')}
              size="sm"
            />
            <TextInput
              label={t('location.nameEn')}
              placeholder="English name"
              {...form.getInputProps('namesEn')}
              size="sm"
            />
            <TextInput
              label={t('location.nameAm')}
              placeholder="የአማርኛ ስም"
              {...form.getInputProps('namesAm')}
              size="sm"
            />
            <NumberInput
              label={t('location.level')}
              placeholder="1"
              min={1}
              max={10}
              {...form.getInputProps('level')}
              size="sm"
            />
            <Group justify="flex-end">
              <Button variant="default" onClick={resetForm} size="sm">
                {t('location.cancel')}
              </Button>
              <Button type="submit" size="sm">
                {editingId ? t('location.update') : t('location.create')}
              </Button>
            </Group>
          </Stack>
        </form>
      )}

      <Divider mb="md" />

      <AdvancedTable
        tableName={t('location.manageTypes')}
        columns={[
          ...locationTypeColumns(t, locale),
          locationTypeColumnActions(t, {
            onEdit: handleEdit,
            onDelete: (type) => handleDelete(type.id),
          }),
        ]}
        data={paged.rows}
        itemCount={paged.itemCount}
        pageIndex={paged.pageIndex}
        onPageChange={table.setPageIndex}
        pageSize={table.pageSize}
        isLoading={isLoading}
        refresh={refetch}
        emptyText={t('location.noTypes')}
      />
    </Modal>
  );
}
