import React, { useEffect, useState } from "react";
import { useNavigate } from "react-router-dom";
import Button from "../../components/common/Button";
import { Input, Switch, Button as ButtonAnt } from "antd";
import { useAppStore } from "../../store/appStore";
import CartProductBooked from "./childs/CartProductBooked";
import { useCartStore } from "../../store/cartStore";
import { formatNumber } from "../../utils";
import { useUserStore } from "../../store/userStore";
import ShipmentFee from "./childs/ShipmentFee";
import PaymentMethod from "./childs/PaymentMethod";
import { useAccountStore } from "../../store/accountStore";
import { alerts } from "../../utils/alerts";
import OrderSuccess from "./childs/OrderSuccess";
import {
  IconCart,
  IconChevronLeft,
  IconChevronRight,
  IconDocument,
  IconFairTrade,
  IconHome,
  IconLocation,
  IconMoney,
  IconReceipt,
} from "../../components/Icon";
import Header from "../../components/Header";

const ConfirmOrder = () => {
  const navigate = useNavigate();
  const { appTheme } = useAppStore((state) => state);

  const {
    loading,
    loadingOrder,
    cartInfo,
    shipmentFee,
    paymentMethod,
    postListShipperFee,
    applyDiscount,
    isUseDiscountPrice,
    setIsUseDiscountPrice,
    customerInfo,
    setCustomerInfo,
    shipmentInfo,
    setShipmentInfo,
    paymentInfo,
    setPaymentInfo,
    getPaymentMethods,
    defaultAddress,
    setDefaultAddress,
    codeVoucher,
    orderCart,
  } = useCartStore((state) => ({
    loading: state.loading,
    loadingOrder: state.loadingOrder,
    cartInfo: state.cartInfo,
    getCart: state.getCart,
    shipmentFee: state.shipmentFee,
    paymentMethod: state.paymentMethod,
    postListShipperFee: state.postListShipperFee,
    applyDiscount: state.applyDiscount,
    isUseDiscountPrice: state.isUseDiscountPrice,
    setIsUseDiscountPrice: state.setIsUseDiscountPrice,
    customerInfo: state.customerInfo,
    setCustomerInfo: state.setCustomerInfo,
    shipmentInfo: state.shipmentInfo,
    setShipmentInfo: state.setShipmentInfo,
    paymentInfo: state.paymentInfo,
    setPaymentInfo: state.setPaymentInfo,
    getPaymentMethods: state.getPaymentMethods,
    defaultAddress: state.defaultAddress,
    setDefaultAddress: state.setDefaultAddress,
    codeVoucher: state.codeVoucher,
    orderCart: state.orderCart,
  }));

  const { accountInfo } = useAccountStore((state) => state);

  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,
    total_shipping_fee,
  } = cartInfo;
  const { badges, userAddress, getUserAddress } = useUserStore((state) => ({
    badges: state.badges,
    userAddress: state.userAddress,
    getUserAddress: state.getUserAddress,
  }));
  const [isShowShipmentModal, setIsShowShipmentModal] = useState(false);
  const [isShowPaymentModal, setIsShowPaymentModal] = useState(false);
  const [isShowOrderSuccess, setIsShowOrderSuccess] = useState(false);

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

    applyDiscount(info);
  };

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

  //Handle Order Product
  const handleOrder = () => {
    if (!defaultAddress.id) {
      alerts.error("Bạn chưa chọn địa chỉ nhận hàng!");
      return;
    }
    const orderInfo = {
      is_use_points: isUseDiscountPrice.is_use_points,
      is_use_balance_collaborator:
        isUseDiscountPrice.is_use_balance_collaborator,
      is_use_balance_agency: isUseDiscountPrice.is_use_balance_agency,
      customer_note: customerInfo.customer_note,
      code_voucher: codeVoucher,
      payment_method_id: paymentInfo.payment_method_id,
      payment_partner_id: paymentInfo.id,
      customer_address_id: defaultAddress.id,
      total_shipping_fee: shipmentInfo.fee,
      shipper_type: shipmentInfo.ship_speed_code,
      partner_shipper_id: shipmentInfo.partner_id,
      order_from: 0,
      from_pos: false,
      collaborator_by_customer_id:
        localStorage.getItem("cowc_id") ?? accountInfo.id,
    };

    orderCart(orderInfo, () => {
      setIsShowOrderSuccess(true);
    });
  };

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

  useEffect(() => {
    applyDiscount();
    getUserAddress();
  }, []);
  useEffect(() => {
    if (userAddress.length > 0) {
      const defaultAddressArr = getAddressDefault();
      if (defaultAddressArr.length > 0) {
        if (Object.entries(defaultAddress).length === 0) {
          setDefaultAddress(defaultAddressArr[0]);
          postListShipperFee(defaultAddressArr[0].id);
        } else {
          postListShipperFee(defaultAddress.id);
        }
      }
    }
  }, [userAddress]);
  useEffect(() => {
    getPaymentMethods();
  }, []);

  useEffect(() => {
    if ((paymentMethod ?? []).length > 0 && paymentInfo.id === "") {
      setPaymentInfo({
        id: paymentMethod?.[0]?.id,
        name: paymentMethod?.[0]?.name,
        payment_method_id: paymentMethod?.[0]?.payment_method_id,
      });
    }
  }, [paymentMethod]);

  useEffect(() => {
    if ((shipmentFee ?? []).length > 0 && shipmentInfo.partner_id === "") {
      setShipmentInfo({
        ...shipmentFee?.[0]?.fee_with_type_ship?.[0],
        partner_id: shipmentFee?.[0]?.partner_id,
        name: shipmentFee?.[0]?.name,
      });
      applyDiscount({
        total_shipping_fee: shipmentFee?.[0]?.fee_with_type_ship?.[0].fee,
      });
    }
  }, [shipmentFee]);

  return (
    <div>
      <Header
        title="Xác nhận đơn hàng"
        goBack={() => {
          navigate("/cart");
        }}
      ></Header>

      <main className="mb-[60px]">
        <div
          className="flex justify-between outline-none items-center py-[10px] px-3 border-b-[1px] border-[#e4e4e4] gap-4 bg-white"
          onClick={() => navigate("/cart-address")}
        >
          <div className="flex gap-[10px] flex-1">
            <div>
              <div
                className="p-1 rounded-full bg-gray-100"
                style={{
                  color: appTheme.color_main_1,
                }}
              >
                <IconLocation
                  className={"w-4 h-4"}
                  style={{
                    color: appTheme.color_main_1,
                  }}
                />
              </div>
            </div>
            <div className="text-sm">
              <p>Địa chỉ nhận hàng:</p>
              {Object.entries(defaultAddress).length > 0 ? (
                <div>
                  <div>{`${
                    defaultAddress.name ? `${defaultAddress.name} | ` : ""
                  }${defaultAddress.phone}`}</div>
                  <div>
                    {defaultAddress.email
                      ? defaultAddress.email
                      : "Chưa có Email"}
                  </div>
                  <div>
                    {defaultAddress.address_detail
                      ? defaultAddress.address_detail
                      : "Chưa có địa chỉ chi tiết"}
                  </div>
                  <div className="text-gray-500">
                    {`${defaultAddress.wards_name}, ${defaultAddress.district_name}, ${defaultAddress.province_name}`}
                  </div>
                </div>
              ) : (
                <div>Chưa chọn địa chỉ nhận hàng (nhấn để chọn)</div>
              )}
            </div>
          </div>
          <div className="flex gap-[3px] items-center justify-end">
            <IconChevronRight className={"w-4 h-4"} />
          </div>
        </div>
        <div className="p-[12px] flex gap-3 bg-white">
          <IconCart
            className={"w-5 h-5"}
            style={{
              color: appTheme.color_main_1,
            }}
          />
          <span className="font-semibold">Các mặt hàng đã đặt:</span>
        </div>
        <div>
          {cartInfo.line_items?.map((item, index) => (
            <CartProductBooked
              key={item.id}
              item={item}
              getAddressDefault={getAddressDefault}
              endItem={index === cartInfo.line_items?.length - 1}
            />
          ))}
        </div>
        {userAddress.length > 0 && (
          <div
            className="border-y border-green-500 px-3"
            onClick={() => setIsShowShipmentModal(true)}
          >
            <div className="text-green-500 py-[6px] border-b border-[#e4e4e4] text-sm">
              Đơn vị vận chuyển ( Nhấn để chọn )
            </div>
            <div className="py-1">
              <div className="font-semibold py-1">Vận chuyển nhanh</div>
              <div>
                <div className="flex justify-between items-center text-sm">
                  <div>{shipmentInfo.name}</div>
                  <div className="flex gap-x-1 items-center">
                    {shipmentInfo.fee > 0 ? formatNumber(shipmentInfo.fee) : 0}đ{" "}
                    <IconChevronRight className={"w-3 h-3"} />
                  </div>
                </div>
                <div className="text-sm">{shipmentInfo.description}</div>
              </div>
            </div>
          </div>
        )}

        <div className="bg-white py-2 px-3 border-b-[1px] border-[#e4e4e4] gap-x-1 flex items-center">
          <span className="font-semibold flex-shrink-0">Tin nhắn: </span>
          <Input
            className="w-full border-0 py-1 hover:border-0 focus:border-0 focus:shadow-none"
            placeholder="Lưu ý cho người bán..."
            value={customerInfo.customer_note}
            onChange={(e) =>
              setCustomerInfo({
                customer_note: e.target.value,
              })
            }
          />
        </div>
        <div className="bg-white p-3 flex justify-between ">
          <span className="font-semibold">
            Tổng số tiền ({cartInfo.line_items?.length} sản phẩm):{" "}
          </span>
          <span>
            {total_before_discount > 0
              ? formatNumber(total_before_discount)
              : 0}{" "}
            đ
          </span>
        </div>

        <div className=" outline-none py-2 bg-gray-100">
          <div
            className="flex justify-between items-center py-2 px-3 bg-[#fff]"
            onClick={() => navigate("/voucher-wallet")}
          >
            <div className="flex gap-[10px] flex-1 items-center">
              <IconReceipt
                className={"w-5 h-5"}
                style={{
                  color: appTheme.color_main_1,
                }}
              />
              <p className="font-semibold">Shop Voucher:</p>
            </div>
            <div className="flex gap-[3px] flex-1 items-center justify-end">
              <p className="text-sm">
                {codeVoucher !== "" ? codeVoucher : "chọn hoặc nhập mã"}
              </p>
              <IconChevronRight
                className={"w-3 h-3"}
                style={{
                  color: appTheme.color_main_1,
                }}
              />
            </div>
          </div>
        </div>

        <div
          className="flex justify-between outline-none items-center py-[10px] px-3 bg-white border-b-[1px] border-[#e4e4e4] text-xs"
          onClick={() => setIsShowPaymentModal(true)}
        >
          <div className="flex gap-[10px] flex-1 items-center">
            <div className="p-1 rounded-full bg-gray-100">
              <IconMoney
                className={"w-4 h-4"}
                style={{
                  color: appTheme.color_main_1,
                }}
              />
            </div>
            <p>Phương thức thanh toán</p>
          </div>
          <div className="flex gap-[3px] flex-1 items-center justify-end">
            <p
              style={{
                color: appTheme.color_main_1,
              }}
            >
              {paymentInfo.name}
            </p>
            <IconChevronRight className={"w-3 h-3"} />
          </div>
        </div>

        <div className=" border-b-[1px] border-[#e4e4e4] bg-white">
          <div className="flex justify-between items-center px-3 text-sm py-2">
            <div className="flex gap-[10px] flex-1 items-center">
              <div className="p-1 rounded-full bg-gray-100">
                <IconMoney
                  className={"w-4 h-4"}
                  style={{
                    color: appTheme.color_main_1,
                  }}
                />
              </div>

              <p>
                {" "}
                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>
                {" "}
                [ -
                {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_collaborator === 1 ? (
          <div className=" border-b-[1px] border-[#e4e4e4] bg-white">
            <div className="flex justify-between items-center px-3 py-2">
              <div className="flex gap-[10px] flex-1 items-center">
                <div className="p-1 rounded-full bg-gray-100">
                  <IconFairTrade
                    className={"w-4 h-4"}
                    style={{
                      color: appTheme.color_main_1,
                    }}
                  />
                </div>
                <p className="">Dùng số dư CTV</p>
              </div>
              <div className="flex gap-[8px] flex-1 items-center justify-end">
                <p className="">
                  [ -
                  {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}
        {badges.status_agency === 1 ? (
          <div className=" border-b-[1px] border-[#e4e4e4] bg-white">
            <div className="flex justify-between items-center px-3">
              <div className="flex gap-[10px] flex-1 items-center">
                <div className="p-1 rounded-full bg-gray-100">
                  <IconHome
                    className={"w-4 h-4"}
                    style={{
                      color: appTheme.color_main_1,
                    }}
                  />
                </div>

                <p className="">Dùng số dư đại lý</p>
              </div>
              <div className="flex gap-[8px] flex-1 items-center justify-end py-[8px]">
                <p className="">
                  [ -
                  {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}
        <div className="border-b-[1px] border-[#e4e4e4] px-3 py-1 flex flex-col gap-y-1">
          <div className="flex justify-between bg-[#fff]">
            <p>Tạm tính:</p>
            <p>
              {" "}
              {total_before_discount > 0
                ? formatNumber(total_before_discount)
                : 0}
            </p>
          </div>
          <div className="flex justify-between bg-[#fff]">
            <p>Giảm giá sản phẩm:</p>
            <p>
              {" "}
              -{" "}
              {product_discount_amount > 0
                ? formatNumber(product_discount_amount)
                : 0}
            </p>
          </div>
        </div>
        <div className="flex justify-between px-3 py-1 bg-white">
          <p>Tổng tiền hàng:</p>
          <p> {formatNumber(total_after_discount)}</p>
        </div>
        <div className="flex justify-between px-3 py-1 bg-white">
          <p>Tổng tiền vận chuyển:</p>
          <p>+ {formatNumber(total_shipping_fee)}</p>
        </div>
        <div className="flex justify-between px-3 py-1 bg-white">
          <p>Tổng tiền thanh toán:</p>
          <p> {total_final > 0 ? formatNumber(total_final) : 0} </p>
        </div>

        <div className="px-2 py-3 bg-gray-100 my-4 text-[14px] gap-1 ">
          <div className="flex items-center bg-[#fff] p-2 gap-x-2">
            <div className="p-1 rounded-full bg-gray-100">
              <IconDocument
                className={"w-4 h-4"}
                style={{
                  color: appTheme.color_main_1,
                }}
              />
            </div>
            <p className="text-sm">
              Nhấn 'Đặt hàng' đồng nghĩa với việc bạn đồng ý tuân theo Điều
              khoản Ikitech
            </p>
          </div>
        </div>

        <div className="bg-[#fff] fixed bottom-0 w-full flex justify-end gap-4 items-center pr-2 h-[60px] border-t-[1px] border-[#e4e4e4] ">
          <div className="text-end">
            Tổng thanh toán
            <p className="text-red-600 font-semibold">
              {total_final ? formatNumber(total_final) : 0} đ
            </p>
          </div>
          {loadingOrder ? (
            <ButtonAnt
              className="px-4 py-5 text-[#fff] flex items-center justify-center"
              type="primary"
              style={{
                backgroundColor: appTheme.color_main_1,
              }}
              loading
            >
              <span className="font-semibold">Đặt hàng</span>
            </ButtonAnt>
          ) : (
            <ButtonAnt
              className="px-4 py-5 text-[#fff] flex items-center justify-center"
              type="primary"
              style={{
                backgroundColor: appTheme.color_main_1,
              }}
              onClick={handleOrder}
            >
              <span className="font-semibold">Đặt hàng</span>
            </ButtonAnt>
          )}
        </div>
      </main>
      {isShowShipmentModal ? (
        <ShipmentFee
          isShowShipmentModal={isShowShipmentModal}
          setIsShowShipmentModal={setIsShowShipmentModal}
        ></ShipmentFee>
      ) : null}

      {isShowPaymentModal ? (
        <PaymentMethod
          isShowPaymentModal={isShowPaymentModal}
          setIsShowPaymentModal={setIsShowPaymentModal}
        ></PaymentMethod>
      ) : null}
      {isShowOrderSuccess ? (
        <OrderSuccess isShowOrderSuccess={isShowOrderSuccess}></OrderSuccess>
      ) : null}
    </div>
  );
};
export default ConfirmOrder;
