import { Button, Space, message } from "antd";
import OtpIcon from "components/Icons/otpIcon.tsx";
import OtpInput from "components/OtpInput/OtpInput";
import ProText from "components/ProText";
import ProTitle from "components/ProTitle";
import { loginSuccess } from "features/auth/authSlice";
import { useState } from "react";
import { useTranslation } from "react-i18next";
import { useNavigate, useParams } from "react-router-dom";
import { useConfirmOtpMutation, useSendOtpMutation } from "redux/api/auth";
import { useAppDispatch } from "redux/hooks";
import { ProGray1 } from "ThemeConstants";

export default function OtpPage() {
  const { subdomain } = useParams();
  const dispatch = useAppDispatch();
  const { t } = useTranslation();
  const [sendOtp, { isLoading }] = useSendOtpMutation();
  const [confirmOtp, { isLoading: isConfirmLoading }] = useConfirmOtpMutation();
  const [otp, setOtp] = useState<string>("");
  const handleOtpSave = (otp: string) => {
    try {
      setOtp(otp);
    } catch (error) {
      console.error("Failed to parse otp:", error);
    }
  };
  const navigate = useNavigate();

  return (
    <>
      <div
        style={{
          display: "flex",
          flexDirection: "column",
          justifyContent: "center",
          alignItems: "center",
          textAlign: "center",
          padding: 16,
          gap: 24,
          height: "92vh",
        }}
      >
        <OtpIcon />

        <div>
          <ProTitle level={4}>{t("otp.verification")}</ProTitle>
          <ProText style={{ color: ProGray1 }}>
            {t("otp.enterThe4DigitCodeThatSentToYourPhoneNumber")}
          </ProText>
          <br />
          <ProText style={{ color: ProGray1 }}>
            {localStorage.getItem("otp")}
          </ProText>
        </div>
        <div>
          <Space size="small">
            <OtpInput
              length={5}
              onComplete={handleOtpSave}
              resendOtp={() =>
                sendOtp({
                  phone: localStorage.getItem("userPhone") || "",
                })
              }
              isLoading={isLoading || isConfirmLoading}
            />
          </Space>
        </div>
        <Button
          type="primary"
          shape="round"
          style={{
            width: "100%",
            height: 48,
            marginBottom: 16,
            color: "white",
            border: "none",
            boxShadow: "none",
          }}
          disabled={!otp || otp.length < 5 || isConfirmLoading}
          onClick={() => {
            confirmOtp({ otp: otp, phone: localStorage.getItem("userPhone") })
              .unwrap()
              .then((response) => {
                dispatch(loginSuccess(response));
                message.info(t("otp.confirmOTPSuccess"));
                navigate(`/${subdomain}/menu`);
              });
          }}
        >
          {t("otp.continue")}
        </Button>
      </div>
    </>
  );
}
