import { type MouseEvent, useState } from 'react';

import { useTheme } from '@material-hu/mui/styles';

import Pills from '@material-hu/components/design-system/Pills';
import TableCell from '@material-hu/components/design-system/Table/components/TableCell';
import TableRow from '@material-hu/components/design-system/Table/components/TableRow';
import { type TableRowProps } from '@material-hu/components/design-system/Table/components/TableRow/types';
import Title from '@material-hu/components/design-system/Title';

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

import { type CategoryItem } from '../../../types';
import { getCategoryStatusType } from '../../../utils';

import CategoriesTableRowActions from './CategoriesTableRowActions';

type CategoriesTableRowProps = TableRowProps & {
  category: CategoryItem;
  depth?: number;
  forceClose?: boolean;
};

const CategoriesTableRow = ({
  category,
  depth = 1,
  onCollapse,
  forceClose = false,
  open: openProp = false,
  ...tableRowProps
}: CategoriesTableRowProps) => {
  const [open, setOpen] = useState(false);

  const { t } = useLokaliseTranslation('learning');
  const { palette, spacing } = useTheme();

  const hasChildren = category.children && category.children.length > 0;
  const hasCourses = !!category.amountOfCourses;

  const handleCollapse = (event: MouseEvent<HTMLElement>) =>
    onCollapse ? onCollapse(event) : setOpen(!open);

  const controlledOpen = onCollapse ? openProp : open;
  const isOpen = forceClose ? false : controlledOpen;

  const backgroundColor = isOpen
    ? palette.new.background.layout.default
    : palette.new.background.layout.tertiary;

  const rowStyles = {
    backgroundColor,
    '&:hover': {
      backgroundColor,
    },
  };

  return (
    <TableRow
      collapsable={hasChildren}
      onCollapse={handleCollapse}
      open={isOpen}
      renderDetail={(detailRowProps: TableRowProps) => (
        <>
          {category.children?.map(child => (
            <CategoriesTableRow
              key={child.id}
              depth={depth + 1}
              category={child}
              forceClose={!isOpen}
              {...detailRowProps}
              sx={{
                ...rowStyles,
                ...detailRowProps.sx,
              }}
            />
          ))}
        </>
      )}
      {...tableRowProps}
      sx={{
        ...rowStyles,
        ...tableRowProps.sx,
        '& td:first-of-type': {
          overflow: 'visible',
          '& > div': {
            marginRight: spacing(-4 * (depth - 1)),
          },
        },
      }}
    >
      {!hasChildren && <TableCell />}
      <TableCell
        scope="row"
        sx={{
          '& > div': {
            marginLeft: spacing(3 * (depth - 1)),
          },
          minWidth: '250px',
          width: '350px',
          maxWidth: '350px',
        }}
      >
        <Title
          variant="S"
          withEllipsis
          overflow="tooltip"
          title={category.name}
          description={
            hasChildren
              ? t('categories.children.count', {
                  count: category.children?.length,
                })
              : undefined
          }
        />
      </TableCell>
      <TableCell>
        {category.status && (
          <Pills
            label={t(`categories.status.${category.status.toLowerCase()}`, {
              count: 1,
            })}
            type={getCategoryStatusType(category.status)}
            hasIcon={false}
            size="small"
          />
        )}
      </TableCell>
      <TableCell>
        {hasCourses ? category.amountOfCourses : t('courses.associated.empty')}
      </TableCell>
      <CategoriesTableRowActions
        category={category}
        depth={depth}
      />
    </TableRow>
  );
};

export default CategoriesTableRow;
