import { FC, useState } from 'react';
import { useNavigate } from 'react-router-dom';

import Box from '@material-hu/mui/Box';
import Divider from '@material-hu/mui/Divider';
import ListItem from '@material-hu/mui/ListItem';
import ListItemText from '@material-hu/mui/ListItemText';
import Tooltip from '@material-hu/mui/Tooltip';
import Typography from '@material-hu/mui/Typography';

import { FormItemResponse, FormStepType } from 'src/types/forms';
import { useLokaliseTranslation } from 'src/utils/i18n';

import AcceptCancelDialog from 'src/components/AcceptCancelDialog';
import FormChatAvatar from 'src/components/dashboard/chat/ChatAvatar/FormChatAvatar';
import FormAvailableMenu from 'src/components/dashboard/form/FormAvailableMenu';
import { formRoutes } from 'src/components/dashboard/form/routes';

export type FormListAvailableItemProps = {
  id: number;
  stepsType: string;
  isAnonymous?: boolean;
} & Pick<
  FormItemResponse,
  'hasActiveRequests' | 'pictureUrl' | 'type' | 'title'
>;

export const FormListAvailableItem: FC<FormListAvailableItemProps> = props => {
  const {
    pictureUrl,
    id,
    type,
    title,
    isAnonymous = false,
    stepsType,
    hasActiveRequests,
  } = props;
  const [open, setOpen] = useState(false);

  const { t } = useLokaliseTranslation('forms');
  const navigate = useNavigate();

  const isPdfForm = stepsType === FormStepType.FILE;

  const handleComfirm = () => {
    setOpen(false);
    return navigate(
      isPdfForm
        ? formRoutes.form.pdfDetail(type, id)
        : formRoutes.form.detail(type, id),
    );
  };

  const handleSelect = () =>
    hasActiveRequests ? setOpen(hasActiveRequests) : handleComfirm();

  return (
    <>
      <ListItem
        button
        onClick={handleSelect}
        sx={{
          display: 'flex',
          flexDirection: 'row',
          justifyContent: 'space-between',
        }}
      >
        <FormChatAvatar pictureUrl={pictureUrl} />
        <ListItemText
          primary={<>{title}</>}
          primaryTypographyProps={{
            color: 'textPrimary',
            noWrap: true,
            variant: 'subtitle2',
          }}
        />
        {isAnonymous && (
          <Tooltip title={t('post:anonymous_answer')}>
            <Typography sx={{ mr: 1 }}>🤫</Typography>
          </Tooltip>
        )}
        <Box>
          <FormAvailableMenu
            id={id}
            type={type}
            isPdfForm={isPdfForm}
          />
        </Box>
      </ListItem>
      <Divider
        sx={{
          ml: 11,
          '&:last-child': {
            display: 'none',
          },
        }}
      />
      <AcceptCancelDialog
        open={open}
        onCancel={() => setOpen(false)}
        onAccept={handleComfirm}
        showCancel
      >
        <Typography>{t('CONFIRM_RE_COMPLETE_FORM')}</Typography>
      </AcceptCancelDialog>
    </>
  );
};

export default FormListAvailableItem;
