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 { MdRule } from 'react-icons/md'
import { FaPlus, FaTrash } from 'react-icons/fa'
import { Box, Button, InputAdornment, Typography, Modal, TextField, Grid } from '@mui/material'
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'
import AddParcours from './AddParcours'
import UpdateParcour from './UpdateParcour'
import { FaPenToSquare } from 'react-icons/fa6'

const Parcours = () => {
  const [parcours, setParcours] = useState([])

  useEffect(() => {
    window.notesysteme.getParcours().then((response) => {
      setParcours(response)
    })
  }, [])

  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 deleteButton = async (id) => {
    console.log(id);
    let response = await window.notesysteme.deleteParcours(id);
    console.log(response);
    if (response.success) {
      const updatedParcours = parcours.filter((parcour) => parcour.id !== id)
      setParcours(updatedParcours)
      setIsDeleted(true)
    }
  }

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

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

  /**
   * function to open delete modal
   */
  const openDeleteModal = (id) => {
    setIds(id)
    setOpen(true)
  }

  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>Supprimé avec succès</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 parcours ?</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>
  )

  const columns = [
    { field: 'nom', headerName: 'Nom', width: 230 },
    { field: 'uniter', headerName: 'Uniter', width: 180 },
    { field: 'mention', headerName: 'Mention', width: 230 },
    {
      field: 'action',
      headerName: 'Action',
      flex: 1,
      renderCell: (params) => (
        <div style={{ display: 'flex', gap: '10px' }}>
          <Link to={`#`} onClick={() => openUpdate(params.value)}>
            <Button color="warning" variant="contained">
              <FaPenToSquare
                style={{ fontSize: '20px', color: 'white', outline: 'none' }}
                className={`update${params.value}`}
              />
              <Tooltip
                anchorSelect={`.update${params.value}`}
                style={{ fontSize: '15px', zIndex: 22 }}
                place="top"
              >
                Modifier
              </Tooltip>
            </Button>
          </Link>
          <Button 
            color="error" 
            variant="contained"
            onClick={() => openDeleteModal(params.value)}
            sx={{
              marginTop: '13px',
              minWidth: '50px', // largeur mini
              height: '30px',   // hauteur
              padding: '4px',   // espace interne
            }}
          >
            <FaTrash
              style={{ fontSize: '20px', color: 'white', outline: 'none' }}
              className={`delete${params.value}`}
            />
            <Tooltip
              anchorSelect={`.delete${params.value}`}
              style={{ fontSize: '15px', zIndex: 22 }}
              place="top"
            >
              Supprimer
            </Tooltip>
          </Button>
        </div>
      )
    },
    {
      renderCell: (params) => (
        <div>
          
        </div>
      )
    }
  ]

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

  const dataRow = parcours.map((parc) => ({
    id: parc.id,
    nom: parc.nom,
    uniter: parc.uniter,
    mention: parc.mention_nom || parc.mention || 'Mention non trouvée',
    action: parc.id
  }))

  const [isSubmitted, setIsSubmitted] = useState(false)
  const handleFormSubmit = (status) => {
    setIsSubmitted(status)
  }

  useEffect(() => {
    if (isSubmitted) {
      window.notesysteme.getParcours().then((response) => {
        setParcours(response)
      })
      setIsSubmitted(false)
    }
  }, [isSubmitted])

  const [openModalAdd, setOpenModalAdd] = useState(false)
  const [openModalUpdate, setOpenModalUpdate] = useState(false)
  const [idToSend, setIdToSend] = useState(null)

  const closeUpdate = () => {
    setOpenModalUpdate(false)
  }

  const openUpdate = (id) => {
    setIdToSend(id)
    setOpenModalUpdate(true)
  }

  const openModalAddFunction = () => {
    setOpenModalAdd(true)
  }

  const closeModalAdd = () => {
    setOpenModalAdd(false)
  }

  return (
    <div className={classe.mainHome}>
      {modals()}
      <AddParcours open={openModalAdd} onClose={closeModalAdd} onSubmitSuccess={handleFormSubmit} />
      <UpdateParcour
        id={idToSend}
        onClose={closeUpdate}
        onSubmitSuccess={handleFormSubmit}
        open={openModalUpdate}
      />
      <div className={classeAdd.header}>
        <div className={classe.h1style}>
          <div className={classeHome.blockTitle}>
            <h1 style={{ display: 'flex', alignItems: 'center', gap: '10px' }}>
              <MdRule />
              Parcours
            </h1>
            <Link to={'#'} onClick={openModalAddFunction}>
              <Button color="warning" variant="contained">
                <FaPlus style={{ fontSize: '20px' }} /> Ajouter
              </Button>
            </Link>
          </div>
        </div>
      </div>

      <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}>
              <div
                style={{
                  display: 'flex',
                  alignItems: 'center',
                  justifyContent: 'center',
                  flexDirection: 'column', // Stacks content vertically on smaller screens
                  width: '100%'
                }}
              >
                <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}
                />
              </div>
            </ThemeProvider>
          </Paper>
        </div>
      </div>
    </div>
  )
}

export default Parcours