import React, { useEffect, useMemo, useState} from "react";
import {
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  CircularProgress,
  Grid,
  Box,
  Button,
  Typography,
  TextField,
  MenuItem,
  InputAdornment,
  Card,
  IconButton
} from "@mui/material";


import { useNotifier } from "../../../Core/Notifier";
import { useStyles } from "../../../theme/appStyles";
import { useNavigate } from "react-router-dom";
import { CiSearch } from "react-icons/ci";
import DeleteOutlineSharpIcon from "@mui/icons-material/DeleteOutlineSharp";
import EditSharpIcon from "@mui/icons-material/EditSharp";
import AddIcon from "@mui/icons-material/Add";
import Pagination from "../../../Components/Pagination";
import axios from "axios";
import dayjs from 'dayjs';
import { IDriver } from "../../../Api/Interface/api.interface";

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;
}

interface UserInfo {
  id: number;
  username: string;
  token: string;
  user_id: number;
}

interface Deposit {
  id: number;
  amount: string;
  user_id: number;
  created_at: string;
  date: string;
  is_approved: boolean; 
  remarks: string;
  projectId: string;
}


interface Expense {
  id: number;
  projectId: string;
  date: string;
  description: string;
  remarks: string;
  amount: number;
  hst: number;
  category: number;
  status: number;
  total: number;
  installment: number;
  installment_details: Installment[];
  file?: string;
  created_at: string;
  before_images?: string;
  after_images?: string;
}

interface Installment  {
  date: string;
  amount: string;
  paymentMode: string;
  description: string;
};


const Index = () => {
  const classes = useStyles();
  const navigate = useNavigate();
  const [projects, setProjects] = useState<Project[]>([]); 
  const { showErrorMessage, showMessage } = useNotifier();
  const API_URL = process.env.REACT_APP_API_URL;
  const [searchQuery, setSearchQuery] = useState(""); 
  const [page, setPage] = useState(0);
const [rowsPerPage, setRowsPerPage] = useState(50);
 const [team, setTeam] = useState<IDriver[]>([]); 
  const LARAVEL_API_URL = process.env.REACT_APP_LARAVEL_API;
  const [userInfo, setUserInfo] = useState<UserInfo | null>(null);
  const [deposit, setDeposit] = useState<Deposit[]>([]); 
  const currentUser = userInfo ? team.find(driver => driver.id === userInfo.user_id) : null;
  const [expenses, setExpenses] = useState<Expense[]>([]); 
  const [selectedExpense, setSelectedExpense] = useState<Expense | null>(null);
    const [installments, setInstallments] = useState<Installment[]>([]);
// Get allocated project IDs
let allocatedProjectIds: number[] = [];

if (currentUser) {
  if (typeof currentUser.projectId === "string") {
    try {
      allocatedProjectIds = JSON.parse(currentUser.projectId);
    } catch {
      allocatedProjectIds = [parseInt(currentUser.projectId)];
    }
  } else if (Array.isArray(currentUser.projectId)) {
    allocatedProjectIds = currentUser.projectId;
  } else if (typeof currentUser.projectId === "number") {
    allocatedProjectIds = [currentUser.projectId];
  }
}


const filteredProjects = projects.filter(project =>
  project.projectName.toLowerCase().includes(searchQuery.toLowerCase()) &&
  allocatedProjectIds.includes(project.id)
)

  const currentUserId = parseInt(localStorage.getItem("user_id") || "0");
  // console.log(currentUserId);

  const handleEditClick = (id: number) => {
    navigate(`/project/${id}`);
  };

const handleDeleteClick = (id: number) => {
  const confirmDelete = window.confirm("Are you sure you want to delete this project?");
  if (!confirmDelete) return;

  const headers = {
    Authorization: `Bearer ${localStorage.getItem("token") || ""}`,
  };

  axios.delete(`${API_URL}/delete-project/${id}`, { headers })
    .then(() => {
      setProjects(projects.filter((project) => project.id !== id));
      showMessage("Deleted successfully");
    })
    .catch((error) => {
      showErrorMessage("Failed to delete the project");
    });
};





  useEffect(() => {


        const fetchUserInfo = async () => {
          try {
              const response = await axios.post(
                  `${API_URL}/user/userInfo`,
                  {}, // No body required
                  {
                      headers: {
                          'Content-Type': 'application/json',
                          Authorization: `Bearer ${localStorage.getItem('token') || ''}`, // Include token from localStorage
                      },
                  }
              );
              setUserInfo(response.data.data); // Update your state with the response
            // console.log(response.data.data)
          } catch (error) {
              console.error('Error fetching user info', error);
          }
      };
    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);
      }
    };

     const fetchTeam = async () => {
          try {
            const response = await axios.get(`${API_URL}/view-team`);
            // setTeam(response.data.data);
            const team: IDriver[] = response.data.data;
    //    const managers = team.filter(driver => {
    //   const ids = typeof driver.projectId === 'string' ? JSON.parse(driver.projectId) : driver.projectId;
    //   return (
    //     driver.driverUserRole === 'manager' &&
    //     Array.isArray(ids) &&
    //     ids.includes(parseInt(projectId || '0'))
    //   );
    // });
    
       
            setTeam(team); 
           // console.log(response.data.data);
          } catch (error) {
            console.error("Failed to load team members", error);
          }
        };
const fetchDeposit = async () => {
      try {
        const response = await axios.get(`${API_URL}/view-all-deposits`);
        setDeposit(response.data); // Set the fetched data to state
        // console.log(response.data);
      } catch (error) {
        console.error("Failed to load expenses", error);
      }
    };
  const fetchExpenses = async () => {
      try {
       
        const response = await axios.get(`${API_URL}/view-all-expenses`);
        setExpenses(response.data); // Set the fetched data to state
   // console.log(response.data)
      if (selectedExpense) {
      const updatedExpense = response.data.find((exp: any) => exp.id === selectedExpense.id);
      if (updatedExpense) {
        setSelectedExpense(updatedExpense);
        // Also update installments based on the updated expense
        let updatedInstallments = [];
        try {
          updatedInstallments = updatedExpense.installment_details
            ? JSON.parse(updatedExpense.installment_details)
            : [];
        } catch {
          updatedInstallments = [];
        }
        setInstallments(updatedInstallments);
      }
    }
  } catch (error) {
    console.error("Failed to load expenses", error);
  }
};
        
    fetchProjects();
    fetchExpenses();
    fetchTeam();
    fetchUserInfo();
    fetchDeposit();
  }, [API_URL]);

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

  const handleAddProjectClick = () => {
    navigate("/project/create");
  };

  



  return (

 <>
    <Box display="flex" justifyContent="center" alignItems="center">

<Grid container spacing={3} px={3} pt={3} pb={5}>
  {filteredProjects.length > 0 ? (
    filteredProjects
      .filter((project) => project.projectStatus === "1")
      .map((project, index) => {
        const start = dayjs(project.projectStartDate);
        const today = dayjs();
        const days = project.projectStartDate
          ? today.diff(start, "day")
          : null;


          const projectDeposits = deposit.filter(
    (d) => Number(d.projectId) === project.id && d.is_approved
  );

  const projectExpenses = expenses.filter(
    (e) =>  Number(e.projectId) === project.id && String(e.status) === "Paid"
  );

  const totalDeposit = projectDeposits.reduce(
    (sum, d) => sum + Number(d.amount),
    0
  );

  const totalExpense = projectExpenses.reduce(
    (sum, e) => sum + Number(e.total),
    0
  );

  const bankBalance = totalDeposit - totalExpense;

        return (
          <Grid
            item
            xs={12}
            sm={6}
            md={4}
            lg={3}
            key={project.id}
            data-aos="fade-up"
            data-aos-delay={`${index * 100}`}
          >
     <Card  onClick={() => navigate(`/expense/list/${project.id}`)} 
  sx={{
    p: 2,
    height: "100%",
    display: "flex",
    flexDirection: "column",
    alignItems: "center",
    position: "relative",
    justifyContent: "flex-start",
      cursor: "pointer", 
        transition: "0.2s",
    "&:hover": {
      boxShadow: 4,
      transform: "scale(1.01)",
    },
  }}
>
  {/* Top-right Edit/Delete buttons */}
  <Box sx={{ position: "absolute", top: 8, right: 8, display: "flex", gap: 1 }}>
    <IconButton
      size="small"
      color="primary"
      onClick={(e) => {
    e.stopPropagation();
    handleEditClick(project.id);
  }}
    >
      <EditSharpIcon fontSize="small" />
    </IconButton>
    <IconButton
      size="small"
      color="error"
      onClick={(e) => {
    e.stopPropagation();
    handleDeleteClick(project.id);
  }}
    >
      <DeleteOutlineSharpIcon fontSize="small" />
    </IconButton>
  </Box>

  {/* Fixed-height Image Area */}
  <Box
    sx={{
     width: '100%',
      height: '120px',
      mb: 2,
      mt: 4, // leave space for top buttons
      borderRadius: 2,
      overflow: "hidden",
      display: "flex",
      alignItems: "center",
      justifyContent: "center",
      backgroundColor: project.projectImg ? "transparent" : "#f0f0f0",
    }}
  >
    {project.projectImg ? (
      <img
        src={`${LARAVEL_API_URL}/${project.projectImg}`}
        alt={project.projectName}
        style={{
        width: '100%',
        height: '120px',
         display: "flex",
      alignItems: "center",
      justifyContent: "center",
          borderRadius: 8,
          userSelect: "none",
        }}
        draggable={false}
        tabIndex={-1}
      />
    ) : (
      <Typography
        variant="h1"
        sx={{ color: "#666", fontWeight: 600, userSelect: "none" }}
      >
      {
    (
      project.projectName
        ?.split(' ')
        .find(word => /[A-Za-z]/.test(word))
        ?.match(/[A-Za-z]/)?.[0] || ''
    ).toUpperCase()
  }
      </Typography>
    )}
  </Box>

  {/* Project Name */}
  <Typography
    variant="h6"
    sx={{
      fontWeight: 600,
      textAlign: "center",
      minHeight: "1.0rem", // Ensures same space even with 1-line or 2-line names
    }}
  >
    {project.projectName}
  </Typography>

  {/* Days Since Start */}
  {project.projectStartDate && (
    <Typography
      variant="body2"
      sx={{
        px: 1.5,
        py: 0.5,
        borderRadius: 2,
        color: project.projectStatus === "Active" ? "#00796B" : "#E65100",
        fontWeight: 500,
        textAlign: "center",
      }}
    >
      ({days} days)
    </Typography>
  )}

<Box
  sx={{
    mt: "auto",
    width: "100%",
    display: "flex",
    justifyContent: "space-between",
    gap: 1.5, // space between boxes
  }}
>
  {/* Deposit */}
  <Box
    sx={{
      flex: 1,
      p: 1,
      borderRadius: 2,
      background: "#E0F2F1", // light teal
      textAlign: "center",
      boxShadow: 1,
    }}
  >
    <Typography variant="caption" sx={{ color: "#004D40", fontWeight: 500 }}>
      Deposit
    </Typography>
    <Typography variant="body2" sx={{ fontWeight: 700, color: "#00796B" }}>
      ${totalDeposit.toFixed(0)}
    </Typography>
  </Box>

  {/* Expense */}
  <Box
    sx={{
      flex: 1,
      p: 1,
      borderRadius: 2,
      background: "#FBE9E7", // light orange
      textAlign: "center",
      boxShadow: 1,
    }}
  >
    <Typography variant="caption" sx={{ color: "#BF360C", fontWeight: 500 }}>
      Expense
    </Typography>
    <Typography variant="body2" sx={{ fontWeight: 700, color: "#E65100" }}>
      ${totalExpense.toFixed(0)}
    </Typography>
  </Box>

  {/* Balance */}
  <Box
    sx={{
      flex: 1,
      p: 1,
      borderRadius: 2,
      background: "#E3F2FD", // light blue
      textAlign: "center",
      boxShadow: 1,
    }}
  >
    <Typography variant="caption" sx={{ color: "#0D47A1", fontWeight: 500 }}>
      Balance
    </Typography>
    <Typography
      variant="body2"
      sx={{
        fontWeight: 700,
        color: bankBalance >= 0 ? "#2E7D32" : "#C62828", // green if +, red if -
      }}
    >
      ${bankBalance.toFixed(0)}
    </Typography>
  </Box>
</Box>

</Card>

          </Grid>
        );
      })
  ) : (
    <Grid item xs={12}>
      <Typography align="center" sx={{ mt: 2 }}>
        {/* No Projects Found */}
      </Typography>
    </Grid>
  )}

  {/* Add New Project Card */}
  <Grid
  item
  xs={12}
  sm={6}
  md={4}
  lg={3}
  data-aos="fade-up"
  data-aos-delay="0"
>
  <Card
    sx={{
      p: 2,
      height: "100%",
      display: "flex",
      flexDirection: "column",
      alignItems: "center",
      justifyContent: "center",
      backgroundColor: "#fafafa",
      cursor: "pointer",
       transition: "0.2s",
    "&:hover": {
      boxShadow: 4,
      transform: "scale(1.01)",
    },
    }}
    onClick={handleAddProjectClick} // Replace with your actual function
  >
    <Box
      sx={{
        width: "100%",
        height: "120px",
        mb: 2,
        mt: 1,
        borderRadius: 2,
        display: "flex",
        alignItems: "center",
        justifyContent: "center",
        backgroundColor: "#f0f0f0",
      }}
    >
      <AddIcon color="action" sx={{ fontSize: 40 }} />
    </Box>
    <Typography variant="h6" sx={{ fontWeight: 600, textAlign: "center" }}>
      Add New Project
    </Typography>
  </Card>
</Grid>

</Grid>

</Box>
   
    
    <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}>Project</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="Project Name .."
                  sx={{ width: "100%" }}
                  size="small" />
              </Grid>

              {/* <Grid item>
                <Button
                  variant="contained"
                  className={classes.addButton}
                  onClick={handleAddProjectClick}
                >
                  Add project
                </Button>

              </Grid> */}





            </Grid>
          </Grid>
        </Grid>



        <Grid item lg={12} md={12} sm={12} xs={12}>
          <Card sx={{ padding: 3 }}>
            <TableContainer>
              <Table className={classes.table}>
                <TableHead className={classes.tableHeaderRow}>
                  <TableRow className={classes.tableRowHover}>
                    <TableCell className={classes.tablheader}>  <strong>Project Name</strong></TableCell>
                    <TableCell className={classes.tablheader} sx={{ textAlign: "right" }}>
                      <strong>Actions</strong>
                    </TableCell>
                  </TableRow>
                </TableHead>
                <TableBody>
                  {filteredProjects.filter((project) => project.projectStatus !== '1').length > 0 ? (
                    filteredProjects
                        .filter((project) => project.projectStatus !== '1')
.map((expense) => (
                      <TableRow key={expense.id}>
                        <TableCell scope="row" className={classes.tablCell} onClick={() => navigate(`/expense/list/${expense.id}`)}  sx={{ cursor: "pointer" }}>{expense.projectName}</TableCell>
                        <TableCell scope="row" className={classes.tablCell}>
                          <Grid
                            container
                            spacing={1}
                            sx={{ display: "flex", justifyContent: "flex-end" }}
                          >
                            <Grid item>
                              <Button
                                variant="contained"
                                className={classes.editButtonList}
                                onClick={() => handleEditClick(expense.id)}
                              >
                                <EditSharpIcon className={classes.editListIcon} />
                              </Button>
                            </Grid>
                            <Grid item>
                              <Button
                                variant="contained"
                                className={classes.deleteButtonList}
                                onClick={() => handleDeleteClick(expense.id)}
                              >
                                <DeleteOutlineSharpIcon
                                  className={classes.deleteButtonList} />
                              </Button>
                            </Grid>
                          </Grid>
                        </TableCell>
                      </TableRow>
                    ))
                  ) : (
                    <TableRow>
                      <TableCell colSpan={5} align="center">
                        No Data Available
                      </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={Math.ceil(filteredProjects.length / rowsPerPage)}
                    page={page}
                    rowsPerPage={rowsPerPage}
                    onPageChange={handleChangePage} />
                </Grid>
              </Grid>

            </TableContainer>


          </Card>
        </Grid>

      </Card></>
       

  );
};

export default Index;
