import { useFormContext } from 'react-hook-form';

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

import Accordion, {
  type AccordionProps,
} from '@material-hu/components/design-system/Accordion';
import CardContainer, {
  type CardContainerProps,
} from '@material-hu/components/design-system/CardContainer';
import Checkbox, {
  type CheckboxProps,
} from '@material-hu/components/design-system/Checkbox/Checkbox';

import { type ServiceItemStatus } from '../../types';

type Props = {
  name: string;
  title: string;
  description: string;
  expanded?: boolean;
  onChangeExpanded?: (
    event: React.SyntheticEvent,
    newExpanded: boolean,
  ) => void;
  options: {
    value: ServiceItemStatus;
    label: string;
  }[];
  slotProps?: {
    checkbox?: CheckboxProps;
    cardContainer?: CardContainerProps;
    accordion?: Omit<
      AccordionProps,
      | 'title'
      | 'description'
      | 'expanded'
      | 'onChange'
      | 'elevation'
      | 'disableGutters'
      | 'customDetail'
    >;
  };
};

/**
 * A React Hook Form integrated multi-select component for Service Item statuses.
 * Renders an accordion with checkboxes that allow selecting multiple ServiceItemStatus values.
 *
 * Must be used within a FormProvider context from react-hook-form.
 * The selected statuses are stored as an array in the form field specified by `name`.
 *
 * The accordion can be controlled (by providing `expanded` prop) or uncontrolled.
 */
const ServiceItemStatusFormSelect = ({
  name,
  title,
  description,
  expanded,
  onChangeExpanded,
  options,
  slotProps = {
    checkbox: {},
    cardContainer: {},
    accordion: {},
  },
}: Props) => {
  const { watch, setValue } = useFormContext();
  const statusesValue = watch(name) || [];

  const handleStatusCheck = (status: ServiceItemStatus) => {
    const newStatuses = statusesValue.includes(status)
      ? statusesValue.filter((s: ServiceItemStatus) => s !== status)
      : [...statusesValue, status];
    setValue(name, newStatuses);
  };

  const controlledProps =
    expanded !== undefined ? { expanded, onChange: onChangeExpanded } : {};

  return (
    <Accordion
      title={title}
      description={description}
      {...controlledProps}
      elevation={0}
      sx={{
        backgroundColor: ({ palette }) =>
          palette?.new.background.layout.default,
      }}
      disableGutters
      {...slotProps.accordion}
      customDetail={
        <Stack sx={{ gap: 1 }}>
          <CardContainer
            padding={16}
            fullWidth
            {...slotProps.cardContainer}
          >
            <Stack sx={{ width: 1, gap: 0.5 }}>
              {options.map(status => (
                <Stack
                  onClick={e => {
                    e.preventDefault();
                    e.stopPropagation();
                    handleStatusCheck(status.value);
                  }}
                  key={status.value}
                  sx={{
                    width: 1,
                    px: 1,
                    py: 0.5,
                    borderRadius: ({ shape }) => shape.borderRadiusM,
                    cursor: 'pointer',
                    '&:hover': {
                      backgroundColor: ({ palette }) =>
                        palette?.new.action.button.background.tertiary.hover,
                    },
                  }}
                >
                  <Checkbox
                    key={status.value}
                    label={status.label}
                    checked={statusesValue.includes(status.value)}
                    {...slotProps.checkbox}
                  />
                </Stack>
              ))}
            </Stack>
          </CardContainer>
        </Stack>
      }
    />
  );
};

export default ServiceItemStatusFormSelect;
