"use client";

import React, { useState, useEffect } from "react";
import {
  Card,
  Box,
  Typography,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableFooter,
  TablePagination,
  TableRow,
  Paper,
  IconButton,
  TableHead,
  Button,
  TextField,
  DialogActions,
  DialogContent,
  DialogTitle,
  FormControl,
  FormHelperText
} from "@mui/material";
import AddIcon from "@mui/icons-material/Add";
import ClearIcon from "@mui/icons-material/Clear";
import HomeSectionService, {HomeSectionOPData, HomeSectionIdOPData} from "@/service/HomeSectionService";
import { ToastContainer, toast} from 'react-toastify';
import 'react-toastify/dist/ReactToastify.css';
import { HomeSectionFormValues, HomeSectionValidationSchema, HomeSectionTouchFields  } from '@lib/ValidationSchemas';
import { useFormik  } from 'formik';
import TablePaginationActions from "../../Pagination";
import BootstrapDialog from "../../BootstrapModel";
import withAuth from "@/withAuth";
import routes from "@/routes";
import {RoleEnum} from '@constant/StaticData';
import Textarea from "../../Fields/TextArea";
import {handleFetchWithTokenRefresh} from '@utils/common';
import { useCookies } from 'react-cookie';
import { ArrowUpward, ArrowDownward  } from '@mui/icons-material';

const HomeSection: React.FC = () => {
  const [page, setPage] = React.useState(0);
  const [rowsPerPage, setRowsPerPage] = React.useState(10);
  const [HomeSectionData, setHomeSectionData] = useState<HomeSectionOPData | undefined>(undefined);
  const [HomeSectionDataById, setHomeSectionDataById] = useState<HomeSectionIdOPData | undefined>(undefined);
  const [open, setOpen] = useState(false);
  const [delOpen, setDelOpen] = useState(false);
  const [viewOpen, setViewOpen] = useState(false);
  const [title, setTitle] = useState("Add New");
  const [delId, setDelId] = useState(0);
  const [HSId, setHSId] = useState(0);
  const [changes, setChanges] = useState("");
  const [btnName, setBtnName] = useState("Create");
  const [cookies, setCookie, removeCookie] = useCookies();
  const [isPagination, setIsPagination] = useState(false);
  const [sortOrder, setSortOrder] = useState<'DESC' | 'ASC'>('DESC');

  const handleSubmit = async(values:any) =>{
    const errors = await formik.validateForm();
      formik.setTouched(HomeSectionTouchFields);   
      if (Object.keys(errors).length === 0) {
        try {
          
          let successMsg;

          if (changes === 'Add') {
            successMsg = "Inserted data successfully !!";

            const HomeSectionInsData = await HomeSectionService.createHomeSection(values);
            if(HomeSectionInsData?.HouseSectionCreate && HomeSectionInsData.HouseSectionCreate?.[0]?.id > 0){
              const HomeSectionData = HomeSectionInsData.HouseSectionCreate[0] || [];
              setHomeSectionData((prevData) => {
                if (!prevData || !prevData.HouseSectionFind) {
                  return prevData;
                }
                const existingRows = prevData?.HouseSectionFind?.rows || [];                    
                const total = prevData?.HouseSectionFind?.total  || 0;   
                const pages = Math.ceil(total / rowsPerPage);                 
                return {
                  ...prevData,
                  HouseSectionFind: {
                    rows: [HomeSectionData, ...existingRows],
                    total: total + 1,
                    pages: pages
                  },
                }; 
              });
              toast.success(successMsg, {
                  position: "bottom-left",
                  autoClose: 2000,
              });
            } 
          } else if (changes === 'Edit') {
              successMsg = "Updated data successfully !!";
              const HomeSectionInsData = await HomeSectionService.updateHomeSection(values);

              if(HomeSectionInsData?.HouseSectionUpdate && HomeSectionInsData.HouseSectionUpdate.affected > 0){
                const HomeSectionData = HomeSectionInsData.HouseSectionUpdate.affectedRows?.[0] || null;
                setHomeSectionData((prevData) => {
                  if (!prevData || !prevData.HouseSectionFind) {
                      return prevData;
                  }
                  const updatedRows = (prevData.HouseSectionFind.rows || []).map((item) => 
                      item.id === HomeSectionData?.id ? HomeSectionData : item
                  );
                  return {
                      ...prevData,
                      HouseSectionFind: {
                          ...prevData.HouseSectionFind,
                          rows: updatedRows,
                      },
                  };
              }); 
               if(HomeSectionInsData?.HouseSectionUpdate?.snapshot?.error.length > 0){
                  const errorMsg = HomeSectionInsData?.HouseSectionUpdate.snapshot?.error[0]
                  toast.error(errorMsg, {
                    position: "bottom-left",
                    autoClose: 2000,
                  });
                  } else {
                  toast.success(successMsg, {
                    position: "bottom-left",
                    autoClose: 2000,
                });
              } 
            }
          }
          setOpen(false);
          setHSId(0);
        }catch (error:any) {
          console.log('GraphQL Mutation Error:', error);
          handleFetchWithTokenRefresh(error, cookies, setCookie, handleSubmit, "Error during insert/update entry!!", values);
        }
      } 
  }

  const formik = useFormik<HomeSectionFormValues>({
    initialValues: {
      title: "",
      desc: ""
    },
    validationSchema: HomeSectionValidationSchema,
    onSubmit: async(values) => {
      handleSubmit(values);
    },
  });

  const fetchData = async () => {
    try {		
      const start = (page)*rowsPerPage;
      const HomeSectionData = await HomeSectionService.getHomeSection(rowsPerPage, start,sortOrder);
      if(HomeSectionData != undefined && HomeSectionData != null && HomeSectionData?.HouseSectionFind){
        setHomeSectionData(HomeSectionData);
      }
    } catch (err:any) {
      console.error('Error during fetch data:', err);
      handleFetchWithTokenRefresh(err, cookies, setCookie, fetchData, "Error during fetch data");
    }
  };


  const handleSort = async() => {
    const newSortOrder = sortOrder === 'ASC' ? 'DESC' : 'ASC';
    setSortOrder(newSortOrder);
    await fetchData(); 
  };


  useEffect(() => {
    fetchData();
  },[page, rowsPerPage,sortOrder]);

  useEffect(() => {
    if (isPagination) {
      fetchData();
      setIsPagination(false); 
    }
  }, [isPagination]);

  const fetchDataByID = async () => {
    try {		
      const HomeSectionIdData = await HomeSectionService.getHomeSectionById(HSId);
      if(HomeSectionIdData != undefined && HomeSectionIdData != null && HomeSectionIdData?.HouseSectionFindOneById){
        setHomeSectionDataById(HomeSectionIdData);
      }
    } catch (err:any) {
      console.error('Error during fetch data:', err);
      handleFetchWithTokenRefresh(err, cookies, setCookie, fetchDataByID, "Error during fetch data");
    }
  };

  useEffect(() => {
    if (HSId !== 0) {
      fetchDataByID();
    }
  },[HSId]);

  const setFormikValues = () => {
    if (HomeSectionDataById) {
      formik.setValues({
        title: HomeSectionDataById?.HouseSectionFindOneById?.title || "",
        desc: HomeSectionDataById?.HouseSectionFindOneById?.desc || "",
        id: HomeSectionDataById?.HouseSectionFindOneById?.id || 0,
      });
    }
  }

  useEffect(() => {
    setFormikValues();
  }, [HomeSectionDataById]);

  const emptyRows =
    page > 0 ? Math.max(0, (1 + page) * rowsPerPage - (HomeSectionData?.HouseSectionFind?.total || 0)) : 0;

  const handleChangePage = (
    event: React.MouseEvent<HTMLButtonElement> | null,
    newPage: number
  ) => {
    setPage(newPage);
  };

  const handleChangeRowsPerPage = (
    event: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>
  ) => {
    setRowsPerPage(parseInt(event.target.value, 10));
    setPage(0);
  };

  // Modal
  
  const handleClickOpen = (Title:string) => {
    setTitle(Title);
    setOpen(true);
    formik.resetForm();  
    setChanges("Add");  
    setBtnName("Create");
  };

  const handleEditOpen = (Title:string, Id:number) => {
    setTitle(Title);
    setHSId(Id);
    setOpen(true); 
    if(formik.values.title === ''){
      setFormikValues();
    }
    setChanges("Edit"); 
    setBtnName("Update");
  };
  const handleClose = () => {
    setOpen(false);
    setHSId(0);
    formik.resetForm();
  };

  const handleDelClickOpen = (Id:number) => {
    setDelId(Id);
    setDelOpen(true);
  };
  const handleDelClose = () => {
    setDelOpen(false);
    setHSId(0);
  };

  const handleViewClickOpen = (Id:number) => {
    setViewOpen(true);
    setHSId(Id);
    if(formik.values.title === ''){
      setFormikValues();
    }
  };

  const handleViewClose = () => {
    setViewOpen(false);
    setHSId(0);
  };

  const handleDelSubmit = async() => {
    try {		
      const HomeSectionDelData = await HomeSectionService.deleteHomeSection(delId);
      if(HomeSectionDelData && HomeSectionDelData.HouseSectionDelete?.affected == 1){
        setHomeSectionData((prevData) => {
          if (!prevData || !prevData.HouseSectionFind) {
              return prevData;
          }

          const filteredRows = (prevData.HouseSectionFind.rows || []).filter(item => item.id !== delId);
          const total = ((prevData.HouseSectionFind.total-1) || 0);
          const pages = Math.ceil(total / rowsPerPage); 
          setHSId(0);

          if(prevData?.HouseSectionFind?.pages !== pages){
            setIsPagination(true);
          }

          return {
              ...prevData,
              HouseSectionFind: {
                  ...prevData.HouseSectionFind,
                  rows: filteredRows,
                  total: total,
                  pages: pages
              },
          };
       });
         if(HomeSectionDelData?.HouseSectionDelete?.snapshot?.error.length > 0){
            const errorMsg = HomeSectionDelData.HouseSectionDelete?.snapshot?.error[0]
            toast.error(errorMsg, {
              position: "bottom-left",
              autoClose: 2000,
            });
            }else{
            toast.success('Entry Deleted Successfully !!', {
                position: "bottom-left",
                autoClose: 2000,
            });
          } 
        setPage(0);
        setDelOpen(false);
      }
      
    } catch (err:any) {
      console.error('Error during delete data:', err);
      handleFetchWithTokenRefresh(err, cookies, setCookie, handleDelSubmit, "Error during delete data");
    }

  };

  return (
    <>
      <Card
        sx={{
          boxShadow: "none",
          borderRadius: "7px",
          mb: "25px",
          padding: { xs: "18px", sm: "20px", lg: "25px" },
        }}
        className="rmui-card"
      >
        <Box
          sx={{
            display: { xs: "block", sm: "flex" },
            alignItems: "center",
            justifyContent: "space-between",
            mb: "25px",
            float:"right"
          }}
        >
          <Button
            onClick={() => handleClickOpen("Add New Gallery Category")}
            variant="outlined"
            sx={{
              textTransform: "capitalize",
              borderRadius: "7px",
              fontWeight: "500",
              fontSize: "13px",
              padding: "6px 13px",
            }}
            color="primary"
            title="Add"
          >
            <AddIcon sx={{ position: "relative", top: "-1px" }} /> Add New
          </Button>
        </Box>

        {/* Table */}
        <Box
          sx={{
            marginLeft: "-25px",
            marginRight: "-25px",
          }}
        >
          <TableContainer
            component={Paper}
            sx={{
              boxShadow: "none",
              borderRadius: "0",
            }}
            className="rmui-table"
          >
            <Table sx={{ minWidth: 1000 }} aria-label="Offer Strength Table">
              <TableHead className="bg-primary-50">
                <TableRow>
                  <TableCell
                    sx={{
                      fontWeight: "500",
                      padding: "10px 24px",
                      fontSize: "14px",
                      width:"15%"
                    }}
                    className="text-black border-bottom"
                  >
                    <IconButton
                          aria-label="sort"
                          color="primary"
                          sx={{ padding: "5px" }}
                          onClick={handleSort}
                        >
                          {sortOrder === 'ASC' ? (
                            <ArrowUpward sx={{ fontSize: '16px' }} />
                          ) : (
                            <ArrowDownward sx={{ fontSize: '16px' }} />
                          )}
                        </IconButton>
                    Title
                  </TableCell>

                 {/*  <TableCell
                    sx={{
                      fontWeight: "500",
                      padding: "10px 20px",
                      fontSize: "14px",
                    }}
                    className="text-black border-bottom"
                  >
                    Description
                  </TableCell> */}

                  <TableCell
                    sx={{
                      fontWeight: "500",
                      padding: "10px 20px",
                      fontSize: "14px",
                      width:"10%",
                      textAlign:"right"
                    }}
                    className="text-black border-bottom"
                  >
                    Action
                  </TableCell>
                </TableRow>
              </TableHead>

              <TableBody>
                {HomeSectionData?.HouseSectionFind?.rows && HomeSectionData.HouseSectionFind.rows.length > 0 ? (
                HomeSectionData.HouseSectionFind.rows.map((row) => (
                    <TableRow key={row.id}>
                      <TableCell
                        sx={{
                          padding: "5px 13px",
                          fontSize: "14px",
                          width: "65px",
                        }}
                        className="border-bottom"
                      >
                      {row.title}
                      </TableCell>

                      {/* <TableCell
                        sx={{
                          padding: "15px 20px",
                          fontSize: "14px",
                        }}
                        className="border-bottom"
                      >
                        {row.desc}
                      </TableCell>
 */}
                      <TableCell
                        sx={{
                          padding: "15px 20px",
                        }}
                        className="border-bottom"
                      >
                        <Box
                          sx={{
                            display: "flex",
                            alignItems: "center",
                            float:"right"
                          }}
                        >
                          <IconButton
                          aria-label="view"
                          color="primary"
                          title="View"
                          sx={{ padding: "5px" }}
                          onClick={() => handleViewClickOpen(row.id)}
                          >
                          <i
                              className="material-symbols-outlined"
                              style={{ fontSize: "16px" }}
                          >
                              visibility
                          </i>
                          </IconButton>


                          <IconButton
                          aria-label="edit"
                          color="secondary"
                          title="Edit"
                          sx={{ padding: "5px" }}
                          onClick={() => handleEditOpen("Edit Gallery Category", row.id)}
                          >
                          <i
                              className="material-symbols-outlined"
                              style={{ fontSize: "16px" }}
                          >
                              edit
                          </i>
                          </IconButton>
                          

                          <IconButton
                            aria-label="delete"
                            color="error"
                            title="Delete"
                            sx={{ padding: "5px" }}
                            onClick={() => handleDelClickOpen(row.id)}
                          >
                            <i
                              className="material-symbols-outlined"
                              style={{ fontSize: "16px" }}
                            >
                              delete
                            </i>
                          </IconButton>
                        </Box>
                      </TableCell>
                    </TableRow>
                  ))
                ) : (
                  <TableRow>
                    <TableCell colSpan={8} align="center">
                      No data available.
                    </TableCell>
                  </TableRow>
                )}
                {emptyRows > 0 && (
                  <TableRow style={{ height: 53 * emptyRows }}>
                    <TableCell colSpan={8} />
                  </TableRow>
                )}
              </TableBody>

              <TableFooter>
                <TableRow>
                  <TablePagination
                    rowsPerPageOptions={[
                      5,
                      10,
                      25,
                      { label: "All", value: -1 },
                    ]}
                    colSpan={8}
                    count={HomeSectionData?.HouseSectionFind?.total || 0}
                    rowsPerPage={rowsPerPage}
                    page={page}
                    slotProps={{
                      select: {
                        inputProps: {
                          "aria-label": "rows per page",
                        },
                        native: true,
                      },
                    }}
                    onPageChange={handleChangePage}
                    onRowsPerPageChange={handleChangeRowsPerPage}
                    ActionsComponent={TablePaginationActions}
                    sx={{
                      border: "none",
                    }}
                  />
                </TableRow>
              </TableFooter>
            </Table>
          </TableContainer>
        </Box>
      </Card>

      {/* Modal */}
      <BootstrapDialog
        onClose={handleClose}
        aria-labelledby="customized-dialog-title"
        open={open}
        className="rmu-modal"
        PaperProps={{
            sx: { width: { xs: '100%', sm: '100%', md: '100%' }, maxWidth: '500px' }
          }}
      >
        <Box>
          <Box
            sx={{
              display: "flex",
              justifyContent: "space-between",
              alignItems: "center",
              background: "#f6f7f9",
              padding: { xs: "15px 20px", md: "25px" },
            }}
            className="rmu-modal-header"
          >
            <Typography
              id="modal-modal-title"
              variant="h6"
              sx={{
                fontWeight: "600",
                fontSize: { xs: "16px", md: "18px" },
              }}
              className="text-black"
            >
              {title}
            </Typography>

            <IconButton aria-label="remove" size="small" onClick={handleClose}>
              <ClearIcon />
            </IconButton>
          </Box>

          <Box className="rmu-modal-content">
            <Box component="form" onSubmit={formik.handleSubmit}>
              <Box
                sx={{
                  padding: "25px",
                  borderRadius: "8px",
                }}
                className="bg-white"
              >
             
                <Box mb={2}>
                    <Typography
                      component="h5"
                      sx={{
                        fontWeight: "500",
                        fontSize: "14px",
                        mb: "12px",
                      }}
                      className="text-black"
                    >
                      Title
                    </Typography>

                    <TextField
                      autoComplete="title"
                      name="title"
                      fullWidth
                      id="title"
                      label="Title"
                      value = {formik.values.title}
                      onChange={formik.handleChange}
                      onBlur={formik.handleBlur}
                      error={Boolean(formik.touched.title && formik.errors.title)}
                      helperText={formik.touched.title && formik.errors.title}
                    />
                </Box>

               {/*  <Box mb={2} display="flex" justifyContent="space-between">
                  <Box flex={1} mr={1}>
                    <Typography
                          component="h5"
                          sx={{
                            fontWeight: "500",
                            fontSize: "14px",
                            mb: "12px",
                          }}
                          className="text-black"
                        >
                          Description
                        </Typography>

                        <FormControl
                          fullWidth
                          error={Boolean(formik.touched.desc && formik.errors.desc)}
                        >
                          <Textarea
                            aria-label="minimum height"
                            minRows={4}
                            autoComplete="desc"
                            name="desc"
                            id="desc"
                            placeholder="Description"
                            onChange={formik.handleChange}
                            onBlur={formik.handleBlur}
                            value={formik.values.desc}
                            style={{
                              width: "100%",
                              padding: "8px",
                              border: Boolean(formik.touched.desc && formik.errors.desc)
                                ? "1px solid red"
                                : "1px solid #D5D9E2",
                              borderRadius: "5px",
                            }}
                          />
                          {formik.touched.desc && formik.errors.desc && (
                            <FormHelperText>{formik.errors.desc}</FormHelperText>
                          )}
                        </FormControl>
                  </Box>
                </Box> */}

                <Box mt={1} display="flex" justifyContent="flex-end" gap="10px">
                    <Box
                      sx={{
                        display: "flex",
                        alignItems: "center",
                        justifyContent: "end",
                        gap: "10px",
                      }}
                    >
                      <Button
                        onClick={handleClose}
                        variant="outlined"
                        color="error"
                        sx={{
                          textTransform: "capitalize",
                          borderRadius: "8px",
                          fontWeight: "500",
                          fontSize: "13px",
                          padding: "11px 30px",
                        }}
                      >
                        Cancel
                      </Button>

                      <Button
                        type="submit"
                        variant="contained"
                        sx={{
                          textTransform: "capitalize",
                          borderRadius: "8px",
                          fontWeight: "500",
                          fontSize: "13px",
                          padding: "11px 30px",
                          color: "#fff !important",
                        }}
                      >
                        <AddIcon
                          sx={{
                            position: "relative",
                            top: "-2px",
                          }}
                          className="mr-5px"
                        />{" "}
                        {btnName}
                      </Button>
                    </Box>
                </Box>
              </Box>
            </Box>
          </Box>
        </Box>
      </BootstrapDialog>

      {/*View */ }
      <BootstrapDialog
        onClose={handleViewClose}
        aria-labelledby="customized-dialog-title"
        open={viewOpen}
        className="rmu-modal"
        PaperProps={{
          sx: { width: { xs: '100%', sm: '100%', md: '100%' }, maxWidth: '500px' }
        }}
      >
        <Box>
          <Box
            sx={{
              display: "flex",
              justifyContent: "space-between",
              alignItems: "center",
              background: "#f6f7f9",
              padding: { xs: "15px 20px", md: "25px" },
            }}
            className="rmu-modal-header"
          >
            <Typography
              id="modal-modal-title"
              variant="h6"
              sx={{
                fontWeight: "600",
                fontSize: { xs: "16px", md: "18px" },
              }}
              className="text-black"
            >
              View Gallery Category
            </Typography>

            <IconButton aria-label="remove" size="small" onClick={handleViewClose}>
              <ClearIcon />
            </IconButton>
          </Box>

          <Box className="rmu-modal-content">
            <Box component="form">
              <Box
                sx={{
                  paddingLeft: "50px",
                  paddingRight: "50px",
                  paddingTop:"25px",
                  borderRadius: "8px",
                  backgroundColor: "white",
                }}
              >
                {[
                  { label: "Title ", value:  ": "+formik.values.title},
                  { label: "Description ", value: ": "+formik.values.desc },

                ].map((field, index) => (
                  <Box mb={2} display="flex" justifyContent="space-between" key={index}>
                    <Typography
                      component="h5"
                      sx={{
                        fontWeight: "500",
                        fontSize: "14px",
                        mb: "12px",
                        flex: "1", 
                      }}
                      className="text-black"
                    >
                      {field.label}
                    </Typography>
                    <Typography
                      sx={{
                        fontSize: "14px",
                        color: "#555",
                        flex: "2", 
                      }}
                    >
                      {field.value}
                    </Typography>
                  </Box>
                ))}
              </Box>
            </Box>
          </Box>
        </Box>
      </BootstrapDialog> 

       {/* Delete Modal */}
      <BootstrapDialog
        onClose={handleDelClose}
        aria-labelledby="customized-dialog-title"
        open={delOpen}
        className="rmu-modal"
      >
        <Box>
          <Box
            sx={{
              display: "flex",
              justifyContent: "space-between",
              alignItems: "center",
              background: "#f6f7f9",
              padding: { xs: "15px 20px", md: "5px" },
            }}
            className="rmu-modal-header"
          >
            <DialogTitle sx={{ m: 0, p: 2 }} id="customized-dialog-title">
              Delete Confirmation
            </DialogTitle>
            <IconButton aria-label="remove" size="small" onClick={handleDelClose}>
              <ClearIcon />
            </IconButton>
          </Box>

           <DialogContent dividers>
              <Typography gutterBottom>
                Are you sure want to delete this entry ?
              </Typography>
              
            </DialogContent>
            
            <DialogActions>
                <Button variant="outlined"
                          color="error" 
                          onClick={handleDelSubmit}>Delete</Button>
                <Button variant="outlined"
                          onClick={handleDelClose}>Cancel</Button>
            </DialogActions> 
            
         
        </Box>
      </BootstrapDialog> 
      <ToastContainer/>
    </>
  );
};

export default withAuth(HomeSection, routes.homesection.auth, RoleEnum.ADMIN);