import { Drawer, Switch } from "antd";
import React, { useEffect, useState } from "react";
import { useNavigate } from "react-router-dom";
import {
  IconArrowDown,
  IconCart2,
  IconChevronLeft,
  IconHome,
  IconMoney,
} from "../../components/Icon";
import ScaleLoading from "../../components/Loading/ScaleLoading";
import Button from "../../components/common/Button";
import { useAppStore } from "../../store/appStore";
import { useCartStore } from "../../store/cartStore";
import { useUserStore } from "../../store/userStore";
import { formatNumber } from "../../utils";
import CartProductItem from "./childs/CartProductItem";
import IconArrowLeft from "../../components/Icon/IconArrowLeft";
import styled from "styled-components";
import Footer from "../../components/Footer";

const CartStyles = styled.div`
  .fixed.bottom-0 {
    border-radius: 0 !important;
    box-shadow: none !important;
    border-top: 1px solid #ccc;
  }
`;

const Cart = () => {
  const navigate = useNavigate();
  const {
    loading,
    loadingCart,
    cartInfo,
    getCart,
    applyDiscount,
    isUseDiscountPrice,
    setIsUseDiscountPrice,
  } = useCartStore((state) => ({
    loading: state.loading,
    loadingCart: state.loadingCart,
    getCart: state.getCart,
    cartInfo: state.cartInfo,
    applyDiscount: state.applyDiscount,
    isUseDiscountPrice: state.isUseDiscountPrice,
    setIsUseDiscountPrice: state.setIsUseDiscountPrice,
  }));

  const {
    total_final,
    total_points_can_use,
    bonus_points_amount_can_use,
    balance_agency_can_use,
    balance_collaborator_can_use,
    product_discount_amount,
    total_before_discount,
    total_after_discount,
    line_items,
  } = cartInfo;
  const { appTheme } = useAppStore((state) => state);
  const { badges, userAddress, getUserAddress } = useUserStore((state) => ({
    badges: state.badges,
    userAddress: state.userAddress,
    getUserAddress: state.getUserAddress,
  }));
  const [isShowDetail, setShowDetail] = useState(false);
  const token = localStorage.getItem("token");

  //Handle Apply Discount
  const handleApplyDiscount = (type: string, value?: boolean | string) => {
    const info = {
      code_voucher: "",
      ...isUseDiscountPrice,
    };
    info[type] = value;

    applyDiscount(info);
  };

  const handleCheckbox = (checked: boolean, type: string) => {
    handleApplyDiscount(type, checked);
    setIsUseDiscountPrice({ [type]: checked });
  };

  //Handle Get Address Default
  const getAddressDefault = () => {
    const defaultAddressArr = userAddress.filter(
      (address) => address.is_default
    );
    return defaultAddressArr;
  };

  //Call API
  useEffect(() => {
    if (!token) navigate("/request-login");
    else {
      getCart(isUseDiscountPrice);
      getUserAddress();
    }
  }, []);

  return (
    <CartStyles className="h-[100vh]">
      <header
        className="pl-[12px] py-[10px] bg-primary text-[#fff] text-[20px] flex items-center"
        style={{
          backgroundColor: appTheme.color_main_1,
        }}
      >
        <IconArrowLeft
          className={"w-6 h-6 absolute"}
          onClick={() => navigate("/")}
        />

        <div className="text-center w-full">
          <p>Giỏ hàng</p>
          <p className="text-[14px]">{line_items?.length || 0} sản phẩm</p>
        </div>
      </header>
      {loadingCart ? (
        <div className="w-full h-[calc(100vh-60px)] flex justify-center items-center">
          <ScaleLoading loading={true}></ScaleLoading>
        </div>
      ) : (
        <>
          <main
            className={`${
              badges.status_agency === 1 || badges.status_collaborator === 1
                ? "h-[calc(100vh-60px-43px-44px-43px-75px)]"
                : "h-[calc(100vh-60px-43px-44px-75px)]"
            } overflow-y-auto bg-[#f7f7f7]`}
          >
            {(cartInfo.line_items ?? []).length > 0 ? (
              <>
                {cartInfo.line_items?.map((item, index) => (
                  <CartProductItem
                    key={item.id}
                    item={item}
                    isUseDiscountPrice={isUseDiscountPrice}
                    getAddressDefault={getAddressDefault}
                    endItem={index === cartInfo.line_items?.length - 1}
                  />
                ))}
              </>
            ) : loading === false ? (
              <div className="flex justify-center flex-col items-center mt-2">
                <p>Giỏ hàng trống,</p>
                <p>Mua hàng ngay thôi nào!</p>
                <div className="mt-2" onClick={() => navigate("/products")}>
                  <IconCart2 className="w-8 h-8" />
                </div>
              </div>
            ) : null}
          </main>
          <div className="w-full bg-white  py-[9px] border-b-[1px] border-[#ccc] shadow-md">
            <div className="flex justify-between items-center px-[8px]">
              <div className="flex gap-[10px] flex-1 items-center">
                <div
                  className="p-1 rounded-full bg-gray-100"
                  style={{
                    color: appTheme.color_main_1,
                  }}
                >
                  <IconMoney className="w-4 h-4" />
                </div>
                <p className="text-sm">
                  Dùng{" "}
                  {total_points_can_use
                    ? formatNumber(total_points_can_use)
                    : 0}{" "}
                  xu
                </p>
              </div>
              <div className="flex gap-[8px] flex-1 items-center justify-end">
                <p className="text-sm">
                  [ -
                  {bonus_points_amount_can_use
                    ? formatNumber(bonus_points_amount_can_use)
                    : 0}
                  đ]
                </p>
                <Switch
                  checked={isUseDiscountPrice.is_use_points}
                  onChange={(checked) =>
                    handleCheckbox(checked, "is_use_points")
                  }
                  className="bg-[#00000073]"
                />
              </div>
            </div>
          </div>
          {badges.status_agency === 1 ? (
            <div className="w-full bg-white border-b-[1px] border-[#ccc]">
              <div className="flex justify-between outline-none items-center py-[9px] px-[8px]">
                <div className="flex gap-[10px] flex-1 items-center">
                  <div
                    className="p-1 rounded-full bg-gray-100"
                    style={{
                      color: appTheme.color_main_1,
                    }}
                  >
                    <IconHome className="w-4 h-4" />
                  </div>
                  <p className="">Dùng số dư đại lý</p>
                </div>
                <div className="flex gap-[8px] flex-1 items-center justify-end">
                  <p className="text-sm">
                    [ -
                    {balance_agency_can_use
                      ? formatNumber(balance_agency_can_use)
                      : 0}
                    đ]
                  </p>
                  <Switch
                    checked={isUseDiscountPrice.is_use_balance_agency}
                    onChange={(checked) =>
                      handleCheckbox(checked, "is_use_balance_agency")
                    }
                    className="bg-[#00000073]"
                  />
                </div>
              </div>
            </div>
          ) : null}
          {badges.status_collaborator === 1 ? (
            <div className="w-full bg-white border-b-[1px] border-[#ccc]">
              <div className="flex justify-between outline-none items-center py-[9px] px-[8px]">
                <div className="flex gap-[10px] flex-1 items-center">
                  <div
                    className="p-1 rounded-full bg-gray-100"
                    style={{
                      color: appTheme.color_main_1,
                    }}
                  >
                    <IconHome className="w-4 h-4" />
                  </div>
                  <p className="">Dùng số dư CTV</p>
                </div>
                <div className="flex gap-[8px] flex-1 items-center justify-end">
                  <p className="text-sm">
                    [ -
                    {balance_collaborator_can_use
                      ? formatNumber(balance_collaborator_can_use)
                      : 0}
                    đ]
                  </p>
                  <Switch
                    checked={isUseDiscountPrice.is_use_balance_collaborator}
                    onChange={(checked) =>
                      handleCheckbox(checked, "is_use_balance_collaborator")
                    }
                    className="bg-[#00000073]"
                  />
                </div>
              </div>
            </div>
          ) : null}

          <div className="w-full bg-white flex justify-end gap-[25px] pr-4">
            <div className="text-end" onClick={() => setShowDetail(true)}>
              <p className="flex gap-x-1 mb-[1px]">
                <span className="text-sm">Tổng cộng:</span>
                <span className="text-red-600 font-semibold">
                  {total_final ? formatNumber(total_final) : 0} đ
                </span>
              </p>
              <p className="text-red-600 text-[10px] rounded-[4px] flex  justify-end">
                <span className="font-medium inline-flex bg-red-100 px-1 items-center gap-x-1">
                  Khuyến mãi:
                  {product_discount_amount
                    ? formatNumber(product_discount_amount)
                    : 0}{" "}
                  đ
                  <IconArrowDown className={"w-3 h-3"} />
                </span>
              </p>
            </div>
            <div className="flex">
              <button
                className={`p-[12px] text-[#fff] bg-gray-300 ${
                  cartInfo.line_items?.length > 0
                    ? ""
                    : "pointer-events-none select-none"
                }`}
                style={{
                  backgroundColor:
                    cartInfo.line_items?.length > 0
                      ? appTheme.color_main_1
                      : "",
                }}
                onClick={() => navigate("/confirm-order")}
              >
                <span className="font-semibold">Đặt hàng</span> (
                {line_items?.length})
              </button>
            </div>
          </div>
        </>
      )}
      <Footer></Footer>
      <Drawer
        placement={"bottom"}
        open={isShowDetail}
        height={"fit-content"}
        onClose={() => setShowDetail(false)}
        title="Chi tiết đơn hàng"
        bodyStyle={{ padding: 0 }}
      >
        <div>
          <div className="flex justify-between px-[8px] py-[12px]">
            <p>Tạm tính</p>
            <p>
              {total_before_discount > 0
                ? formatNumber(total_before_discount)
                : 0}{" "}
              đ
            </p>
          </div>
          <div className="flex justify-between px-[8px] py-[12px]">
            <p>Giảm giá sản phẩm</p>
            <p>
              -{" "}
              {product_discount_amount > 0
                ? formatNumber(product_discount_amount)
                : 0}{" "}
              đ
            </p>
          </div>
          <div className="flex justify-between px-[8px] py-[12px]">
            <p>Tổng giảm</p>
            <p>
              - {formatNumber(total_before_discount - total_after_discount)} đ
            </p>
          </div>
          <hr />
          <div className="flex justify-between px-[8px] py-[16px]">
            <p>Tổng tiền</p>
            <p> {total_final > 0 ? formatNumber(total_final) : 0} đ</p>
          </div>
        </div>
        <div className="py-2 bg-gray-100">
          <div className="bg-[#fff] py-[2px]">
            <Button
              className="w-[90%] mx-auto py-4 flex items-center justify-center"
              type="primary"
              style={{
                backgroundColor: appTheme.color_main_1,
              }}
              onClick={() => setShowDetail(false)}
            >
              Đóng
            </Button>
          </div>
        </div>
      </Drawer>
      {/* <Drawer
        placement={"right"}
        open={step == 2}
        height="h-[100vh]"
        width={"w-full"}
        onClose={() => setStep(1)}
        bodyStyle={{ padding: 0 }}
        headerStyle={{ display: "none" }}
      >
        <ConfirmOrder
          customerNote={customerNote}
          setStep={setStep}
          getAddressDefault={getAddressDefault}
          setCustomerNote={setCustomerNote}
          isUseDiscountPrice={isUseDiscountPrice}
          handleCheckbox={handleCheckbox}
        />
      </Drawer> */}
    </CartStyles>
  );
};

export default Cart;
