import { type FC, useState } from 'react';
import { FormProvider, useForm } from 'react-hook-form';

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

import Button from '@material-hu/components/design-system/Buttons/Button';
import useHuSnackbar from '@material-hu/components/design-system/Snackbar';

import { BUNNY_IMAGE_CLASSES } from 'src/pages/dashboard/Conversations/constants';
import {
  useEditGroup,
  useGetCorrectAttachmentUrl,
  useUploadImage,
} from 'src/pages/dashboard/Conversations/hooks/useConversationsQueries';
import {
  type Channel,
  type FormValuesEditGroup,
} from 'src/pages/dashboard/Conversations/types';
import { formateDataImage } from 'src/pages/dashboard/Conversations/utils';
import { useLokaliseTranslation } from 'src/utils/i18n';

import FormGroupInfo from '../../../shared/FormGroupInfo';

type EditGroupInfoType = {
  title: string;
  onSave: (picture: string, name: string) => void;
  saveLabel: string;
  onClose: () => void;
  conversation: Channel;
};

const EditGroupInfo: FC<EditGroupInfoType> = props => {
  const { title, onClose, conversation } = props;
  const { t } = useLokaliseTranslation(['chat', 'general']);
  const { enqueueSnackbar } = useHuSnackbar();
  const { mutateAsync } = useEditGroup();
  const [previewImage, setPreviewImage] = useState<string | null>(null);
  const form = useForm<FormValuesEditGroup>({
    defaultValues: {
      picture: null,
      name: conversation?.name || '',
    },
  });

  const { data, isLoading } = useGetCorrectAttachmentUrl({
    url: conversation?.hu_data?.picture_url || '',
    enabled: !!conversation?.hu_data?.picture_url,
    imageClass: BUNNY_IMAGE_CLASSES.AVATAR_LG,
  });

  const {
    handleSubmit,
    setValue,
    formState: { isDirty },
  } = form;

  const uploadImgGroupMutation = useUploadImage();

  const handleChange = async (event: React.ChangeEvent<HTMLInputElement>) => {
    try {
      const file = event.target.files?.[0];
      if (!file) return;
      const previewUrl = URL.createObjectURL(file);
      setPreviewImage(previewUrl);

      const dataImage = await uploadImgGroupMutation.mutateAsync(file);

      setValue('picture', formateDataImage(dataImage), { shouldDirty: true });
      URL.revokeObjectURL(previewUrl);
    } catch (error) {
      enqueueSnackbar({
        title: t('chat:errors.upload_image'),
        variant: 'error',
      });
    }
  };

  const submit = async (values: FormValuesEditGroup) => {
    try {
      await mutateAsync({
        channelId: conversation.id,
        name: values.name,
        picture: values.picture,
      });
      onClose();
    } catch (error) {
      enqueueSnackbar({
        title: t('chat:errors.edit_group'),
        variant: 'error',
      });
    }
  };

  return (
    <Stack sx={{ p: 3 }}>
      <Stack
        sx={{
          flexDirection: 'row',
          justifyContent: 'space-between',
          alignItems: 'center',
        }}
      >
        <Typography
          variant="globalS"
          fontWeight="fontWeightSemiBold"
        >
          {title}
        </Typography>
        <IconButton onClick={onClose}>
          <IconX />
        </IconButton>
      </Stack>
      <FormProvider {...form}>
        <Stack sx={{ alignItems: 'center' }}>
          <FormGroupInfo
            name="name"
            picture={previewImage || data}
            isLoading={isLoading || uploadImgGroupMutation.isLoading}
            onChange={handleChange}
          />
        </Stack>
      </FormProvider>
      <Divider sx={{ mt: 2.5, mb: 3 }} />
      <Stack sx={{ alignItems: 'flex-end' }}>
        <Button
          variant="primary"
          disabled={!isDirty}
          onClick={handleSubmit(submit)}
        >
          {t('general:save')}
        </Button>
      </Stack>
    </Stack>
  );
};

export default EditGroupInfo;
