import React, { useEffect, useState } from "react";
import {
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  CircularProgress,
  Grid,
  Box,
  Button,
  TextField,
  InputAdornment,
  Card,
  Typography,
} from "@mui/material";
import {
  useDeleteDriverMutation,
  useGetDriverQuery,
} from "../../../Api/attoDeskApi";
import { IDriver } from "../../../Api/Interface/api.interface";
import NewPopUpDriver from "../Edit/index";
import DeletePopup from "../../../Components/Delete/DeletePopup";
import useDebounce from "../../../Components/SearchDebonce/useDebounce";
import { useNavigate } from "react-router-dom";
import { useStyles } from "../../../theme/appStyles";
import { useNotifier } from "../../../Core/Notifier";
import { CiSearch } from "react-icons/ci";
import DeleteOutlineSharpIcon from "@mui/icons-material/DeleteOutlineSharp";
import EditSharpIcon from "@mui/icons-material/EditSharp";
import VisibilitySharpIcon from "@mui/icons-material/VisibilitySharp";
import CustomCheckbox from "../../../Components/Checkbox.tsx";
import Pagination from "../../../Components/Pagination";
import axios from "axios";

interface Project {
  id: number;
  projectName: string;
  projectStatus: string;
  created_at: string;
  projectType: string;
  projectDomainName: string;
  projectPhoneNumber: string;
  projectStreetNumber: string;
  projectStreetName: string;
  projectProvince:string,
  projectCity:string,
  projectPostalCode:string,
  projectStartDate: string;
  projectImg:string,
  projectEstimatedEndDate: string;
  projectDescription: string;
  projectEmail: string;
  
}

const Index = () => {
  const classes = useStyles();
  const navigate = useNavigate();
  const { showErrorMessage, showMessage } = useNotifier();
  const [searchQuery, setSearchQuery] = useState("");
  const [currentSearchQuery, setCurrentSearchQuery] = useState("");
  const [page, setPage] = useState(0);
  const [rowsPerPage, setRowsPerPage] = useState(5);
     const API_URL = process.env.REACT_APP_API_URL;
      const [projects, setProjects] = useState<Project[]>([]); 
  const [selectedCoursing, setSelectedCoursing] = useState<IDriver | null>(
    null
  );
  const debouncedSearchQuery = useDebounce(searchQuery, 300);
  const [openDialog, setOpenDialog] = useState(false);
  const [openDeleteCategory, setOpenDeleteCategory] = useState(false);
  const [coursingToDelete, setCoursingToDelete] = useState<IDriver | null>(
    null
  );

  const { data, isLoading, isError, refetch } = useGetDriverQuery({
    searchText: currentSearchQuery,
    id: "",
  });

  const handleChangePage = (event: unknown, newPage: number) => {
    setPage(newPage);
  };

  useEffect(() => {
    if (debouncedSearchQuery.length >= 4 || debouncedSearchQuery === "") {
      setCurrentSearchQuery(debouncedSearchQuery);
      refetch();
    }
  }, [debouncedSearchQuery]);

     useEffect(() => {
          const fetchProjects = async () => {
            try {
                const headers = {
              Authorization: `Bearer ${localStorage.getItem("token") || ""}`,
          };
              
              const response = await axios.get(`${API_URL}/view-projects`, {headers});
              setProjects(response.data); // Set the fetched data to state
       
            } catch (error) {
              console.error("Failed to load projects", error);
            }
          };
          fetchProjects();
        }, [API_URL]);

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

  const handleOpenDialog = (coursing: IDriver) => {
    setSelectedCoursing(coursing);
    setOpenDialog(true);
  };

  const handleCloseDialog = () => {
    setSelectedCoursing(null);
    setOpenDialog(false);
  };

  const handleOpenDeletePopup = (coursing: IDriver) => {
    setCoursingToDelete(coursing);
    setOpenDeleteCategory(true);
  };

  const handleCloseDeletePopup = () => {
    setCoursingToDelete(null);
    setOpenDeleteCategory(false);
  };

  const [deleteCategory] = useDeleteDriverMutation();
  const handleDelete = async (id: string) => {
    try {
      const response = await deleteCategory(id).unwrap();
      if (response.status) {
        showMessage("Deleted successfully");
        setOpenDeleteCategory(false);
      } else {
        showErrorMessage("Failed to delete the customer");
      }
    } catch (error) {
      showErrorMessage("Failed to delete the customer");
    }
  };

  if (isLoading)
    return (
      <Box
        display="flex"
        justifyContent="center"
        alignItems="center"
        height="10vh"
      >
        <CircularProgress />
      </Box>
    );

  const coursings: IDriver[] = Array.isArray(data?.data)
    ? (data?.data as IDriver[])
    : [];

  const handleSearch = () => {
    setCurrentSearchQuery(searchQuery);
  };

  const resetFields = () => {
    setSearchQuery("");
    setCurrentSearchQuery("");
    refetch();
  };

  const handleAddProductClick = () => {
    navigate("/team/create");
  };

  return (
    <Card className={classes.card}>
      <Grid
        container
        justifyContent={"space-between"}
        spacing={5}
        sx={{ borderBottom: 2, padding: 2 }}
        className={classes.titleGrid}
      >
        <Grid item lg={4} md={4} sm={4} xs={4} pt={2} alignContent={"center"}>
          <Typography className={classes.cardTitle}>New Team</Typography>
        </Grid>
        <Grid
          item
          lg={8}
          md={8}
          sm={8}
          xs={8}
          sx={{ display: "flex", justifyContent: "flex-end" }}
        >
          <Grid
            container
            spacing={1}
            justifyContent="flex-end"
            sx={{ display: "flex" }}
          >
            <Grid item>
              <TextField
                InputProps={{
                  startAdornment: (
                    <InputAdornment position="start">
                      <CiSearch className={classes.searchWidgetIcon} />
                    </InputAdornment>
                  ),
                  classes: {
                    root: classes.formControlList,
                  },
                }}
                fullWidth
                value={searchQuery}
                onChange={(e) => setSearchQuery(e.target.value)}
                placeholder="Mobile & Name .."
                sx={{ width: "100%" }}
                size="small"
              />
            </Grid>

            <Grid item>
              <Button
                variant="contained"
                className={classes.addButton}
                onClick={handleAddProductClick}
              >
                Add Team
              </Button>
            </Grid>
          </Grid>
        </Grid>
      </Grid>

      <Grid>
        <TableContainer>
          <Table className={classes.table}>
            <TableHead className={classes.tableHeaderRow}>
              <TableRow>
                <TableCell className={classes.tablheader}>
                  <CustomCheckbox name="checkbox" />
                </TableCell>
                {/* <TableCell className={classes.tablheader}>
                  <strong>#</strong>
                </TableCell> */}
                <TableCell className={classes.tablheader}>
                  <strong>Team Member Name</strong>
                </TableCell>
                <TableCell className={classes.tablheader}>
                  <strong>User Role</strong>
                </TableCell>
                   <TableCell className={classes.tablheader}>
                  <strong>Project</strong>
                </TableCell>
                {/* <TableCell className={classes.tablheader}>
                  <strong>Mobile Number</strong>
                </TableCell> */}
                {/* <TableCell className={classes.tablheader}>
                  <strong>E-mail</strong>
                </TableCell> */}
                {/* <TableCell className={classes.tablheader}>
                  <strong>Address</strong>
                </TableCell> */}
                <TableCell
                  className={classes.tablheader}
                  sx={{ textAlign: "right" }}
                >
                  <strong>Actions</strong>
                </TableCell>
              </TableRow>
            </TableHead>
            <TableBody>
              {isError || coursings.length === 0 ? (
                <TableRow>
                  <TableCell colSpan={20} align="center">
                    {isError ? "Error fetching data" : "No data available"}
                  </TableCell>
                </TableRow>
              ) : (
                coursings
                  .slice(page * rowsPerPage, page * rowsPerPage + rowsPerPage)
                  .map((row: IDriver, index) => (
                    <TableRow key={row.id} className={classes.tableRowHover}>
                      <TableCell className={classes.tablCell}>
                        <CustomCheckbox name="checkbox" />
                      </TableCell>
                      {/* <TableCell scope="row" className={classes.tablCell}>
                        {page * rowsPerPage + index + 1}
                      </TableCell> */}
                      <TableCell
                        component="th"
                        scope="row"
                        className={classes.tablCell}
                      >
                        {" "}
                        <Grid container spacing={1}>
                          <Grid item>
                            {/* <Box className={classes.SelectImageTableBox}>
                              <img
                                src={row.driverImg}
                                alt="img"
                                // alt={row.productName.toLowerCase()}
                                className={classes.SelectImageTable}
                              />
                            </Box> */}
                          </Grid>
                          <Grid
                            item
                            textAlign={"center"}
                            alignContent={"center"}
                          >
                            <Typography className={classes.nameTableList}>
                              {(row.driverFirstName || "") +
                                " " +
                                (row.driverLastName || "")}
                            </Typography>
                          </Grid>
                        </Grid>
                      </TableCell>
                      <TableCell scope="row" className={classes.tablCell}>
                      {row.driverUserRole === "super_admin"
    ? "Super Admin"
    : row.driverUserRole === "manager"
    ? "Manager"
    : row.driverUserRole}
                      </TableCell>
                <TableCell scope="row" className={classes.tablCell}>
    {(typeof row.projectId === "string" ? JSON.parse(row.projectId) : row.projectId || [])
    .map((id: number) => projects.find((p) => p.id === id)?.projectName)
    .filter(Boolean)
    .join(", ")}
    
</TableCell>

                      {/* <TableCell scope="row" className={classes.tablCell}>
                        {row.driverMobileNum}
                      </TableCell>
                      <TableCell scope="row" className={classes.tablCell}>
                        {row.driverEmail}
                      </TableCell> */}
                      {/* <TableCell scope="row" className={classes.tablCell}>
                        {row.driverAddress}
                      </TableCell> */}
                      <TableCell scope="row" className={classes.tablCell}>
                        <Grid
                          container
                          spacing={1}
                          sx={{ display: "flex", justifyContent: "flex-end" }}
                        >
                          {/* <Grid item>
                            <Button
                              variant="contained"
                              className={classes.viewButtonList}
                              onClick={() =>
                                navigate(`/driver-history/${row.id}`)
                              }
                            >
                              <VisibilitySharpIcon
                                className={classes.viewListIcon}
                              />
                            </Button>
                          </Grid> */}
                          <Grid item>
                            <Button
                              variant="contained"
                              className={classes.editButtonList}
                              onClick={() => handleOpenDialog(row)}
                            >
                              <EditSharpIcon className={classes.editListIcon} />
                            </Button>
                          </Grid>
                          <Grid item>
                            <Button
                              variant="contained"
                              className={classes.deleteButtonList}
                              onClick={() => handleOpenDeletePopup(row)}
                            >
                              <DeleteOutlineSharpIcon
                                className={classes.deleteButtonList}
                              />
                            </Button>
                          </Grid>
                        </Grid>
                      </TableCell>
                    </TableRow>
                  ))
              )}
            </TableBody>
          </Table>
          <Grid
            spacing={5}
            p={"18px"}
            py={4}
            justifyContent={"end"}
            container
            textAlign={"center"}
            alignContent={"center"}
            alignItems={"center"}
          >
            <Grid
              sx={{
                textAlign: "end",
                justifyContent: "flex-end",
                alignItems: "flex-end",
              }}
            >
              <Pagination
                count={coursings.length}
                page={page}
                rowsPerPage={rowsPerPage}
                onPageChange={handleChangePage}
              />
            </Grid>
          </Grid>
        </TableContainer>
        {selectedCoursing && (
          <NewPopUpDriver
            openModel={openDialog}
            handleCloseDialog={handleCloseDialog}
            data={selectedCoursing}
          />
        )}
        {coursingToDelete && (
          <DeletePopup
            open={openDeleteCategory}
            handleCloseDelete={handleCloseDeletePopup}
            onConfirm={async () => {
              await handleDelete(coursingToDelete.id.toString());
            }}
            title="Delete Driver"
            content={`Are you sure you want to delete "${
              coursingToDelete.driverFirstName +
              " " +
              coursingToDelete.driverLastName
            }"?`}
          />
        )}
      </Grid>
    </Card>
  );
};

export default Index;
