import React, { useEffect, useMemo, useState } from "react";
import {
  Box,
  Button,
  Card,
  CircularProgress,
  Grid,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  Typography,
} from "@mui/material";
import ArrowBackIosNewIcon from "@mui/icons-material/ArrowBackIosNew";
import EditIcon from "@mui/icons-material/Edit";
import DeleteIcon from "@mui/icons-material/Delete";
import AddIcon from "@mui/icons-material/Add";
import { useNavigate, useParams } from "react-router-dom";
import { useStyles } from "../../../theme/styles";
import {
  useDeleteCustomerTransactionMutation,
  useGetCustomerQuery,
  useGetCustomerTransactionQuery,
} from "../../../Api/attoDeskApi";
import {
  ICustomer,
  ICustomerTransaction,
} from "../../../Api/Interface/api.interface";
import NewPopUpCustomer from "../../Customer/Components/NewPopUpCustomer";
import NewCustomerTransactionPopUp from "./NewCustomerTransactionPopUp";
import { useNotifier } from "../../../Core/Notifier";
import DeletePopup from "../../../Components/Delete/DeletePopup";

const Index: React.FC = () => {
  const navigate = useNavigate();
  const classes = useStyles();
  const { id: customerId } = useParams<{ id: string }>();
  const [selectCustomer, setSelectCustomer] = useState<ICustomer | null>(null);
  const [transactionData, setTransactionData] =
    useState<ICustomerTransaction>();
    const [deleteCategory] = useDeleteCustomerTransactionMutation();
  const [openDialog, setOpenDialog] = useState(false);
  const [openAddTransaction, setOpenAddTransaction] = useState(false);
  const { showErrorMessage, showMessage } = useNotifier();
  const [openDeleteCategory, setOpenDeleteCategory] = useState(false);
  const [coursingToDelete, setCoursingToDelete] =
    useState<ICustomerTransaction | null>(null);
  useEffect(() => {
    // console.log("URL Credit ID:", customerId);
  }, [customerId]);

  const { data, isLoading, isError } = useGetCustomerQuery({
    searchText: "",
    id: String(customerId),
  });

  const { data: customerTransactionData, isLoading: customerDataIsLoading } =
    useGetCustomerTransactionQuery({
      searchText: "",
      customerId: String(customerId),
      projectId: "",
    });

  const customer = useMemo(() => {
    if (data && Array.isArray(data.data) && data.data.length > 0) {
      return data.data[0] as ICustomer;
    }
    return null;
  }, [data]);

  const transactions: ICustomerTransaction[] = useMemo(() => {
    if (
      customerTransactionData &&
      Array.isArray(customerTransactionData.data)
    ) {
      return customerTransactionData.data as ICustomerTransaction[];
    }
    return [];
  }, [customerTransactionData]);

  const handleOpenDialog = (customer: ICustomer) => {
    setSelectCustomer(customer);
    setOpenDialog(true);
  };

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

  const handleOpenAddTransaction = () => {
    setTransactionData(undefined);
    setOpenAddTransaction(true);
  };

  const handleCloseAddTransaction = () => {
    setTransactionData(undefined);
    setOpenAddTransaction(false);
  };

  if (isLoading) {
    return <CircularProgress />;
  }

  if (isError) {
    return (
      <Typography color="error">
        Error fetching customer data. Please try again later.
      </Typography>
    );
  }

  if (!customer) {
    return <Typography>No customer data available.</Typography>;
  }
  const handleOpenDeletePopup = (coursing: ICustomerTransaction) => {
    setCoursingToDelete(coursing);
    setOpenDeleteCategory(true);
  };

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

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

  

  return (
    <Box sx={{ p: 2 }} className={classes.indexBox}>
      <Grid container>
        <Grid item lg={12} md={12} sm={12} xs={12} className={classes.grid1}>
          <Card
            sx={{
              p: 2,
              width: "100%",
              boxShadow: "none",
              pb: 2,
            }}
          >
            <Grid container spacing={5}>
              <Grid
                item
                lg={12}
                md={12}
                sm={12}
                xs={12}
                className={classes.cardTitleGrid}
              >
                <Box
                  sx={{
                    textAlign: "start",
                  }}
                >
                  <Button
                    startIcon={<ArrowBackIosNewIcon sx={{ fontSize: 40 }} />}
                    className={classes.backButton}
                    onClick={() => navigate(-1)}
                  >
                    Back
                  </Button>
                </Box>
              </Grid>
              <Grid
                item
                lg={12}
                md={12}
                sm={12}
                xs={12}
                py={2}
                sx={{ borderBottom: 1 }}
                className={classes.cardTitleGrid}
              >
                <Grid container direction="row" alignItems="center" spacing={2}>
                  <Grid item lg={10} md={10} sm={12} xs={12}>
                    <Typography
                      className={classes.cardTitleProfileVieTypography}
                    >
                      {customer.customerFirstName +
                        " " +
                        customer.customerLastName}
                    </Typography>
                    <Typography>
                      {customer.customerMobileNum +
                        " / " +
                        customer.customerEmail}
                    </Typography>
                    <Typography>{customer.customerAddress}</Typography>
                  </Grid>
                  <Grid
                    item
                    lg={2}
                    md={2}
                    sm={12}
                    xs={12}
                    sx={{ display: "flex", justifyContent: "flex-end" }}
                  >
                    <Grid
                      container
                      spacing={1}
                      sx={{
                        display: "flex",
                        justifyContent: "flex-end",
                      }}
                    >
                      <Grid item>
                        <Button
                          variant="contained"
                          className={classes.searchButton}
                          onClick={() => handleOpenDialog(customer)}
                        >
                          <EditIcon />
                        </Button>
                      </Grid>
                    </Grid>
                  </Grid>
                </Grid>
              </Grid>
              <Grid
                item
                lg={12}
                md={12}
                sm={12}
                xs={12}
                py={5}
                sx={{
                  display: "flex",
                  justifyContent: "flex-end",
                }}
              >
                <Button
                  variant="contained"
                  startIcon={<AddIcon sx={{ fontSize: 40 }} />}
                  className={classes.indexButton}
                  onClick={handleOpenAddTransaction}
                >
                  Transaction
                </Button>
              </Grid>
              <Grid item lg={12} md={12} sm={12} xs={12} py={5} pt={10}>
                <Grid container direction="row" alignItems="center" spacing={2}>
                  <TableContainer>
                    <Table>
                      <TableHead>
                        <TableRow>
                          <TableCell className={classes.CustomerViewtypography}>
                            Transaction Name
                          </TableCell>
                          <TableCell className={classes.CustomerViewtypography}>
                            Amount
                          </TableCell>
                          <TableCell className={classes.CustomerViewtypography}>
                            Collection
                          </TableCell>
                          <TableCell className={classes.CustomerViewtypography}>
                            Reminder
                          </TableCell>
                          <TableCell className={classes.CustomerViewtypography}>
                            Description
                          </TableCell>
                          <TableCell
                            sx={{ textAlign: "right" }}
                            className={classes.CustomerViewtypography}
                          >
                            Action
                          </TableCell>
                        </TableRow>
                      </TableHead>
                      <TableBody>
                        {transactions.map((transaction) => (
                          <TableRow key={transaction.id}>
                            <TableCell className={classes.typography}>
                              {transaction.transactionName}
                            </TableCell>
                            <TableCell className={classes.typography}>
                              {transaction.transactionAmount}
                            </TableCell>
                            <TableCell className={classes.typography}>
                              {transaction.transactionCollection}
                            </TableCell>
                            <TableCell className={classes.typography}>
                              {transaction.transactionReminderDate}
                            </TableCell>
                            <TableCell className={classes.typography}>
                              {transaction.transactionDescription}
                            </TableCell>
                            <TableCell
                              sx={{ textAlign: "right" }}
                              className={classes.typography}
                            >
                              <Grid
                                container
                                spacing={1}
                                sx={{
                                  display: "flex",
                                  justifyContent: "flex-end",
                                }}
                              >
                                <Grid item>
                                  <Button
                                    variant="contained"
                                    className={classes.searchButton}
                                    onClick={() => {
                                      setTransactionData(transaction);
                                      setOpenAddTransaction(true);
                                    }}
                                  >
                                    <EditIcon />
                                  </Button>
                                </Grid>
                                <Grid item>
                                  <Button
                                    variant="contained"
                                    className={classes.resetButton}
                                    onClick={() => handleOpenDeletePopup(transaction)}
                                  >
                                    <DeleteIcon />
                                  </Button>
                                </Grid>
                              </Grid>
                            </TableCell>
                          </TableRow>
                        ))}
                      </TableBody>
                    </Table>
                  </TableContainer>
                </Grid>
              </Grid>
            </Grid>
          </Card>
        </Grid>
      </Grid>
      {selectCustomer && (
        <NewPopUpCustomer
          openModel={openDialog}
          handleCloseDialog={handleCloseDialog}
          data={selectCustomer}
        />
      )}
      {openAddTransaction && (
        <NewCustomerTransactionPopUp
          openModel={openAddTransaction}
          handleCloseDialog={handleCloseAddTransaction}
          data={transactionData}
          customerId={customerId}
        />
      )}
      {coursingToDelete && (
        <DeletePopup
          open={openDeleteCategory}
          handleCloseDelete={handleCloseDeletePopup}
          onConfirm={async () => {
            await handleDelete(coursingToDelete.id.toString());
          }}
          title="Delete Customer"
          content={`Are you sure you want to delete "${coursingToDelete.transactionName}"?`}
        />
      )}
    </Box>
  );
};

export default Index;
