import {
  Controller,
  type UseControllerProps,
  useFormContext,
} from 'react-hook-form';

import Stack from '@material-hu/mui/Stack/Stack';
import Typography from '@material-hu/mui/Typography/Typography';

import RadioBase from '@material-hu/components/design-system/RadioButton/RadioBase';
import Table from '@material-hu/components/design-system/Table';
import TableBody from '@material-hu/components/design-system/Table/components/TableBody';
import TableCell from '@material-hu/components/design-system/Table/components/TableCell';
import TableContainer from '@material-hu/components/design-system/Table/components/TableContainer';
import TableHead from '@material-hu/components/design-system/Table/components/TableHead';
import TableRow from '@material-hu/components/design-system/Table/components/TableRow';

import useHuGoTheme from 'src/hooks/useHuGoTheme';
import useRules, { type RulesOptions } from 'src/hooks/useRules';
import {
  type CheckboxGridValue,
  type Option,
  type Question,
  type Row,
} from 'src/types/forms';

export type CheckboxGridHugoProps = Omit<UseControllerProps, 'rules'> &
  Partial<Question> & {
    disabled?: boolean;
    rules?: RulesOptions;
  };

const CheckboxGridHugo = ({
  name,
  defaultValue,
  options,
  rows,
  disabled = false,
  rules = {},
}: CheckboxGridHugoProps) => {
  const HugoThemeProvider = useHuGoTheme();
  const {
    control,
    setValue,
    watch,
    trigger,
    formState: { isSubmitted },
  } = useFormContext();

  const { requiredCheckboxGrid } = rules;
  const checkboxGridRules = useRules({
    ...rules,
    requiredCheckboxGrid:
      requiredCheckboxGrid && rows && options ? { rows, options } : undefined,
  });

  const value: CheckboxGridValue = watch(name, defaultValue) || {};

  const isChecked = (row: Row, option: Option) =>
    !!value && !!value[row.id] && value[row.id][0] === option.description;

  const handleChange = (row: Row, option: Option) => {
    const newValue: CheckboxGridValue = { ...value };

    if (isChecked(row, option)) {
      delete newValue[row.id];
    } else {
      newValue[row.id] = [option.description];
    }

    setValue(name, newValue);
    if (isSubmitted) {
      trigger(name);
    }
  };

  return (
    <HugoThemeProvider>
      <Controller
        name={name}
        rules={checkboxGridRules}
        control={control}
        defaultValue={defaultValue}
        render={() => (
          <TableContainer>
            <Table>
              <TableHead>
                <TableRow headerRow>
                  <TableCell
                    align="center"
                    headerCell
                    sx={{ borderRight: '1px solid', borderColor: 'divider' }}
                  />
                  {options?.map(option => (
                    <TableCell
                      key={option.id}
                      align="center"
                      headerCell
                    >
                      {option.description}
                    </TableCell>
                  ))}
                </TableRow>
              </TableHead>
              <TableBody>
                {rows?.map(row => (
                  <TableRow
                    key={row.id}
                    sx={{
                      '&:last-child td, &:last-child th': { borderBottom: 0 },
                    }}
                  >
                    <TableCell
                      id={`row-${row.id}`}
                      sx={{ borderRight: '1px solid', borderColor: 'divider' }}
                    >
                      <Typography
                        variant="globalS"
                        noWrap
                      >
                        {row.description}
                      </Typography>
                    </TableCell>
                    {options?.map(option => (
                      <TableCell key={option.id}>
                        <Stack
                          sx={{
                            width: 1,
                            display: 'flex',
                            justifyContent: 'center',
                            alignItems: 'center',
                          }}
                        >
                          <RadioBase
                            value={option.description}
                            checked={isChecked(row, option)}
                            disabled={disabled}
                            onChange={() => handleChange(row, option)}
                            sx={{ width: 'fit-content' }}
                          />
                        </Stack>
                      </TableCell>
                    ))}
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          </TableContainer>
        )}
      />
    </HugoThemeProvider>
  );
};

export default CheckboxGridHugo;
