import { Button, Layout, Space, message } from "antd";
import ImageWithFallback from "components/ImageWithFallback";
import OtpIcon from "components/Icons/otpIcon.tsx";
import OtpInput from "components/OtpInput/OtpInput";
import ProHeader from "components/ProHeader/ProHeader";
import ProText from "components/ProText";
import ProTitle from "components/ProTitle";
import { loginSuccess } from "features/auth/authSlice";
import useBreakPoint from "hooks/useBreakPoint";
import { useState } from "react";
import { useTranslation } from "react-i18next";
import { useNavigate, useParams } from "react-router-dom";
import { useConfirmOtpMutation, useSendOtpMutation } from "redux/api/auth";
import { useGetRestaurantDetailsQuery } from "redux/api/others";
import { useAppDispatch } from "redux/hooks";
import { ProGray1 } from "ThemeConstants";
import { default_image } from "utils/constants";
import styles from "./otp.module.css";

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 { isTablet } = useBreakPoint();
  const { data: restaurant } = useGetRestaurantDetailsQuery(subdomain, {
    skip: !subdomain,
  });
  const handleOtpSave = (otp: string) => {
    try {
      setOtp(otp);
    } catch (error) {
      console.error("Failed to parse otp:", error);
    }
  };
  const navigate = useNavigate();

  return (
    <Layout className={styles.otpPage}>
      {isTablet ? <ProHeader>{t("otp.verification")}</ProHeader> : null}

      <div className={styles.otpWrapper}>
        {/* Restaurant Cover Image - Desktop Only */}
        <div className={styles.restaurantCoverContainer}>
          <ImageWithFallback
            src={restaurant?.restaurant_cover}
            fallbackSrc={default_image}
            alt={t("otp.restaurantCover")}
            className={styles.restaurantCover}
            width="100%"
            height="100%"
            preview={false}
          />
        </div>

        {/* OTP Form Container */}
        <Layout.Content className={styles.otpContentWrapper}>
          <div className={styles.otpContainer}>
            <OtpIcon />

            <div className={styles.otpContent}>
              <ProTitle level={4} className={styles.otpTitle}>
                {t("otp.verification")}
              </ProTitle>
              <ProText style={{ color: ProGray1 }}>
                {t("otp.enterThe4DigitCodeThatSentToYourPhoneNumber")}
              </ProText>
              <br />
              <ProText style={{ color: ProGray1 }}>
                {localStorage.getItem("otp")}
              </ProText>
            </div>
            <div className={styles.otpInputContainer}>
              <Space size="small">
                <OtpInput
                  length={5}
                  onComplete={handleOtpSave}
                  resendOtp={() =>
                    sendOtp({
                      phone: localStorage.getItem("userPhone") || "",
                    })
                  }
                  isLoading={isLoading || isConfirmLoading}
                />
              </Space>
            </div>
            <Button
              type="primary"
              shape="round"
              className={styles.otpButton}
              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>
        </Layout.Content>
      </div>
    </Layout>
  );
}
