"use client"

import type React from "react"

import { useEffect } from "react"
import {
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  Button,
  TextField,
  FormControl,
  InputLabel,
  Select,
  MenuItem,
  IconButton,
  Typography,
  FormControlLabel,
  Radio,
  RadioGroup,
  Chip,
  Autocomplete,
  Grid,
} from "@mui/material"
import { Close as CloseIcon } from "@mui/icons-material"
import { AutomationEvent, AutomationFrequency, type IEmailAutomation } from "@/shared/types/email-automation"
import type { IEmailTemplate } from "@/shared/types/email-template"
import { TimePicker } from "@mui/x-date-pickers/TimePicker"
import { LocalizationProvider } from "@mui/x-date-pickers/LocalizationProvider"
import { AdapterDateFns } from "@mui/x-date-pickers/AdapterDateFns"
import fr from "date-fns/locale/fr"
import { parse, format } from "date-fns"
import ConditionalComponent from "@/shared/components/table/ConditionalComponent"
import { useFormik } from "formik"
import { emailAutomationSchema } from '../utils/email-automation-schema';
import { StyledInputLabel, StyledMenuItem, StyledSelect, StyledTextField, StyledTimePicker } from "@/shared/theme/css"
import { styled } from "@mui/system"
import { TimeValue } from "@/shared/types/usager"
import { Dayjs } from "dayjs"

const StyledDialogContent = styled(DialogContent)(({ theme }) => ({
  backgroundColor: "#fafafa",
  padding: "24px",
  display: "flex",
  flexDirection: "column",
  gap: "16px",
  maxHeight: "70vh",
  overflowY: "auto",
  '&::-webkit-scrollbar': {
    width: '8px',
    background: 'transparent',
  },
  '&::-webkit-scrollbar-thumb': {
    backgroundColor: 'transparent',
    borderRadius: '3px',
    transition: 'background-color 0.2s',
  },
  '&:hover::-webkit-scrollbar-thumb': {
    backgroundColor: theme.palette.grey[400],
  },
}))

interface EmailAutomationFormProps {
  open: boolean
  automation: IEmailAutomation | null
  mode: "add" | "edit" | "view"
  templates: IEmailTemplate[]
  onClose: () => void
  onSave: (automation: IEmailAutomation) => void
}

// Données mock pour les groupes et individus
const mockGroups = ["Tous les employés", "Service RH", "Service IT", "Direction", "Managers", "Nouveaux employés"]

const mockIndividuals = [
  "jean.dupont@example.com",
  "marie.martin@example.com",
  "paul.bernard@example.com",
  "sophie.petit@example.com",
  "thomas.durand@example.com",
]

// Valeurs initiales par défaut
const defaultInitialValues: IEmailAutomation = {
  id: "",
  nom: "",
  templateId: "",
  templateTitre: "",
  declencheur: {
    type: "FREQUENCE",
    frequence: AutomationFrequency.QUOTIDIEN,
  },
  destinataires: {
    type: "GROUPE",
    groupes: [],
  },
  heureEnvoi: "09:00",
  isArchive: false,
}

export default function EmailAutomationForm({
  open,
  automation,
  mode,
  templates,
  onClose,
  onSave,
}: EmailAutomationFormProps) {
  const isReadOnly = mode === "view"

  // Initialisation de Formik
  const formik = useFormik<IEmailAutomation>({
    initialValues: automation || defaultInitialValues,
    validationSchema: emailAutomationSchema,
    onSubmit: (values) => {
      onSave(values)
      if (mode === "add") {
        formik.resetForm({ values: defaultInitialValues })
      }
    },
    enableReinitialize: true,
  })

  // Réinitialiser le formulaire lorsque le dialogue s'ouvre
  useEffect(() => {
    if (open) {
      if (mode === "add" && !automation) {
        formik.resetForm({ values: defaultInitialValues })
      } else if (automation) {
        formik.resetForm({ values: automation })
      }
    }
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [open, mode, automation])

  // Gestion du changement de type de déclencheur
  const handleDeclencheurTypeChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const value = e.target.value as "FREQUENCE" | "EVENEMENT"

    if (value === "FREQUENCE") {
      formik.setFieldValue("declencheur", {
        type: value,
        frequence: AutomationFrequency.QUOTIDIEN,
        evenement: undefined,
      })
    } else {
      formik.setFieldValue("declencheur", {
        type: value,
        evenement: AutomationEvent.AUTRE,
        frequence: undefined,
      })
    }
  }

  // Gestion du changement de type de destinataires
  const handleDestinataireTypeChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const value = e.target.value as "GROUPE" | "INDIVIDU"

    if (value === "GROUPE") {
      formik.setFieldValue("destinataires", {
        type: value,
        groupes: formik.values.destinataires.groupes || [],
        individus: undefined,
      })
    } else {
      formik.setFieldValue("destinataires", {
        type: value,
        individus: formik.values.destinataires.individus || [],
        groupes: undefined,
      })
    }
  }

  // Gestion du changement des groupes
  const handleGroupsChange = (_: any, values: string[]) => {
    formik.setFieldValue("destinataires.groupes", values)
  }

  // Gestion du changement des individus
  const handleIndividualsChange = (_: any, values: string[]) => {
    formik.setFieldValue("destinataires.individus", values)
  }

  const handleTimeChange = (time: TimeValue) => {
    if (time instanceof Date || time instanceof Dayjs) {
      const timeString = format(time as Date, "HH:mm")
      formik.setFieldValue("heureEnvoi", timeString)
    }
  }

  // Convertir l'heure au format string en objet Date pour le TimePicker
  const getTimeValue = () => {
    try {
      if (formik.values.heureEnvoi) {
        return parse(formik.values.heureEnvoi, "HH:mm", new Date())
      }
    } catch (error) {
      console.error("Erreur de parsing de l'heure:", error)
    }
    return new Date()
  }

  // Fonction pour gérer la fermeture du dialogue
  const handleDialogClose = () => {
    if (mode === "add") {
      formik.resetForm({ values: defaultInitialValues })
    }
    onClose()
  }

  // Gestion du changement de modèle d'email
  const handleTemplateChange = (e: React.ChangeEvent<{ value: unknown }>) => {
    const templateId = e.target.value as string
    formik.setFieldValue("templateId", templateId)

    const selectedTemplate = templates.find((t) => t.id === templateId)
    if (selectedTemplate) {
      formik.setFieldValue("templateTitre", selectedTemplate.titre)
    }
  }

  return (
    <LocalizationProvider dateAdapter={AdapterDateFns} adapterLocale={fr}>
      <Dialog
        open={open}
        onClose={handleDialogClose}
        maxWidth="md"
        fullWidth
        PaperProps={{
          sx: {
            borderRadius: 4,
            overflow: "hidden",
          },
        }}
      >
        <DialogTitle
          sx={{
            display: "flex",
            justifyContent: "space-between",
            alignItems: "center",
            backgroundColor: "primary.main",
            color: "white",
            fontWeight: "600",
            padding: "16px 24px",
            borderBottom: (theme) => `1px solid ${theme.palette.divider}`,
          }}
        >
          <Typography variant="h6" sx={{ fontSize: "1.25rem", fontWeight: "bold", color: "white" }}>
            {mode === "add"
              ? "Ajouter une règle d'envoi automatique"
              : mode === "edit"
                ? "Modifier la règle d'envoi automatique"
                : "Détails de la règle d'envoi automatique"}
          </Typography>
          <IconButton aria-label="close" onClick={handleDialogClose} size="small" sx={{ color: "white" }}>
            <CloseIcon />
          </IconButton>
        </DialogTitle>

        <form onSubmit={formik.handleSubmit}>
          <StyledDialogContent
            dividers
          >

            <Grid container spacing={3}>
              <Grid item xs={12}>
                <StyledTextField
                  name="nom"
                  label="Nom de la règle"
                  value={formik.values.nom}
                  onChange={formik.handleChange}
                  onBlur={formik.handleBlur}
                  fullWidth
                  required
                  error={formik.touched.nom && Boolean(formik.errors.nom)}
                  helperText={formik.touched.nom && formik.errors.nom}
                  disabled={isReadOnly}
                />
              </Grid>

              <Grid item xs={12}>
                <FormControl
                  fullWidth
                  error={formik.touched.templateId && Boolean(formik.errors.templateId)}
                  disabled={isReadOnly}
                >
                  <StyledInputLabel id="template-label">Modèle d&#39;email</StyledInputLabel>
                  <StyledSelect
                    labelId="template-label"
                    name="templateId"
                    value={formik.values.templateId}
                    onChange={(e) => handleTemplateChange(e as any)}
                    onBlur={formik.handleBlur}
                    label="Modèle d'email"
                  >
                    {templates
                      .filter((template) => !template.isArchive)
                      .map((template) => (
                        <StyledMenuItem key={template.id} value={template.id}>
                          {template.titre}
                        </StyledMenuItem>
                      ))}
                  </StyledSelect>
                  {formik.touched.templateId && formik.errors.templateId && (
                    <Typography variant="caption" color="error">
                      {formik.errors.templateId as string}
                    </Typography>
                  )}
                </FormControl>
              </Grid>

              <Grid item xs={12}>
                <Typography variant="subtitle1" gutterBottom>
                  Déclencheur
                </Typography>
                <RadioGroup
                  name="declencheur.type"
                  value={formik.values.declencheur.type}
                  onChange={handleDeclencheurTypeChange}
                >
                  <FormControlLabel value="FREQUENCE" control={<Radio disabled={isReadOnly} />} label="Fréquence" />
                  <FormControlLabel
                    value="EVENEMENT"
                    control={<Radio disabled={isReadOnly} />}
                    label="Événement spécifique"
                  />
                </RadioGroup>

                <ConditionalComponent isValid={formik.values.declencheur.type === "FREQUENCE"}>
                  <FormControl
                    fullWidth
                    sx={{ mt: 2 }}
                    error={formik.touched.declencheur?.frequence && Boolean(formik.errors.declencheur?.frequence)}
                    disabled={isReadOnly}
                  >
                    <StyledInputLabel id="frequence-label">Fréquence</StyledInputLabel>
                    <StyledSelect
                      labelId="frequence-label"
                      name="declencheur.frequence"
                      value={formik.values.declencheur.frequence}
                      onChange={formik.handleChange}
                      onBlur={formik.handleBlur}
                      label="Fréquence"
                    >
                      {Object.values(AutomationFrequency).map((freq) => (
                        <StyledMenuItem key={freq} value={freq}>
                          {freq.replace(/_/g, " ")}
                        </StyledMenuItem>
                      ))}
                    </StyledSelect>
                    {formik.touched.declencheur?.frequence && formik.errors.declencheur?.frequence && (
                      <Typography variant="caption" color="error">
                        {formik.errors.declencheur.frequence as string}
                      </Typography>
                    )}
                  </FormControl>
                </ConditionalComponent>

                <ConditionalComponent isValid={formik.values.declencheur.type === "EVENEMENT"}>
                  <FormControl
                    fullWidth
                    sx={{ mt: 2 }}
                    error={formik.touched.declencheur?.evenement && Boolean(formik.errors.declencheur?.evenement)}
                    disabled={isReadOnly}
                  >
                    <StyledInputLabel id="evenement-label">Événement</StyledInputLabel>
                    <StyledSelect
                      labelId="evenement-label"
                      name="declencheur.evenement"
                      value={formik.values.declencheur.evenement}
                      onChange={formik.handleChange}
                      onBlur={formik.handleBlur}
                      label="Événement"
                    >
                      {Object.values(AutomationEvent).map((event) => (
                        <StyledMenuItem key={event} value={event}>
                          {event.replace(/_/g, " ")}
                        </StyledMenuItem>
                      ))}
                    </StyledSelect>
                    {formik.touched.declencheur?.evenement && formik.errors.declencheur?.evenement && (
                      <Typography variant="caption" color="error">
                        {formik.errors.declencheur.evenement as string}
                      </Typography>
                    )}
                  </FormControl>
                </ConditionalComponent>
              </Grid>

              <Grid item xs={12}>
                <Typography variant="subtitle1" gutterBottom>
                  Destinataires
                </Typography>
                <RadioGroup
                  name="destinataires.type"
                  value={formik.values.destinataires.type}
                  onChange={handleDestinataireTypeChange}
                >
                  <FormControlLabel value="GROUPE" control={<Radio disabled={isReadOnly} />} label="Groupes" />
                  <FormControlLabel
                    value="INDIVIDU"
                    control={<Radio disabled={isReadOnly} />}
                    label="Individus spécifiques"
                  />
                </RadioGroup>

                <ConditionalComponent isValid={formik.values.destinataires.type === "GROUPE"}>
                  <Autocomplete
                    multiple
                    options={mockGroups}
                    value={formik.values.destinataires.groupes || []}
                    onChange={handleGroupsChange}
                    disabled={isReadOnly}
                    renderTags={(value, getTagProps) =>
                      value.map((option, index) => <Chip label={option} {...getTagProps({ index })} key={option} />)
                    }
                    renderInput={(params) => (
                      <StyledTextField
                        {...params}
                        label="Sélectionner des groupes"
                        error={formik.touched.destinataires?.groupes && Boolean(formik.errors.destinataires?.groupes)}
                        helperText={
                          formik.touched.destinataires?.groupes && (formik.errors.destinataires?.groupes as string)
                        }
                        sx={{ mt: 2 }}
                      />
                    )}
                  />
                </ConditionalComponent>

                <ConditionalComponent isValid={formik.values.destinataires.type === "INDIVIDU"}>
                  <Autocomplete
                    multiple
                    options={mockIndividuals}
                    value={formik.values.destinataires.individus || []}
                    onChange={handleIndividualsChange}
                    disabled={isReadOnly}
                    renderTags={(value, getTagProps) =>
                      value.map((option, index) => <Chip label={option} {...getTagProps({ index })} key={option} />)
                    }
                    renderInput={(params) => (
                      <StyledTextField
                        {...params}
                        label="Sélectionner des destinataires"
                        error={
                          formik.touched.destinataires?.individus && Boolean(formik.errors.destinataires?.individus)
                        }
                        helperText={
                          formik.touched.destinataires?.individus && (formik.errors.destinataires?.individus as string)
                        }
                        sx={{ mt: 2 }}
                      />
                    )}
                  />
                </ConditionalComponent>
              </Grid>

              <Grid item xs={12}>
             
                <StyledTimePicker
                  label="Heure d'envoi"
                  value={getTimeValue()}
                  onChange={handleTimeChange}
                  disabled={isReadOnly}
                  slotProps={{
                    textField: {
                      fullWidth: true,
                      error: formik.touched.heureEnvoi && Boolean(formik.errors.heureEnvoi),
                      helperText: formik.touched.heureEnvoi && (formik.errors.heureEnvoi as string),
                    },
                  }}
                />
              </Grid>
            </Grid>

            
          </StyledDialogContent>
          <DialogActions sx={{ padding: "16px 24px", backgroundColor: "#fafafa" }}>
            <Button
              onClick={handleDialogClose}
              variant="outlined"
              type="button"
              sx={{
                borderRadius: "8px",
                padding: "8px 16px",
                color: "primary.main",
                borderColor: "primary.main",
                "&:hover": {
                  borderColor: "primary.dark",
                  color: "primary.dark",
                },
              }}
            >
              {isReadOnly ? "Fermer" : "Annuler"}
            </Button>

            <ConditionalComponent isValid={!isReadOnly}>
              <Button
                variant="contained"
                type="button"
                onClick={() => {
                  formik.validateForm().then((errors) => {
                    formik.submitForm()
                    })
                }}
                sx={{
                  borderRadius: "8px",
                  padding: "8px 16px",
                  backgroundColor: "primary.main",
                  "&:hover": {
                    backgroundColor: "primary.dark",
                  },
                  boxShadow: 2,
                }}
              >
                {mode === "add" ? "Ajouter" : "Enregistrer"}
              </Button>
            </ConditionalComponent>
          </DialogActions>
        </form>
      </Dialog>
    </LocalizationProvider>
  )
}
