import { useCallback, useState } from 'react';
import { useFieldArray, useFormContext } from 'react-hook-form';

import { IconX } from '@material-hu/icons/tabler';
import IconButton from '@material-hu/mui/IconButton';
import Stack from '@material-hu/mui/Stack';
import { styled } from '@material-hu/mui/styles';
import Typography from '@material-hu/mui/Typography';

import SortableList from '@material-hu/components/composed-components/SortableList';
import { type ItemComponentProps } from '@material-hu/components/composed-components/SortableList/types';
import Button from '@material-hu/components/design-system/Buttons/Button';
import FormInputClassic from '@material-hu/components/design-system/Inputs/Classic/form';
import RadioBase from '@material-hu/components/design-system/RadioButton/RadioBase';
import FormSwitcher from '@material-hu/components/design-system/Switcher/form';

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

const Form = () => {
  const [isTitleFocused, setIsTitleFocused] = useState(false);

  const { t } = useLokaliseTranslation('livestream');

  const { control } = useFormContext();

  const { fields, append, remove, move } = useFieldArray({
    control: control,
    name: 'pollOptions',
  });

  const renderItem = useCallback(
    (
      props: ItemComponentProps<{
        id: string;
      }>,
    ) => (
      <PollOptionItem
        {...props}
        onRemove={() => remove(props.index)}
        isRemoveDisabled={fields.length <= 2}
      />
    ),
    [fields.length, remove],
  );

  return (
    <Stack sx={{ gap: 2 }}>
      <FieldContainer>
        <FormInputClassic
          name="title"
          inputProps={{
            label: t('general:question'),
            multiline: true,
            maxLength: 250,
            hasCounter: isTitleFocused,
            onFocus: () => {
              setIsTitleFocused(true);
            },
            onBlur: () => {
              setIsTitleFocused(false);
            },
          }}
        />
      </FieldContainer>
      <FieldContainer>
        <Stack sx={{ gap: 2 }}>
          <Typography
            variant="globalS"
            fontWeight="fontWeightSemiBold"
            color="new.text.neutral.default"
          >
            {t('general:options')}
          </Typography>
          <SortableList
            items={fields}
            slotProps={{
              dragIcon: {
                size: 16,
              },
            }}
            ItemComponent={renderItem}
            onSort={(_, oldIndex, newIndex) => move(oldIndex, newIndex)}
            sx={{
              gap: 1,
              width: '100%',
              height: 'auto',
              overflowY: 'visible',
            }}
            dragByHandler
          />

          <Button
            size="small"
            variant="tertiary"
            onClick={() => append({ value: '' })}
            disabled={fields.length >= 4}
          >
            {t('polls.drawer.add_option')}
          </Button>
        </Stack>
      </FieldContainer>
      <FieldContainer>
        <FormSwitcher
          name="viewVotesResult"
          switcherProps={{
            title: t('polls.show_results'),
            titleProps: {
              sx: {
                color: 'new.text.neutral.default',
              },
            },
          }}
        />
      </FieldContainer>
    </Stack>
  );
};

const FieldContainer = styled(Stack)(({ theme }) => ({
  padding: theme.spacing(2),
  backgroundColor: theme.palette.new.background.layout.default,
  borderRadius: '16px',
}));

const PollOptionItem: React.FC<
  ItemComponentProps<{
    id: string;
  }> & {
    isRemoveDisabled: boolean;
    onRemove: () => void;
  }
> = props => {
  const { item, dragHandleButton, index, isRemoveDisabled, onRemove } = props;
  const { t } = useLokaliseTranslation('livestream');

  return (
    <Stack
      key={item.id}
      sx={{
        flexDirection: 'row',
        alignItems: 'center',
        gap: 1,
      }}
    >
      {dragHandleButton}
      <RadioBase
        tabIndex={-1}
        disabled
      />
      <FormInputClassic
        name={`pollOptions.${index}.value`}
        inputProps={{
          placeholder: t('polls.drawer.option_index', {
            index: index + 1,
          }),
          hasCounter: false,
          size: 'small',
          maxLength: 100,
        }}
      />
      <IconButton
        size="small"
        variant="tertiary"
        onClick={onRemove}
        disabled={isRemoveDisabled}
      >
        <IconX size={16} />
      </IconButton>
    </Stack>
  );
};

export default Form;
