import React, { useEffect, useState } from 'react'
import classe from '../assets/AllStyleComponents.module.css'
import classeAdd from '../assets/AddStudent.module.css'
import classeHome from '../assets/Home.module.css'
import { Link } from 'react-router-dom'
import { Box, Button, InputAdornment, Typography, Modal, TextField, Grid } from '@mui/material'
import { BsBookmarkPlusFill } from 'react-icons/bs'
import { FaClipboardList, FaPenToSquare, FaTrash } from 'react-icons/fa6'
import Paper from '@mui/material/Paper'
import { createTheme, ThemeProvider } from '@mui/material/styles'
import { DataGrid, GridToolbar } from '@mui/x-data-grid'
import { frFR } from '@mui/x-data-grid/locales'
import { Tooltip } from 'react-tooltip'
import warning from '../assets/warning.svg'
import success from '../assets/success.svg'

const Mentions = () => {
  const theme = createTheme({
    components: {
      MuiIconButton: {
        styleOverrides: {
          root: {
            color: 'gray' // Change the color of toolbar icons
          }
        }
      },
      MuiButton: {
        styleOverrides: {
          root: {
            color: '#121212' // Change the color of toolbar icons
          }
        }
      }
    }
  })

  const [isDeleted, setIsDeleted] = useState(false)
  const [ids, setIds] = useState(0)

  const [mentions, setMentions] = useState([])

  useEffect(() => {
    window.mention.getMention().then((response) => {
      setMentions(response)
    })
  }, [])

  const columns = [
    { field: 'nom', headerName: 'Nom', width: 350 },
    { field: 'uniter', headerName: 'Unité ', width: 180 },
    {
      field: 'action',
      headerName: 'Action',
      flex: 1,
      renderCell: (params) => (
        <div style={{ display: 'flex', gap: '10px' }}>
          <Link to={`/singlemention/${params.value}`}>
            <Button color="warning" variant="contained">
              <FaPenToSquare
                style={{ fontSize: '20px', color: 'white' }}
                className={`update${params.value}`}
              />
              <Tooltip
                anchorSelect={`.update${params.value}`}
                style={{ fontSize: '15px', zIndex: 22 }}
                place="top"
              >
                Modifier
              </Tooltip>
            </Button>
          </Link>
          <Link
            to={`#`}
            onClick={() => {
              setIds(params.row.id)
              setOpen(true)
            }}
          >
            <Button color="error" variant="contained">
              <FaTrash
                style={{ fontSize: '20px', color: 'white' }}
                className={`update${params.value}`}
              />
              <Tooltip
                anchorSelect={`.update${params.value}`}
                style={{ fontSize: '15px', zIndex: 22 }}
                place="top"
              >
                Supprimer
              </Tooltip>
            </Button>
          </Link>
        </div>
      )
    }
  ]

  const paginationModel = { page: 0, pageSize: 5 }

  const dataRow = mentions.map((men) => ({
    id: men.id, // Ensure this exists and is unique for each etudiant
    nom: men.nom,
    uniter: men.uniter,
    action: men.id // Ensure this is a valid URL for the image
  }))

  const deleteButton = async (id) => {
    let response = await window.mention.deleteMention({ id })
    if (response.success) {
      const updatedMentions = mentions.filter((mention) => mention.id !== id)
      setMentions(updatedMentions)
      setIsDeleted(true)
    }
  }

  /**
   * hook to open modal
   */
  const [open, setOpen] = useState(false)

  /**
   * function to close modal
   */
  const handleClose = () => {
    setOpen(false)
    setIsDeleted(false)
  }

  /**
   * function to return the view Modal
   *
   * @returns {JSX}
   */
  const modals = () => (
    <Modal
      open={open}
      onClose={handleClose}
      aria-labelledby="modal-title"
      aria-describedby="modal-description"
    >
      <Box
        sx={{
          position: 'absolute',
          top: '50%',
          left: '50%',
          transform: 'translate(-50%, -50%)',
          width: 450,
          bgcolor: 'background.paper',
          boxShadow: 24,
          p: 4
        }}
      >
        {isDeleted ? (
          <Typography
            style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: '10px' }}
          >
            <img src={success} alt="" width={50} height={50} /> <span>Suprimer avec succèss</span>
          </Typography>
        ) : (
          <Typography
            style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: '10px' }}
          >
            <img src={warning} alt="" width={50} height={50} />{' '}
            <span>Voulez vous supprimer ce mention ?</span>
          </Typography>
        )}
        <Box
          sx={{
            marginTop: '2%',
            display: 'flex',
            gap: '20px',
            alignItems: 'end',
            justifyContent: 'flex-end'
          }}
        >
          {isDeleted ? (
            <Button onClick={handleClose} color="warning" variant="contained">
              OK
            </Button>
          ) : (
            <div>
              <Button
                onClick={() => deleteButton(ids)}
                sx={{ mr: 1 }}
                color="warning"
                variant="contained"
              >
                Oui
              </Button>
              <Button onClick={handleClose} color="warning" variant="contained">
                Non
              </Button>
            </div>
          )}
        </Box>
      </Box>
    </Modal>
  )

  return (
    <div className={classe.mainHome}>
      {modals()}
      <div className={classeAdd.header}>
        <div className={classe.h1style}>
          <div className={classeHome.blockTitle}>
            <h1 style={{ display: 'flex', alignItems: 'center', gap: '10px' }}>
              <FaClipboardList />
              Mentions
            </h1>
            <Link to={'/addmention'}>
              <Button color="warning" variant="contained">
                <BsBookmarkPlusFill style={{ fontSize: '20px' }} /> AJouter
              </Button>
            </Link>
          </div>
        </div>
      </div>

      {/* displaying data */}
      <div className={classeHome.boxEtudiantsCard}>
        <div style={{ display: 'flex', justifyContent: 'center' }}>
          <Paper
            sx={{
              height: 'auto', // Auto height to make the grid responsive
              minHeight: 500, // Ensures a minimum height
              display: 'flex',
              // alignItems: "center",
              // justifyContent: "center",
              width: '100%'
            }}
          >
            <ThemeProvider theme={theme}>
              <DataGrid
                rows={dataRow}
                columns={columns}
                initialState={{ pagination: { paginationModel } }}
                pageSizeOptions={[5, 10]}
                sx={{
                  border: 0,
                  width: '100%', // Ensures the DataGrid takes full width
                  height: '100%', // Ensures it grows to fit content
                  minHeight: 400, // Minimum height for the DataGrid
                  display: 'flex',
                  justifyContent: 'center',
                  '@media (max-width: 600px)': {
                    width: '100%', // 100% width on small screens
                    height: 'auto' // Allow height to grow with content
                  }
                }}
                slots={{ toolbar: GridToolbar }}
                localeText={frFR.components.MuiDataGrid.defaultProps.localeText}
              />
            </ThemeProvider>
          </Paper>
        </div>
      </div>
    </div>
  )
}

export default Mentions
