import { useEffect, useMemo } from 'react';
import { FormProvider, useForm } from 'react-hook-form';

import { zodResolver } from '@hookform/resolvers/zod';

import Alert from '@material-hu/components/design-system/Alert';
import { type FileCardType } from '@material-hu/components/design-system/FileCard/types';
import { Drawer, useDrawerLayer } from '@material-hu/components/layers/Drawers';

import { useAuth } from 'src/contexts/JWTContext';
import { buildAcknowledgementValues } from 'src/pages/dashboard/acknowledgements/utils';
import { urlToFile } from 'src/utils/files';
import { useLokaliseTranslation } from 'src/utils/i18n';

import { DEFAULT_KUDOS_VALUES } from '../../constants';
import { useCreateAcknowledgement } from '../../hooks/useCreateAcknowledgement';
import { useGetAcknowledgement } from '../../hooks/useGetAcknowledgement';
import { useUpdateAcknowledgement } from '../../hooks/useUpdateAcknowledgement';

import { AcknowledgementMessage } from './components/AcknowledgementMessage';
import { SelectAcknowledgedsUsers } from './components/SelectAcknowledgedsUsers';
import { SelectAcknowledgementMultimedia } from './components/SelectAcknowledgementMultimedia';
import { SelectCategoryInput } from './components/SelectCategoryInput';
import { createKudosFormSchema } from './schemas';
import { type CreateKudosFormValues } from './types';

type KudosCreateDrawerProps = { acknowledgementId?: number };

const KudosCreateDrawer = ({ acknowledgementId }: KudosCreateDrawerProps) => {
  const { user } = useAuth();
  const { t } = useLokaliseTranslation('acknowledgements');
  const { closeDrawer } = useDrawerLayer();

  const isCreate = !acknowledgementId;

  const schema = useMemo(() => createKudosFormSchema(t), [t]);

  const { data: acknowledgement } = useGetAcknowledgement(acknowledgementId);

  const attachments = acknowledgement?.attachments || [];

  const form = useForm<CreateKudosFormValues>({
    defaultValues: DEFAULT_KUDOS_VALUES,
    values: buildAcknowledgementValues(acknowledgement),
    resolver: zodResolver(schema),
  });

  const { setValue, reset, handleSubmit } = form;

  useEffect(() => {
    if (!attachments.length) return;

    let cancelled = false;

    const loadAttachments = async () => {
      const results = await Promise.allSettled(
        attachments.map(async (attachment): Promise<FileCardType> => {
          const file = await urlToFile(attachment.url ?? '');
          return {
            status: 'success',
            file,
            attachment: {
              url: attachment.url ?? '',
              name: attachment.name ?? '',
              size: attachment.size ?? '',
              bytes: file.size,
              type: attachment.type,
            },
          };
        }),
      );

      if (cancelled) return;

      const files = results
        .filter(result => result.status === 'fulfilled')
        .map(result => result.value);

      setValue('attachments', files);
    };

    loadAttachments();

    return () => {
      cancelled = true;
    };
  }, [attachments, setValue]);

  const handleCloseDrawer = () => {
    reset();
    closeDrawer();
  };

  const createAcknowledgement = useCreateAcknowledgement();
  const updateAcknowledgement = useUpdateAcknowledgement(acknowledgementId);

  const mutation = isCreate ? createAcknowledgement : updateAcknowledgement;

  const onSubmit = (formValues: CreateKudosFormValues) => {
    mutation.mutate(formValues, {
      onSuccess: () => {
        reset();
        closeDrawer();
      },
    });
  };

  const drawerTitle = isCreate ? t('send_recognition') : t('edit_ack');

  return (
    <FormProvider {...form}>
      <Drawer.Header
        title={drawerTitle}
        hasBackButton
        onClose={handleCloseDrawer}
      />
      <Drawer.Body slotProps={{ sx: { gap: 3 } }}>
        <Alert
          title={t('available_recognition', {
            amount: user?.acknowledgementsToGiveLeft,
          })}
          description={t('available_recognition_description')}
          severity="highlight"
          hasClose
        />
        {isCreate && (
          <>
            <SelectAcknowledgedsUsers />
            <SelectCategoryInput />
          </>
        )}
        <AcknowledgementMessage />
        <SelectAcknowledgementMultimedia />
      </Drawer.Body>
      <Drawer.Actions
        primaryButtonProps={{
          children: t('general:publish'),
          fullWidth: true,
          onClick: handleSubmit(onSubmit),
          disabled: mutation.isLoading,
          loading: mutation.isLoading,
        }}
        secondaryButtonProps={{
          disabled: mutation.isLoading,
          children: t('general:cancel'),
          fullWidth: true,
          onClick: handleCloseDrawer,
        }}
      />
    </FormProvider>
  );
};

export default KudosCreateDrawer;
