import React, { useEffect, useLayoutEffect, useState } from "react";
import style from "./checkout.module.css";
import {
  AccountCircle,
  Assignment,
  Payment,
  Place,
  ShoppingBasket,
} from "@mui/icons-material";
import Stepper from "@/components/utils/stepper";
import AccountCheckout from "@/components/checkout/account";
import AddressCheckout from "@/components/checkout/address";
import ReviewCheckout from "@/components/checkout/review";
import CheckoutPayment from "@/components/checkout/payment";
import { useSelector } from "react-redux";
import { validateAddress } from "../store/checkout";
import { createNotification } from "../customHook/useNotification";
import { useDispatch } from "react-redux";
import { checkoutStoreActions } from "../store/checkout";
import Head from "next/head";
import { useRouter } from "next/router";
import { getTotalStats, getCheckoutCart } from "@/store/checkout";
import { customerApi } from "@/api/api";

const Checkout = ({ metaData }) => {
  const dispatch = useDispatch();
  const totalStats = useSelector(getTotalStats);
  const router = useRouter();
  const accountLogin = useSelector((state) => state.accountStore.loggedIn);
  const shipOrPickup = useSelector(
    (state) => state.checkoutStore.ship_or_pickup
  );
  const checkoutCart = useSelector(getCheckoutCart);
  const addressValidate = useSelector(validateAddress);
  const [data, setData] = useState({
    account: {
      title: "Account",
      status: "active",
      icon: <AccountCircle />,
    },
    address: {
      title: "Delivery",
      status: "no",
      icon: <Place />,
    },
    review: {
      title: "Review",
      status: "no",
      icon: <Assignment />,
    },
    payment: {
      title: "Payment",
      status: "no",
      icon: <Payment />,
    },
  });
  useLayoutEffect(() => {
    if (totalStats.totalPrice > 0) {
      setData({
        account: {
          title: "Account",
          status: "active",
          icon: <AccountCircle />,
        },
        address: {
          title: "Delivery",
          status: "no",
          icon: <Place />,
        },
        review: {
          title: "Review",
          status: "no",
          icon: <Assignment />,
        },
        payment: {
          title: "Payment",
          status: "no",
          icon: <Payment />,
        },
      });
    } else {
      setData({
        account: {
          title: "Account",
          status: "active",
          icon: <AccountCircle />,
        },
        address: {
          title: "Delivery",
          status: "no",
          icon: <Place />,
        },
        review: {
          title: "Review",
          status: "no",
          icon: <Assignment />,
        },
        placeorder: {
          title: "Submit",
          status: "no",
          icon: <ShoppingBasket />,
        },
      });
    }
  }, []);

  const onAccountLoggedIn = () => {
    setData((prev) => {
      let newObject = { ...prev };
      newObject["account"].status = "completed";
      newObject["address"].status = "active";
      return newObject;
    });
    console.log("doneok");
  };

  const onAddressSubmit = () => {
    if (addressValidate && shipOrPickup === "shipping") {
      setData((prev) => {
        let newObject = { ...prev };
        newObject["address"].status = "completed";
        newObject["review"].status = "active";
        return newObject;
      });
    } else if (shipOrPickup === "pickup") {
      setData((prev) => {
        let newObject = { ...prev };
        newObject["address"].status = "completed";
        newObject["review"].status = "active";
        return newObject;
      });
    }
    console.log("hi");
  };

  const onSubmitClick = () => {
    setData((prev) => {
      let newObject = { ...prev };
      newObject["review"].status = "completed";
      newObject["payment"].status = "active";
      return newObject;
    });
  };

  const onBackClicked = (type) => {
    if (type == "address") {
      setData((prev) => {
        let newObject = { ...prev };
        newObject["address"].status = "active";
        newObject["review"].status = "no";
        return newObject;
      });
    } else if (type == "payment") {
      setData((prev) => {
        let newObject = { ...prev };
        newObject["review"].status = "active";
        newObject["payment"].status = "no";
        return newObject;
      });
    }
  };

  useEffect(() => {
    if (checkoutCart.length == 0) {
      window.location.href = "/";
    }
  }, []);

  return (
    <React.Fragment>
      <Head>
        <title>{metaData.meta_title ? metaData.meta_title : "Checkout"}</title>
        <meta charset="UTF-8" />
        <meta name="description" content={metaData.meta_description} />
        <meta
          name="keywords"
          content={
            metaData.meta_keywords && metaData.meta_keywords.length > 0
              ? metaData.meta_keywords.join(",")
              : ""
          }
        />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
      </Head>
      <div className={`container mt-2`}>
        <Stepper data={data} />
        <div className={style.add_new_address}>
          {data.account.status == "active" &&
            data.account.status != "completed" && (
              <AccountCheckout
                stepper={data}
                onAccountLoggedIn={() => onAccountLoggedIn()}
              />
            )}
        </div>
        <div className={style.add_new_address}>
          {data.address.status == "active" &&
            data.address.status != "completed" && (
              <AddressCheckout
                stepper={data}
                onAddressSubmit={(address) => onAddressSubmit(address)}
              />
            )}
        </div>
        {data.review.status == "active" &&
          data.review.status != "completed" && (
            <ReviewCheckout
              onSubmitClick={() => onSubmitClick()}
              onBackClicked={(type) => onBackClicked(type)}
            />
          )}
        {totalStats.totalPrice > 0 &&
          data.payment.status == "active" &&
          data.payment.status != "completed" && (
            <CheckoutPayment onBackClicked={(type) => onBackClicked(type)} />
          )}
      </div>
    </React.Fragment>
  );
};

export default Checkout;

export const getStaticProps = async (ctx) => {
  let metaData = {};
  await Promise.all([customerApi.get("/site/meta?path=/checkout")])
    .then((res) => {
      if (res[0] && res[0].data) metaData = res[0].data.data;
    })
    .catch((err) => {
      console.log("err:", err);
    });
  return {
    props: {
      metaData: metaData,
    },
    revalidate: 600,
  };
};
