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

const AnneeScolaire = () => {
  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 [anneeScolaire, setAnneeScolaire] = useState([])

  useEffect(() => {
    window.anneescolaire.getAnneeScolaire().then((response) => {
      setAnneeScolaire(response)
    })
  }, [])

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

  const column = [
    { field: 'code', headerName: 'Année Univesitaire', width: 130 },
    { field: 'debut', headerName: 'Date de début', width: 130 },
    { field: 'fin', headerName: 'Date de fin', width: 130 },
    {
      field: 'action',
      headerName: 'Action',
      flex: 1,
      renderCell: (params) => (
        <div style={{ display: 'flex', gap: '10px' }}>
          <Link to={`/anneescolaire/${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={`delete${params.value}`}
              />
              <Tooltip
                anchorSelect={`.delete${params.value}`}
                style={{ fontSize: '15px', zIndex: 22 }}
                place="top"
              >
                Supprimer
              </Tooltip>
            </Button>
          </Link>
        </div>
      )
    },
    {
      field: 'current',
      headerName: 'Année en cours',
      flex: 1,
      renderCell: (params) => (
        <div style={{ display: 'flex', gap: '10px' }}>
          <Link to={`#`}>
            <Button color="success" variant="contained">
              {params.value.current == 1 ? (
                <FaCheck
                  style={{ fontSize: '20px', color: 'white' }}
                  className={`courrants${params.value.id}`}
                />
              ) : (
                <FaSquare
                  style={{ fontSize: '20px', color: 'white' }}
                  className={`courrant${params.value.id}`}
                  onClick={() => setCurrent(params.value.id)}
                />
              )}
            </Button>
            <Tooltip
              anchorSelect={`.courrants${params.value.id}`}
              style={{ fontSize: '15px', zIndex: 22 }}
              place="top"
            >
              Année en cours
            </Tooltip>
          </Link>
        </div>
      )
    }
  ]

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

  let data = anneeScolaire.map((annee) => ({
    id: annee.id,
    code: annee.code,
    debut: dayjs(annee.debut).format('DD-MM-YYYY'),
    fin: dayjs(annee.fin).format('DD-MM-YYYY'),
    action: annee.id,
    current: { current: annee.is_current, id: annee.id }
  }))

  const setCurrent = async (id) => {
    // let response = await window.anneescolaire.setCurrent({id});
    // console.log(response);
    // if (response.changes) {
    //   window.anneescolaire.getAnneeScolaire().then((response) => {
    //     setAnneeScolaire(response);
    //   });
    // }
  }

  const deleteButton = async (id) => {
    let response = await window.anneescolaire.deleteAnneeScolaire({ id })
    if (response.success) {
      const updatedAnneeScolaire = anneeScolaire.filter((anneeScolaire) => anneeScolaire.id !== id)
      setAnneeScolaire(updatedAnneeScolaire)
      setIsDeleted(true)
    }
  }

  const CustomToolbar = () => {
    return (
      <div>
        <GridToolbarFilterButton />
      </div>
    )
  }

  /**
   * 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 cette année ?</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={classeHome.header}>
        <div className={classe.h1style}>
          <div className={classeHome.blockTitle}>
            <h1 style={{ display: 'flex', alignItems: 'center', gap: '10px' }}>
              <BsCalendar2Date /> Année Univesitaire
            </h1>
            <Link to={'/addanneescolaire'}>
              <Button color="warning" variant="contained">
                <FaCalendarPlus style={{ fontSize: '20px' }} /> Ajouter
              </Button>
            </Link>
          </div>
        </div>
      </div>

      <div className={classeHome.boxEtudiantsCard}>
        <Paper
          sx={{
            width: '100%',
            height: '100%', // Auto height to make the grid responsive
            minHeight: 500, // Ensures a minimum height
            display: 'flex',
            flexDirection: 'column'
          }}
        >
          <ThemeProvider theme={theme}>
            <div
              style={{
                display: 'flex',
                flexDirection: 'column', // Stacks content vertically on smaller screens,
                width: '100%'
              }}
            >
              <DataGrid
                rows={data}
                columns={column}
                initialState={{ pagination: { paginationModel } }}
                pageSizeOptions={[5, 10]}
                sx={{
                  border: 0,
                  width: 'auto', // Ensures the DataGrid takes full width
                  height: '50%', // 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: CustomToolbar }}
                localeText={frFR.components.MuiDataGrid.defaultProps.localeText}
              />
            </div>
          </ThemeProvider>
        </Paper>
      </div>
    </div>
  )
}

export default AnneeScolaire
