/* eslint-disable @typescript-eslint/no-explicit-any */

import { Button, Form, Input, message } from "antd";
import DatePickerBottomSheet from "components/CustomBottomSheet/DatePickerBottomSheet";
import LoginManIcon from "components/Icons/LoginManIcon";
import ProText from "components/ProText";
import ProTitle from "components/ProTitle";
import { useState } from "react";
import { useTranslation } from "react-i18next";
import PhoneInput from "react-phone-input-2";
import "react-phone-input-2/lib/style.css";
import { useNavigate, useParams } from "react-router-dom";
import { useSendOtpMutation } from "redux/api/auth";
import { useAppSelector } from "redux/hooks";
import { colors, DisabledColor, ProBlack1 } from "ThemeConstants";
import styles from "./login.module.css";

export default function LoginPage() {
  const { t } = useTranslation();
  const { isRTL } = useAppSelector((state) => state.locale);
  const { themeName } = useAppSelector((state) => state.theme);
  const [form] = Form.useForm();
  const [sendOtp, { isLoading }] = useSendOtpMutation();
  const { id } = useParams();

  const [phone, setPhone] = useState<string>("");
  const [selectedDate, setSelectedDate] = useState<string>("");
  const [isOpen, setIsOpen] = useState(false);
  const navigate = useNavigate();

  const handleLogin = async () => {
    localStorage.setItem("userPhone", form.getFieldValue("phone"));
    if (form.getFieldsValue())
      sendOtp(form.getFieldsValue()).then((response: any) => {
        message.info(t("login.OTPSentToYourPhoneNumber"));
        navigate(`/${id}/otp`);
        localStorage.setItem("otp", response.data.result.otp);
      });
  };

  return (
    <div
      style={{
        padding: 24,
        display: "flex",
        flexDirection: "column",
        justifyContent: "center",
        height: "100vh",
      }}
      className={styles.loginPage}
    >
      <ProTitle
        level={5}
        style={{ textAlign: "center", margin: "20px 0 10% 0", fontSize: 18 }}
      >
        {t("login.singup/Login")}
      </ProTitle>

      <div
        style={{
          position: "relative",
          marginBottom: 20,
          [isRTL ? "right" : "left"]: "50%",
          width: "fit-content",
          transform: isRTL ? "translateX(50%)" : "translateX(-50%)",
        }}
      >
        <LoginManIcon />
      </div>

      <ProTitle level={5}>{t("login.EnterYourNumber")} 👋</ProTitle>
      <ProText style={{ fontSize: 12, color: "#3E3E3E" }}>
        {t("login.WeWillSendYouAWhatsAppMessageWithAOneTimeVerificationCode")}
      </ProText>

      <Form
        layout="vertical"
        style={{ marginTop: 20 }}
        name="loginForm"
        form={form}
      >
        <Form.Item
          label={t("login.name")}
          name="name"
          rules={[{ required: true, message: "" }]}
        >
          <Input
            placeholder={t("login.EnterYourName")}
            size="large"
            style={{
              height: 50,
              fontSize: 14,
            }}
          />
        </Form.Item>

        <Form.Item label={t("login.date")} name="date" required>
          <Input
            placeholder={t("login.DateOfBirth")}
            size="large"
            onClick={() => setIsOpen(true)}
            readOnly
            value={selectedDate}
            style={{
              cursor: "pointer",
              height: 50,
              fontSize: 14,
            }}
          />
        </Form.Item>

        <Form.Item
          name="phone"
          label={t("login.phone")}
          rules={[
            { required: true, message: "" },
            { type: "number", message: "" },
          ]}
        >
          <div className={styles.proPhoneNumber}>
            <PhoneInput
              country={"om"}
              inputStyle={{
                borderRadius: 1000,
                height: 50,
                width: "100%",
                color: themeName === "light" ? "#000" : "#FFF",
                backgroundColor: themeName === "light" ? "#FFF" : ProBlack1,
                textAlign: isRTL ? "right" : "left",
                direction: isRTL ? "rtl" : "ltr",
                paddingLeft: "50px",
                paddingRight: "50px",
                borderColor: themeName === "light" ? "#d9d9d9" : "#363636",
              }}
              placeholder={t("login.mobileNumber")}
              value={phone}
              buttonStyle={{
                backgroundColor: "transparent",
                border: 0,
                borderLeft: "1px solid #363636",
                borderRadius: 0,
                position: "relative",
                ...(isRTL && {
                  top: -25,
                  right: 25,
                }),
                ...(!isRTL && {
                  top: -25,
                }),
              }}
              onBlur={(e) => setPhone(e.target.value)}
              autocompleteSearch
              inputProps={{
                id: "phone-number", // Required for accessibility & autofill
                name: "phone-number",
                required: true,
                autoFocus: false,
                autoComplete: "tel",
                type: "tel",
                inputMode: "numeric",
                pattern: "[0-9]*",
              }}
            />
          </div>
        </Form.Item>

        <Form.Item label={null}>
          <Button
            onClick={handleLogin}
            type="primary"
            size="large"
            loading={isLoading}
            style={{
              width: "100%",
              borderRadius: 1000,
              backgroundColor:
                phone.length <= 3 || isLoading
                  ? themeName === "light"
                    ? "rgba(233, 233, 233, 1)"
                    : DisabledColor
                  : colors.primary,
              color: "#FFF",
              height: 50,
              border: "none",
              marginTop: "2rem",
            }}
            disabled={phone.length <= 3 || isLoading}
            htmlType="submit"
          >
            {t("login.sendCode")}
          </Button>
        </Form.Item>
      </Form>

      <DatePickerBottomSheet
        isOpen={isOpen}
        onClose={() => setIsOpen(false)}
        onDateSelect={(date) => {
          const formattedDate = `${date.month}/${date.day}/${date.year}`;
          setSelectedDate(formattedDate);
          form.setFieldValue("date", formattedDate);
        }}
        initialDate={new Date()}
      />
    </div>
  );
}
