import { Dialog, DialogTitle, DialogContent, DialogActions, Button, Stack, IconButton, Typography, Box } from '@mui/material';
import { useState } from 'react';
import { Formik, Field, Form } from 'formik';
import * as Yup from 'yup';
import dynamic from 'next/dynamic';
import "react-quill/dist/quill.snow.css";
import { StyledDialog } from '@/shared/sections/rh/styles';
import { dialogTitleStyles, dialogTitleTextStyles, StyledTextField } from '@/shared/theme/css';
import FontAwesome from '@/shared/components/fontawesome';
import { faRocketchat } from '@fortawesome/free-brands-svg-icons';
import { Close as CloseIcon } from '@mui/icons-material';
import ConditionalComponent from '@/shared/components/table/ConditionalComponent';
import { enqueueSnackbar } from 'notistack';

const ReactQuill = dynamic(() => import('react-quill'), { ssr: false });

const validationSchema = Yup.object({
  recipient: Yup.string().email('Veuillez entrer une adresse email valide.').required('L\'email est requis.'),
  subject: Yup.string().required('Le sujet est requis.'),
  content: Yup.string().required('Le message est requis.')
});

export interface EmailFormValues {
  recipient: string;
  subject: string;
  content: string;
}

interface GeneralEmailDialogProps {
  open: boolean;
  onClose: () => void;
  onSend: (data: EmailFormValues) => void;
  email?: string;
}

export default function GeneralEmailDialog({
  open,
  onClose,
  onSend,
  email = ''
}: GeneralEmailDialogProps) {

  const handleSubmit = async (values: EmailFormValues, { setSubmitting }: any) => {
    try {
      onSend(values);
      enqueueSnackbar('Email envoyé avec succès', { variant: 'success' });
      onClose();
    } catch (error) {
      enqueueSnackbar('Erreur lors de l\'envoi de l\'email', { variant: 'error' });
    } finally {
      setSubmitting(false);
    }
  };

  return (
    <StyledDialog open={open} onClose={onClose} fullWidth>
      <DialogTitle sx={(theme) => dialogTitleStyles(theme)}>
        <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
          <FontAwesome icon={faRocketchat} width={20} />
          <Typography variant="h6" sx={dialogTitleTextStyles}>
            Envoyer un Email
          </Typography>
        </Box>
        <IconButton aria-label="close" onClick={onClose} size="small" sx={{ color: 'white' }}>
          <CloseIcon />
        </IconButton>
      </DialogTitle>

      <Formik
        initialValues={{ recipient: email, subject: '', content: '' }}
        validationSchema={validationSchema}
        onSubmit={handleSubmit}
        enableReinitialize
      >
        {({ setFieldValue, values, errors, touched, isSubmitting: formikSubmitting }) => (
          <Form>
            <DialogContent sx={{ paddingTop: '24px' }}>
              <Stack spacing={3}>
                <Field
                  name="recipient"
                  as={StyledTextField}
                  label="Email"
                  fullWidth
                  error={touched.recipient && !!errors.recipient}
                  helperText={touched.recipient && errors.recipient}
                />

                <Field
                  name="subject"
                  as={StyledTextField}
                  label="Objet"
                  fullWidth
                  error={touched.subject && !!errors.subject}
                  helperText={touched.subject && errors.subject}
                />
                <Typography variant="subtitle1" gutterBottom>
                  Contenu de l&apos;email
                </Typography>
                <Box
                  sx={{
                    border: values.content ? '1px solid #ddd' : '1px solid red',
                    borderRadius: 1,
                    marginBottom: '8px',
                  }}
                >
                  <ReactQuill
                    theme="snow"
                    value={values.content}
                    onChange={(content) => setFieldValue('content', content)}
                    style={{ height: '250px', marginBottom: '50px' }}
                  />
                </Box>
                <ConditionalComponent isValid={!!errors.content && !!touched.content}>
                  <div style={{ color: 'red', fontSize: '12px' }}>
                    {errors.content}
                  </div>
                </ConditionalComponent>
              </Stack>
            </DialogContent>

            <DialogActions sx={{ padding: '16px 24px', backgroundColor: '#fafafa' }}>
              <Button
                onClick={onClose}
                variant="outlined"
                disabled={formikSubmitting}
                sx={{
                  borderRadius: '8px',
                  padding: '8px 16px',
                  color: 'primary.main',
                  borderColor: 'primary.main',
                  '&:hover': {
                    borderColor: 'primary.dark',
                    color: 'primary.dark',
                  },
                }}
              >
                Annuler
              </Button>
              <Button
                type="submit"
                variant="contained"
                disabled={formikSubmitting}
                sx={{
                  borderRadius: '8px',
                  padding: '8px 16px',
                  backgroundColor: 'primary.main',
                  '&:hover': {
                    backgroundColor: 'primary.dark',
                  },
                }}
              >
                {formikSubmitting ? 'Envoi en cours...' : 'Envoyer'}
              </Button>
            </DialogActions>
          </Form>
        )}
      </Formik>
    </StyledDialog>
  );
}