"use client"

import type React from "react"

import { useState } from "react"
import { IconButton, Menu, MenuItem, Checkbox, ListItemText, Divider, Typography, Box } from "@mui/material"
import { FilterList as FilterIcon } from "@mui/icons-material"

interface FileTypeFilterProps {
  fileTypes: string[]
  selectedFileTypes: string[]
  onChange: (selectedTypes: string[]) => void
}

export default function FileTypeFilter({ fileTypes, selectedFileTypes, onChange }: FileTypeFilterProps) {
  const [anchorEl, setAnchorEl] = useState<null | HTMLElement>(null)
  const open = Boolean(anchorEl)

  const handleClick = (event: React.MouseEvent<HTMLElement>) => {
    setAnchorEl(event.currentTarget)
  }

  const handleClose = () => {
    setAnchorEl(null)
  }

  const handleToggle = (fileType: string) => {
    const currentIndex = selectedFileTypes.indexOf(fileType)
    const newSelectedFileTypes = [...selectedFileTypes]

    if (currentIndex === -1) {
      newSelectedFileTypes.push(fileType)
    } else {
      newSelectedFileTypes.splice(currentIndex, 1)
    }

    onChange(newSelectedFileTypes)
  }

  return (
    <>
      <IconButton
        aria-label="filter list"
        onClick={handleClick}
        color={selectedFileTypes.length > 0 ? "primary" : "default"}
      >
        <FilterIcon />
      </IconButton>
      <Menu anchorEl={anchorEl} open={open} onClose={handleClose}>
        <Box sx={{ px: 2, pb: 1 }}>
          <Typography variant="subtitle2" color={'primary.main'}>Filtrer par type</Typography>
        </Box>
        <Divider />
        {fileTypes.map((fileType) => {
          const formattedLabel = fileType.charAt(0).toUpperCase() + fileType.slice(1).toLowerCase();
          return (
            <MenuItem key={fileType} onClick={() => handleToggle(fileType)} dense>
              <Checkbox checked={selectedFileTypes.indexOf(fileType) > -1} size="small" />
              <ListItemText primary={formattedLabel} />
            </MenuItem>
          );
        })}
      </Menu>
    </>
  )
}

