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

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

import HuFileItem from '@material-hu/components/composed-components/files/FileItem';
import HuSortableList from '@material-hu/components/composed-components/SortableList';

import { SortAttachmentsData, SortableAttachment } from 'src/types/attachments';
import { useLokaliseTranslation } from 'src/utils/i18n';

const AddAttachmentFormContent = () => {
  const { t } = useLokaliseTranslation('general');

  const { control, setValue } = useFormContext<SortAttachmentsData>();
  const attachments = useWatch({ name: 'attachments', control });

  const handleSort = (sortedItems: SortableAttachment[]) => {
    setValue('attachments', sortedItems);
  };

  return (
    <Stack sx={{ gap: 2, height: '100%' }}>
      <Typography variant="globalS">
        {t('attachment.sort.description')}
      </Typography>
      <HuSortableList
        onSort={handleSort}
        items={attachments}
        dragByHandler
        sx={{
          gap: 1,
          flex: 1,
        }}
        ItemComponent={({ item, dragHandleButton }) => (
          <HuFileItem
            startContent={dragHandleButton}
            file={item}
            sx={{ width: '100%' }}
          />
        )}
      />
    </Stack>
  );
};

export default AddAttachmentFormContent;
