"use client"

import { useState } from "react"
import {
  Box,
  Typography,
  Divider,
  FormGroup,
  FormControlLabel,
  Checkbox,
  TextField,
  Accordion,
  AccordionSummary,
  AccordionDetails,
  Button,
} from "@mui/material"
import { ExpandMore as ExpandMoreIcon } from "@mui/icons-material"
import { EmailStatus, type IEmailFilter } from "@/shared/types/email"
import { DatePicker } from "@mui/x-date-pickers/DatePicker"
import { LocalizationProvider } from "@mui/x-date-pickers/LocalizationProvider"
import { AdapterDateFns } from "@mui/x-date-pickers/AdapterDateFns"
import fr from "date-fns/locale/fr"

interface EmailFiltersProps {
  onFilterChange: (filters: IEmailFilter) => void
}

export default function EmailFilters({ onFilterChange }: EmailFiltersProps) {
  const [dateDebut, setDateDebut] = useState<Date | undefined>(undefined)
  const [dateFin, setDateFin] = useState<Date | undefined>(undefined)
  const [selectedStatuses, setSelectedStatuses] = useState<EmailStatus[]>([])
  const [searchQuery, setSearchQuery] = useState<string>("")

  const handleStatusChange = (status: EmailStatus) => {
    setSelectedStatuses((prev) => {
      if (prev.includes(status)) {
        return prev.filter((s) => s !== status)
      } else {
        return [...prev, status]
      }
    })
  }

  const handleResetFilters = () => {
    setDateDebut(undefined)
    setDateFin(undefined)
    setSelectedStatuses([])
    setSearchQuery("")

    // Notify parent of reset
    onFilterChange({})
  }

  const handleApplyFilters = () => {
    const filters: IEmailFilter = {}

    if (dateDebut) {
      filters.dateDebut = dateDebut
    }

    if (dateFin) {
      filters.dateFin = dateFin
    }

    if (selectedStatuses.length > 0) {
      filters.status = selectedStatuses
    }

    if (searchQuery) {
      filters.recherche = searchQuery
    }

    onFilterChange(filters)
  }

  return (
    <LocalizationProvider dateAdapter={AdapterDateFns} adapterLocale={fr}>
      <Box sx={{ p: 2 }}>
        <Box sx={{ display: "flex", justifyContent: "space-between", alignItems: "center", mb: 2 }}>
          <Typography variant="h6">Filtres</Typography>
          <Button size="small" onClick={handleResetFilters}>
            Réinitialiser
          </Button>
        </Box>

        <Divider sx={{ mb: 2 }} />

        <Accordion defaultExpanded>
          <AccordionSummary expandIcon={<ExpandMoreIcon />}>
            <Typography>Période</Typography>
          </AccordionSummary>
          <AccordionDetails>
            <Box sx={{ display: "flex", flexDirection: "column", gap: 2 }}>
              <DatePicker
                label="Date de début"
                value={dateDebut}
                onChange={(newValue) => {setDateDebut(newValue || undefined)}}
                slotProps={{ textField: { size: "small", fullWidth: true } }}
              />
              <DatePicker
                label="Date de fin"
                value={dateFin}
                onChange={(newValue) => setDateFin(newValue || undefined)}
                slotProps={{ textField: { size: "small", fullWidth: true } }}
              />
            </Box>
          </AccordionDetails>
        </Accordion>

        <Accordion defaultExpanded>
          <AccordionSummary expandIcon={<ExpandMoreIcon />}>
            <Typography>Statut</Typography>
          </AccordionSummary>
          <AccordionDetails>
            <FormGroup>
              <FormControlLabel
                control={
                  <Checkbox
                    checked={selectedStatuses.includes(EmailStatus.ENVOYE)}
                    onChange={() => handleStatusChange(EmailStatus.ENVOYE)}
                    size="small"
                  />
                }
                label="Envoyé"
              />
              <FormControlLabel
                control={
                  <Checkbox
                    checked={selectedStatuses.includes(EmailStatus.EN_ATTENTE)}
                    onChange={() => handleStatusChange(EmailStatus.EN_ATTENTE)}
                    size="small"
                  />
                }
                label="En attente"
              />
              <FormControlLabel
                control={
                  <Checkbox
                    checked={selectedStatuses.includes(EmailStatus.ECHEC)}
                    onChange={() => handleStatusChange(EmailStatus.ECHEC)}
                    size="small"
                  />
                }
                label="Échec"
              />
            </FormGroup>
          </AccordionDetails>
        </Accordion>

        <Accordion defaultExpanded>
          <AccordionSummary expandIcon={<ExpandMoreIcon />}>
            <Typography>Recherche</Typography>
          </AccordionSummary>
          <AccordionDetails>
            <TextField
              label="Rechercher"
              size="small"
              fullWidth
              value={searchQuery}
              placeholder="Destinataire, objet..."
              onChange={(e) => setSearchQuery(e.target.value)}
            />
          </AccordionDetails>
        </Accordion>

        <Button variant="contained" fullWidth onClick={handleApplyFilters} sx={{ mt: 2 }}>
          Appliquer les filtres
        </Button>
      </Box>
    </LocalizationProvider>
  )
}

