import { useState, useMemo } from 'react';
// @mui
import Paper from '@mui/material/Paper';
import Stack from '@mui/material/Stack';
import Portal from '@mui/material/Portal';
import Backdrop from '@mui/material/Backdrop';
import IconButton from '@mui/material/IconButton';
import Typography from '@mui/material/Typography';
// hooks
import { useBoolean } from 'src/hooks/use-boolean';
import { useResponsive } from 'src/hooks/use-responsive';
// components
import Iconify from 'src/components/iconify';
import Editor from 'src/components/editor';
import { Invoice } from 'src/schemas';
import FormProvider from 'src/components/hook-form/form-provider';
import { RHFTextField } from 'src/components/hook-form';
import { useForm } from 'react-hook-form';
import { LoadingButton } from '@mui/lab';
import { enqueueSnackbar } from 'notistack';
import {
  collectionRef,
  collections,
  createDocId,
  createDocument,
  firestoreBatch,
} from 'src/lib/firestore';
import { storage } from 'src/lib/firebase';
import { getDownloadURL, ref } from 'firebase/storage';
import { increment } from 'firebase/firestore';
import { mutate } from 'swr';

// ----------------------------------------------------------------------

const ZINDEX = 1998;

const POSITION = 24;

type Props = {
  invoice: Invoice | null;
  onCloseCompose: VoidFunction;
  invoiceMutationKey: string[];
};

export default function MailCompose({ invoice, onCloseCompose, invoiceMutationKey }: Props) {
  const smUp = useResponsive('up', 'sm');

  const fullScreen = useBoolean(false);

  // const handleChangeMessage = useCallback((value: string) => {
  //   setMessage(value);
  // }, []);

  const defaultValues = useMemo(
    () => ({
      to: invoice?.invoiceTo?.email || '',
      subject: `New Invoice for ${invoice?.month} - MVP Masters`,
      message: `<p>Dear ${
        invoice?.invoiceTo?.representative || ''
      }, </p><p></p><p>We hope this email finds you well. Please find attached the invoice for ${invoice?.month}, detailing the work MVP Masters has completed during that period. We appreciate your prompt attention to this invoice. </p><p></p><p>Should you have any questions or require further clarification on any items, please don't hesitate to reply to this email.</p><p></p><p>Thank you for your continued partnership and trust in MVP Masters.</p><p><br></p><p>Warm regards,</p><p>Finance Team</p><p>MVP Masters</p>`,
    }),
    [invoice]
  );

  const methods = useForm({
    defaultValues,
  });

  const {
    reset,
    handleSubmit,
    watch,
    setValue,
    formState: { isSubmitting },
  } = methods;

  const values = watch();

  const onSubmit = handleSubmit(async (data) => {
    try {
      if (!invoice) return;
      // await new Promise((resolve) => setTimeout(resolve, 500));

      const pdfFilename = invoice.pdfRef?.split('/').pop() as string;
      const invoicePDFRef = ref(storage, invoice.pdfRef);
      const url = await getDownloadURL(invoicePDFRef);

      const mailData = {
        from: '<MVP Masters - Finance Team> finance@mvpmasters.com',
        to: invoice.invoiceTo.email,
        message: {
          subject: data.subject,
          html: data.message,
          attachments: [
            {
              filename: pdfFilename,
              path: url,
            },
          ],
        },
      };

      const invoiceData = {
        sent: increment(1),
        status: 'pending',
      };

      const mailId = createDocId(collections.mail);

      // write to DB
      await firestoreBatch<any>([
        {
          docPath: `${collections.mail}/${mailId}`,
          type: 'set',
          data: mailData,
        },
        {
          docPath: `${collections.invoice}/${invoice.id}`,
          type: 'set',
          data: invoiceData,
        },
      ]);

      mutate(invoiceMutationKey);

      reset();
      onCloseCompose();
      enqueueSnackbar('Invoice sent!');
      console.info('DATA', data);
    } catch (error) {
      console.error(error);
    }
  });

  return (
    <Portal>
      {(fullScreen.value || !smUp) && <Backdrop open sx={{ zIndex: ZINDEX }} />}

      <Paper
        sx={{
          right: 0,
          bottom: 0,
          borderRadius: 2,
          display: 'flex',
          position: 'fixed',
          zIndex: ZINDEX + 1,
          m: `${POSITION}px`,
          overflow: 'hidden',
          flexDirection: 'column',
          boxShadow: (theme) => theme.customShadows.dropdown,
          ...(fullScreen.value && {
            m: 0,
            right: POSITION / 2,
            bottom: POSITION / 2,
            width: `calc(100% - ${POSITION}px)`,
            height: `calc(100% - ${POSITION}px)`,
          }),
        }}
      >
        <Stack
          direction="row"
          alignItems="center"
          sx={{
            bgcolor: 'background.neutral',
            p: (theme) => theme.spacing(1.5, 1, 1.5, 2),
          }}
        >
          <Typography variant="h6" sx={{ flexGrow: 1 }}>
            Inv. {invoice?.invoiceNumber} - {invoice?.invoiceTo?.name}
          </Typography>

          <IconButton onClick={fullScreen.onToggle}>
            <Iconify icon={fullScreen ? 'eva:collapse-fill' : 'eva:expand-fill'} />
          </IconButton>

          <IconButton onClick={onCloseCompose}>
            <Iconify icon="mingcute:close-line" />
          </IconButton>
        </Stack>

        <FormProvider methods={methods} onSubmit={onSubmit}>
          <RHFTextField sx={{ px: 2, py: 2 }} variant="standard" name="to" placeholder="To" />
          <RHFTextField
            sx={{ px: 2, py: 1 }}
            variant="standard"
            name="subject"
            placeholder="Subject"
          />

          {/* <InputBase
          placeholder="To"
          // endAdornment={
          //   <Stack direction="row" spacing={0.5} sx={{ typography: 'subtitle2' }}>
          //     <Box
          //       sx={{
          //         cursor: 'pointer',
          //         '&:hover': { textDecoration: 'underline' },
          //       }}
          //     >
          //       Cc
          //     </Box>
          //     <Box
          //       sx={{
          //         cursor: 'pointer',
          //         '&:hover': { textDecoration: 'underline' },
          //       }}
          //     >
          //       Bcc
          //     </Box>
          //   </Stack>
          // }
          sx={{
            px: 2,
            height: 48,
            borderBottom: (theme) => `solid 1px ${alpha(theme.palette.grey[500], 0.08)}`,
          }}
        /> */}

          {/* <InputBase
          placeholder="Subject"
          sx={{
            px: 2,
            height: 48,
            borderBottom: (theme) => `solid 1px ${alpha(theme.palette.grey[500], 0.08)}`,
          }}
        /> */}

          <Stack spacing={2} flexGrow={1} sx={{ p: 2 }}>
            <Editor
              simple
              id="compose-mail"
              // value={message}
              // onChange={handleChangeMessage}
              value={values.message}
              onChange={(value) => setValue('message', value)}
              placeholder="Type a message"
              sx={{
                '& .ql-editor': {},
                ...(fullScreen.value && {
                  height: 1,
                  '& .quill': {
                    height: 1,
                  },
                  '& .ql-editor': {
                    maxHeight: 'unset',
                  },
                }),
              }}
            />

            <Stack direction="row" alignItems="center">
              <Stack direction="row" alignItems="center" flexGrow={1}>
                <IconButton>
                  <Iconify icon="solar:gallery-add-bold" />
                </IconButton>

                <IconButton>
                  <Iconify icon="eva:attach-2-fill" />
                </IconButton>
              </Stack>

              <LoadingButton
                type="submit"
                variant="contained"
                color="primary"
                loading={isSubmitting}
                endIcon={<Iconify icon="iconamoon:send-fill" />}
              >
                Send
              </LoadingButton>
            </Stack>
          </Stack>
        </FormProvider>
      </Paper>
    </Portal>
  );
}
