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

import { IconButton, TableRow as MuiTableRow, useTheme } from '@mui/material';
import { IconChevronDown } from '@tabler/icons-react';

import TableCell from '../TableCell';

import { type TableRowProps } from './types';
import { getBackgroundColor } from './utils';

const TableRow = forwardRef<HTMLTableRowElement, TableRowProps>(
  (
    {
      children,
      sx,
      headerRow = false,
      selected,
      collapsable,
      slotProps = {},
      onCollapse = () => null,
      renderDetail = () => null,
      open: openProp,
      ...props
    },
    ref,
  ) => {
    const [open, setOpen] = useState(false);

    const isControlled = openProp !== undefined;
    const isOpen = isControlled ? openProp : open;

    const theme = useTheme();
    const backgroundStyles = getBackgroundColor(headerRow, selected, theme);

    const handleCollapse = (event: MouseEvent<HTMLElement>) => {
      if (!isControlled) setOpen(!open);
      onCollapse(event);
    };

    const rowStyles = {
      borderBottom: `1px solid ${theme.palette.new.border.neutral.default}`,
      ...backgroundStyles,
      ...sx,
      ...(headerRow && { minHeight: '60px' }),
      ':hover': {
        backgroundColor: props.onClick
          ? theme.palette.new.action.background.neutral.hover
          : undefined,
        cursor: props.onClick ? 'pointer' : 'default',
      },
      '&:last-child': {
        borderBottom: 'none',
        '& .MuiTableCell-root': {
          borderBottom: 'none',
        },
      },
    };

    const collapsedRowStyles = {
      borderBottom: isOpen ? 'initial' : 'none',
      maxHeight: isOpen ? '200px' : '0',
      transition: theme.transitions.create(['max-height']),
      '& > td': {
        border: isOpen ? undefined : 'none',
        opacity: isOpen ? 1 : 0,
        maxHeight: isOpen ? '200px' : 0,
        height: isOpen ? 'auto' : 0,
        py: isOpen ? 2 : 0,
        overflow: 'hidden',
        transition: theme.transitions.create(['padding', 'opacity', 'height']),
      },
      '& > td > *': {
        maxHeight: isOpen ? '200px' : 0,
        overflow: 'hidden',
        transition: theme.transitions.create(['max-height', 'padding']),
      },
    };

    return (
      <>
        <MuiTableRow
          ref={ref}
          {...slotProps.root}
          sx={{ ...rowStyles, ...slotProps.root?.sx }}
          selected={selected}
          {...props}
        >
          {collapsable && (
            <TableCell collapsableCell>
              <IconButton
                onClick={handleCollapse}
                {...slotProps.collapseButton}
              >
                <IconChevronDown
                  style={{
                    transform: isOpen ? 'rotate(180deg)' : 'rotate(0deg)',
                    transition: 'transform 0.2s ease-in-out',
                  }}
                />
              </IconButton>
            </TableCell>
          )}
          {children}
        </MuiTableRow>
        {collapsable &&
          renderDetail(
            {
              ...slotProps.detail,
              sx: { ...collapsedRowStyles, ...slotProps.detail?.sx },
            },
            isOpen,
          )}
      </>
    );
  },
);

export type { TableRowProps };

TableRow.displayName = 'TableRow';

export default TableRow;
