"use client"

import { StyledInputLabel, StyledMenuItem, StyledSelect } from "@/shared/theme/css"
import {
  Box,
  Button,
  Checkbox,
  Dialog,
  DialogActions,
  DialogContent,
  DialogTitle,
  FormControl,
  ListItemText,
  type SelectChangeEvent,
} from "@mui/material"
import { useState } from "react"

interface ExportModalProps {
  open: boolean
  onClose: () => void
  onExport: (selectedIds: string[]) => void
  sheets: { id: string; name: string }[]
}

export default function ExportModal({ open, onClose, onExport, sheets }: ExportModalProps) {
  const [selectedSheets, setSelectedSheets] = useState<string[]>([])

  const handleChange = (event: SelectChangeEvent<unknown>) => {
    const {
      target: { value },
    } = event
    setSelectedSheets(typeof value === "string" ? value.split(",") : (value as string[]))
  }

  const handleExport = () => {
    onExport(selectedSheets)
    setSelectedSheets([])
    onClose()
  }

  return (
    <Dialog open={open} onClose={onClose} maxWidth="sm" fullWidth>
      <DialogTitle>Exporter les feuilles de présence</DialogTitle>
      <DialogContent>
        <Box sx={{ mt: 2 }}>
          <FormControl fullWidth>
            <StyledInputLabel id="export-sheets-label">Sélectionner les feuilles</StyledInputLabel>
            <StyledSelect
              labelId="export-sheets-label"
              multiple
              value={selectedSheets}
              onChange={handleChange}
              renderValue={(selected) => {
                return (selected as string[])
                  .map((id) => sheets.find((sheet) => sheet.id === id)?.id || id)
                  .join(", ")
              }}
            >
              {sheets.map((sheet) => (
                <StyledMenuItem key={sheet.id} value={sheet.id}>
                  <ListItemText primary={sheet.name} />
                </StyledMenuItem>
              ))}
            </StyledSelect>
          </FormControl>
        </Box>
      </DialogContent>
      <DialogActions>
        <Button onClick={onClose} variant="outlined" sx={{ textTransform: "none" }}>
          Annuler
        </Button>
        <Button
          onClick={handleExport}
          variant="contained"
          color="primary"
          sx={{ textTransform: "none" }}
          disabled={selectedSheets.length === 0}
        >
          Exporter
        </Button>
      </DialogActions>
    </Dialog>
  )
}

