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

import { IconFolder } from '@material-hu/icons/tabler';
import Stack from '@material-hu/mui/Stack';
import { appearFromBottom } from '@material-hu/utils/animations';

import CardContainer from '@material-hu/components/design-system/CardContainer';
import ListItem from '@material-hu/components/design-system/List/components/ListItem';
import FormUploader from '@material-hu/components/design-system/Uploader/form';

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

import { MAX_FILE_SIZE_BYTES, UPLOAD_FIELDS } from '../../constants';
import { type UploadFormValues } from '../../types';

const UploadFileStep = () => {
  const { t } = useLokaliseTranslation('agents');
  const { control } = useFormContext<UploadFormValues>();

  const folderPath = useWatch({ control, name: UPLOAD_FIELDS.folderPath });
  const folderName = folderPath
    ? folderPath.split('/').filter(Boolean).at(-1)
    : null;

  const Wrapper = folderName ? CardContainer : Stack;

  return (
    <Wrapper
      {...(folderName ? { fullWidth: true } : {})}
      sx={{
        animation: `${appearFromBottom} 0.3s ease-in-out`,
        backgroundColor: theme => theme.palette.new.background.layout.tertiary,
        borderRadius: theme => theme.shape.borderRadiusL,
      }}
    >
      {folderName && (
        <ListItem
          text={{ title: folderName, copetin: t('upload.folder_copetin') }}
          avatar={{ Icon: IconFolder }}
          slotProps={{ container: { sx: { p: 0, mb: 2 } } }}
        />
      )}

      <FormUploader
        name={UPLOAD_FIELDS.files}
        uploaderProps={{
          sx: { width: '100%' },
          fileSizeLimit: MAX_FILE_SIZE_BYTES,
          maxFiles: 1,
          showUploadButtonOnMaxFiles: false,
          acceptedTypes: ['pdf', 'msword', 'text'],
          description: t('upload.file_zone_formats'),
          uploadFunction: file =>
            new Promise(resolve => resolve({ status: 'success', file })),
        }}
      />
    </Wrapper>
  );
};

export default UploadFileStep;
