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

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

import { logEvent } from 'src/config/logging';
import { EventName } from 'src/types/amplitude';
import { Attachment } from 'src/types/attachments';
import { LibraryValues } from 'src/types/libraries';

import FormRichEditor from 'src/components/dashboard/form/formDetail/inputs/FormRichEditor';
import FormTitle from 'src/components/FormInputs/FormTitle';

import { formatLibraryDefaultValues } from '../utils';

import FormAttachments from './FormAttachments';
import FormLibraryCoverPicture from './FormLibraryCoverPicture';
import {
  LibraryArticleLayout,
  LibraryArticleLayoutProps,
} from './LibraryArticleLayout';

export type LibraryFormProps = Omit<LibraryArticleLayoutProps, 'children'>;

export const LibraryForm = ({ library, ...layoutProps }: LibraryFormProps) => {
  const form = useForm<LibraryValues>({
    defaultValues: formatLibraryDefaultValues(library),
  });

  const handleDownloadAttachment = (attachment: Attachment) => {
    logEvent(EventName.WIDGET_LIBRARY_ATTACHMENT_DOWNLOAD, {
      widgetId: library.id,
      parentId: library.parentId,
      name: library.title,
      fileType: attachment.type,
      fileName: attachment.name,
    });
  };

  return (
    <FormProvider {...form}>
      <LibraryArticleLayout
        library={library}
        {...layoutProps}
      >
        <Card
          sx={{
            display: 'flex',
            flexDirection: 'column',
            alignItems: 'center',
            justifyContent: 'flex-start',
          }}
        >
          <FormLibraryCoverPicture name="coverPicture" />
          <Stack
            sx={{
              mx: 10,
              my: 4,
              alignItems: 'center',
              justifyContent: 'center',
              gap: 4,
            }}
          >
            <FormTitle
              name="title"
              iconName="icon"
            />
            <FormRichEditor
              name="body"
              simplifyEditor={false}
            />
          </Stack>
        </Card>
        <FormAttachments
          name="attachments"
          inputProps={{
            onDownload: handleDownloadAttachment,
          }}
        />
      </LibraryArticleLayout>
    </FormProvider>
  );
};

export default LibraryForm;
