import React, { useEffect, useState, useRef } from "react";
import TitleCard from "pages/titleCard";
import { useTheme } from "@mui/material/styles";
import axios from "axios";
import {
  Stack,
  TextField,
  Autocomplete,
  TableContainer,
  Table,
  TableHead,
  TableRow,
  TableCell,
  TableBody,
  Chip,
  Button,
  Dialog,
  DialogTitle,
  DialogContent,
  DialogContentText,
  DialogActions,
  Typography,
  Grid,
} from "@mui/material";
import MainCard from "components/MainCard";
import Loader from "components/Loader";
import AddIcon from "@mui/icons-material/Add";
import dayjs from "dayjs";
import { enqueueSnackbar } from "notistack";
import { Empty } from "antd";

// ==============================|| Starts here ||============================== //
const ClientsPricing = () => {
  const theme = useTheme();
  const [appId, setAppId] = useState(0);
  const [appId1, setAppId1] = useState(0);
  const [locations, setLocations] = useState([]);
  const [locations1, setLocations1] = useState([]);
  const [locaName, setLocoName] = useState("All");
  const [locaName1, setLocoName1] = useState("Select Location");
  const [pricing, setpricing] = useState([]);
  const [isLoader, setIsloader] = useState([]);
  const [pricingDialog, setPricingDialog] = useState(false);
  const [appPricing, setAppPricing] = useState([]);
  const [appConfig, setAppConfig] = useState([]);
  const [newPricing, setNewPricing] = useState({
    applocation: "",
    appname: "",
    slab: "",
    baseprice: null,
    minkm: null,
    priceperkm: null,
    maxkm: null,
    minorder: null,
  });
  const [isAppId, setIsAppId] = useState(true);

  // ==============================|| formatNumberToRupees ||============================== //
  function formatNumberToRupees(value) {
    return new Intl.NumberFormat("en-IN", {
      style: "currency",
      currency: "INR",
      minimumFractionDigits: 2,
    }).format(value);
  }
  function dotzerozero(value) {
    return new Intl.NumberFormat("en-IN", {
      minimumFractionDigits: 2,
    }).format(value);
  }
  /* ============================================= || opentoast || ============================================= */
  const opentoast = (message, variant, duration) => {
    enqueueSnackbar(message, {
      variant: variant,
      anchorOrigin: { vertical: "top", horizontal: "right" },
      autoHideDuration: duration,
    });
  };
  // ==============================|| fetchAppLocations ||============================== //
  const fetchAppLocations = async () => {
    try {
      const locationRes = await axios.get(
        `${process.env.REACT_APP_URL}/utils/getapplocations`
      );
      const updatedLocations = [
        ...locationRes.data.details,
        { locationname: "All", applocationid: 0 }, // Add your new object here
      ];
      console.log("fetchAppLocations", updatedLocations);
      setLocations(updatedLocations);
    } catch (err) {
      console.log("locationRes", err);
    }
  };
  // ==============================|| fetchAppLocations1 (for createpricing ) ||============================== //
  const fetchAppLocations1 = async () => {
    try {
      const locationRes = await axios.get(
        `${process.env.REACT_APP_URL}/utils/getapplocations`
      );
      console.log("fetchAppLocations", locationRes.data.details);
      setLocations1(locationRes.data.details);
    } catch (err) {
      console.log("locationRes", err);
    }
  };
  useEffect(() => {
    fetchAppLocations();
    fetchAppLocations1();
  }, []);
  // ==============================|| getAllPricing ||============================== //
  const getAllPricing = async () => {
    setIsloader(true);
    try {
      const pricingres = await axios.get(
        `${process.env.REACT_APP_URL}/utils/getallpricing/?applocationid=${appId}`
      );
      console.log("pricingres", pricingres.data.details);
      setpricing(pricingres.data.details);
      setIsloader(false);
    } catch (err) {
      console.log("pricingres", err);
    }
  };
  useEffect(() => {
    getAllPricing();
  }, [appId]);

  /* ============================================= || getAppPricing || ============================================= */
  const getAppPricing = async () => {
    try {
      let appPricingRes = await axios.get(
        `${process.env.REACT_APP_URL}/utils/getapppricing/?applocationid=${appId1}`
      );
      console.log("appPricingRes", appPricingRes.data.details);
      setAppPricing(appPricingRes.data.details);
    } catch (error) {
      console.log("appPricingRes", error);
    }
  };
  useEffect(() => {
    appId1 && getAppPricing();
  }, [appId1]);

  /* ============================================= || getallappconfig || ============================================= */
  const getallappconfig = async () => {
    try {
      let appConfigRes = await axios.get(
        `${process.env.REACT_APP_URL}/utils/getallappconfig`
      );
      console.log("appConfigRes", appConfigRes.data.details);
      setAppConfig(appConfigRes.data.details);
    } catch (error) {
      console.log("appConfigRes", error);
    }
  };
  useEffect(() => {
    getallappconfig();
  }, []);
  /* ============================================= || createPricing || ============================================= */
  const createPricing = async () => {
    try {
      // Validate each field
      for (const field in newPricing) {
        if (newPricing[field] === "" || newPricing[field] == null) {
          console.log("testing", newPricing[field]);
          opentoast(`Please enter ${field}`, "warning", 1500);
          return;
        }
      }

      // API Call
      const createPricingres = await axios.post(
        `${process.env.REACT_APP_URL}/utils/createapppricing`,
        {
          ...newPricing,
          pricingdate: dayjs().format("YYYY-MM-DD HH:mm:ss"), // Ensure consistency
        }
      );

      console.log("createPricingres", createPricingres);

      if (createPricingres.data.status) {
        await opentoast("Created Successfully", "success", 1500);
        setPricingDialog(false);
        getAllPricing();
      }
    } catch (err) {
      console.log("Error in createPricing:", err);
    } finally {
      setNewPricing({});
    }
  };

  return (
    <>
      {isLoader && <Loader />}
      {/* ============================================= || Title Card || =============================================  */}
      <Stack
        direction={"row"}
        justifyContent="space-between"
        alignItems="center"
        sx={{ my: 1 }}
      >
        <TitleCard title="Pricing" />
        <Stack
          sx={{
            display: "flex",
            flexDirection: "row",
            alignItems: "center",
            justifyContent: "center",
          }}
        >
          <Autocomplete
            disablePortal
            id="combo-box-demo"
            options={locations}
            getOptionLabel={(option) => `${option.locationname}`}
            sx={{ width: 280, zIndex: "100", mr: 3 }}
            onChange={(event, value, reason) => {
              if (reason === "clear") {
                setAppId(0);
                setLocoName("All");
              } else {
                console.log(value);
                setAppId(value.applocationid);
                setLocoName(value.locationname);
              }
            }}
            renderInput={(params) => <TextField {...params} label={locaName} />}
          />
          <Button
            startIcon={<AddIcon fontSize="large" />}
            sx={{ width: 120, height: 38 }}
            size="small"
            color="primary"
            variant="contained"
            onClick={() => {
              setPricingDialog(true);
            }}
          >
            Add Pricing
          </Button>
        </Stack>
      </Stack>
      {/* ============================================= || table  || =============================================  */}
      <MainCard content={false}>
        <TableContainer>
          <Table>
            <TableHead sx={{ bgcolor: "#e1bee7" }}>
              <TableRow>
                <TableCell>S.No</TableCell>
                <TableCell>Location</TableCell>
                <TableCell>Name</TableCell>
                <TableCell>Slab</TableCell>
                <TableCell align="center">Base Price</TableCell>
                <TableCell align="center">MinKm</TableCell>
                <TableCell align="center">Price/Km</TableCell>
                <TableCell align="center">MaxKm</TableCell>
                <TableCell>Min Orders</TableCell>
              </TableRow>
            </TableHead>
            <TableBody>
              {!pricing ? (
                <TableRow>
                  <TableCell colSpan={9}>{Empty}</TableCell>
                </TableRow>
              ) : (
                pricing.map((data, index) => (
                  <TableRow>
                    <TableCell>{index + 1}</TableCell>
                    <TableCell>{data.applocation}</TableCell>{" "}
                    <TableCell>{data.appname}</TableCell>
                    <TableCell>{data.slab}</TableCell>
                    <TableCell align="center">
                      <Chip
                        size="small"
                        color="primary"
                        label={formatNumberToRupees(data.baseprice)}
                        sx={{ width: 100 }}
                      />
                    </TableCell>
                    <TableCell align="center">
                      <Chip
                        size="small"
                        color="warning"
                        label={`${dotzerozero(data.minkm)} km`}
                        sx={{ width: 100 }}
                      />
                    </TableCell>
                    <TableCell align="center">
                      <Chip
                        size="small"
                        color="success"
                        label={formatNumberToRupees(data.priceperkm)}
                        sx={{ width: 100 }}
                      />
                    </TableCell>
                    <TableCell align="center">
                      <Chip
                        size="small"
                        color="error"
                        label={`${dotzerozero(data.maxkm)} km`}
                        sx={{ width: 100 }}
                      />{" "}
                    </TableCell>
                    <TableCell> {data.minorder}</TableCell>
                  </TableRow>
                ))
              )}
            </TableBody>
          </Table>
        </TableContainer>
      </MainCard>
      {/* ============================================= || CreatePricing dialog  || =============================================  */}
      <Dialog
        open={pricingDialog}
        onClose={() => {
          setPricingDialog(false);
        }}
        maxWidth={"md"}
        fullWidth
      >
        <DialogTitle
          sx={{ bgcolor: theme.palette.primary.main, color: "white" }}
        >
          <Stack
            sx={{ display: "flex", alignItems: "center", flexDirection: "row" }}
          >
            <AddIcon fontSize="large" />{" "}
            <Typography variant="h3">Add pricing</Typography>
          </Stack>
        </DialogTitle>
        <DialogContent>
          <Grid container sx={{ my: 1 }} spacing={5}>
            <Grid item xs={6}>
              <Autocomplete
                fullWidth
                disablePortal
                id="combo-box-demo"
                options={locations1 || ""}
                getOptionLabel={(option) => `${option.locationname}`}
                sx={{ zIndex: "100" }}
                onChange={(event, value, reason) => {
                  if (reason === "clear") {
                    setLocoName1("Select Location");
                    setIsAppId(true);
                  } else {
                    console.log(value);
                    setAppId1(value.applocationid);
                    setLocoName1(value.locationname);
                    setNewPricing({
                      ...newPricing,
                      applocationid: value.applocationid,
                      applocation: value.locationname,
                    });
                    setIsAppId(false);
                  }
                }}
                renderInput={(params) => (
                  <TextField {...params} label={locaName1} />
                )}
              />
            </Grid>
            <Grid item xs={6}>
              <Autocomplete
                disablePortal
                id="combo-box-demo"
                options={appConfig}
                getOptionLabel={(option) => `${option.appname}`}
                fullWidth
                selectOnFocus
                renderInput={(params) => (
                  <TextField {...params} label=" App Name" />
                )}
                onChange={(event, value, reason) => {
                  console.log("appConfig", value);
                  setNewPricing({
                    ...newPricing,
                    appname: value.appname,
                    configid: value.configid,
                  });
                  if (reason === "clear") {
                  }
                }}
              />{" "}
            </Grid>
            <Grid item xs={6}>
              <Autocomplete
                disabled={isAppId}
                disablePortal
                id="combo-box-demo"
                options={appPricing}
                getOptionLabel={(option) => `${option.slab}`}
                fullWidth
                selectOnFocus
                renderInput={(params) => <TextField {...params} label="Slab" />}
                onChange={(event, value, reason) => {
                  console.log("appPricing", value);
                  setNewPricing({
                    ...newPricing,
                    slab: value.slab,
                    pricingid: 0,
                    pricingtypeid: value.pricingtypeid,
                  });
                  if (reason === "clear") {
                  }
                }}
              />{" "}
            </Grid>

            <Grid item xs={6}>
              <TextField
                fullWidth
                type="number"
                required
                id="outlined-required"
                label="Base Price"
                onChange={(e) => {
                  setNewPricing({
                    ...newPricing,
                    baseprice: +e.target.value,
                  });
                }}
              />
            </Grid>
            <Grid item xs={6}>
              <TextField
                fullWidth
                type="number"
                required
                id="outlined-required"
                label="Minkm"
                onChange={(e) => {
                  setNewPricing({
                    ...newPricing,
                    minkm: +e.target.value,
                  });
                }}
              />
            </Grid>
            <Grid item xs={6}>
              <TextField
                fullWidth
                type="number"
                required
                id="outlined-required"
                label="Priceperkm"
                onChange={(e) => {
                  setNewPricing({
                    ...newPricing,
                    priceperkm: +e.target.value,
                  });
                }}
              />
            </Grid>
            <Grid item xs={6}>
              <TextField
                fullWidth
                type="number"
                required
                id="outlined-required"
                label="Maxkm"
                onChange={(e) => {
                  setNewPricing({
                    ...newPricing,
                    maxkm: +e.target.value,
                  });
                }}
              />
            </Grid>
            <Grid item xs={6}>
              <TextField
                fullWidth
                type="number"
                required
                id="outlined-required"
                label="Minorder"
                onChange={(e) => {
                  setNewPricing({
                    ...newPricing,
                    minorder: +e.target.value,
                  });
                }}
              />
            </Grid>
          </Grid>
        </DialogContent>
        <DialogActions sx={{ bgcolor: "#eee", m: 3 }}>
          <Button
            size="large"
            variant="contained"
            color="error"
            onClick={() => {
              setPricingDialog(false);
              setLocoName1("Select Location");
            }}
            sx={{ mr: 3 }}
          >
            Cancel
          </Button>
          <Button
            size="large"
            variant="contained"
            color="success"
            onClick={() => {
              createPricing();
            }}
          >
            Add
          </Button>
        </DialogActions>
      </Dialog>
    </>
  );
};

export default ClientsPricing;
