import { Fragment, useRef } from 'react';
import { useFieldArray, useFormContext } from 'react-hook-form';

import { IconPlus, IconTrash } from '@material-hu/icons/tabler';
import { useTheme } from '@material-hu/mui';
import Divider from '@material-hu/mui/Divider';
import IconButton from '@material-hu/mui/IconButton';
import Stack from '@material-hu/mui/Stack';
import Typography from '@material-hu/mui/Typography/Typography';

import Button from '@material-hu/components/design-system/Buttons/Button';
import CardContainer from '@material-hu/components/design-system/CardContainer';
import FormInputClassic from '@material-hu/components/design-system/Inputs/Classic/form';
import StateCard from '@material-hu/components/design-system/StateCard';

import { useLokaliseTranslation } from 'src/utils/i18n';

import { MAX_CATEGORY_TITLE_LENGTH } from '../../constants';
import { type CategoryItem } from '../../types';
import { hasMaxChildren } from '../../utils';
import useDeleteCategoryModal from '../useDeleteCategoryModal';

import {
  type ManageCategoryChildItem,
  type ManageCategoryFormValues,
} from './form';
import { newCategoryItem } from './utils';

type ManageCategoryFormProps = {
  category: CategoryItem;
  disabled?: boolean;
};

const ManageCategoryForm = ({
  category,
  disabled = false,
}: ManageCategoryFormProps) => {
  const { t } = useLokaliseTranslation('learning');
  const { palette } = useTheme();
  const lastItemIdRef = useRef<HTMLDivElement | null>(null);

  const { control } = useFormContext<ManageCategoryFormValues>();
  const { fields, append, remove } = useFieldArray({
    name: 'children',
    control,
  });

  const children = fields as ManageCategoryChildItem[];
  const isEmpty = !children || children.length === 0;

  const {
    modal: deleteModal,
    showModal: showDeleteModal,
    closeModal: closeDeleteModal,
  } = useDeleteCategoryModal();

  const handleAdd = () => {
    append(newCategoryItem());

    setTimeout(() => {
      if (!lastItemIdRef.current) return;
      lastItemIdRef.current.scrollIntoView({
        behavior: 'smooth',
        block: 'start',
      });
    }, 1);
  };

  const handleDelete = (index: number) => {
    const child = children[index];

    if (!child.originalId && !child.name) {
      remove(index);
      return;
    }

    showDeleteModal({
      category: { ...child, id: child.originalId },
      onDelete: () => {
        remove(index);
        closeDeleteModal();
      },
    });
  };

  return (
    <>
      {deleteModal}
      <Stack sx={{ gap: 2 }}>
        <Typography variant="globalS">
          {t('categories.manage.description')}
        </Typography>
        <CardContainer
          color="grey"
          fullWidth
        >
          <Stack sx={{ flexDirection: 'row', gap: 1 }}>
            <Typography
              variant="globalS"
              fontWeight="fontWeightSemiBold"
              sx={{ whiteSpace: 'nowrap' }}
            >
              {t('categories.manage.managing')}
            </Typography>
            <Typography
              variant="globalS"
              sx={{ color: palette.new.text.neutral.lighter }}
            >
              {category.name}
            </Typography>
          </Stack>
        </CardContainer>
        <CardContainer
          color="grey"
          fullWidth
        >
          {isEmpty && (
            <StateCard
              title={t('empty.categories.children.title')}
              description={t('empty.categories.children.description')}
              primaryAction={{
                label: t('categories.children.add'),
                onClick: handleAdd,
              }}
            />
          )}
          {!isEmpty && (
            <Stack sx={{ gap: 1.5 }}>
              {children.map((child, index) => (
                <Fragment key={child.id}>
                  <Stack
                    ref={
                      index === children.length - 1 ? lastItemIdRef : undefined
                    }
                    sx={{
                      flexDirection: 'row',
                      gap: 1.5,
                      alignItems: 'flex-start',
                    }}
                  >
                    <FormInputClassic
                      name={`children.${index}.name`}
                      inputProps={{
                        label: t('categories.children.title_one'),
                        placeholder: t('general:name'),
                        hasCounter: false,
                        maxLength: MAX_CATEGORY_TITLE_LENGTH,
                        disabled,
                      }}
                    />
                    <IconButton
                      aria-label={t('general:delete')}
                      onClick={() => handleDelete(index)}
                      disabled={disabled}
                      sx={{ height: '56px', mt: '26px' }}
                    >
                      <IconTrash />
                    </IconButton>
                  </Stack>
                  {index !== children.length - 1 && <Divider />}
                </Fragment>
              ))}
              <Button
                onClick={handleAdd}
                size="large"
                variant="secondary"
                disabled={disabled || hasMaxChildren({ children })}
                startIcon={<IconPlus size={16} />}
              >
                {t('categories.children.add')}
              </Button>
            </Stack>
          )}
        </CardContainer>
      </Stack>
    </>
  );
};

export default ManageCategoryForm;
