import {
    Button,
    Checkbox,
    Col,
    Flex,
    Form,
    Grid,
    Input,
    message,
    Row,
    Typography,
} from "antd";
import { useNavigate } from "react-router-dom";

import { LogoutOutlined } from "@ant-design/icons";
import BackIcon from "components/Icons/BackIcon";
import NextIcon from "components/Icons/NextIcon";
import { loginSuccess } from "features/auth/authSlice";
import { useTranslation } from "react-i18next";
import { useCreateLoginMutation } from "redux/api/auth";
import { useAppDispatch, useAppSelector } from "redux/hooks";
import { PATH_AUTH, PATHS } from "utils/constants";
import { ResponseType } from "utils/types/appTypes";
import "./styles.css";

const { Title, Text, Link } = Typography;

type FieldType = {
  username?: string;
  password?: string;
  remember?: boolean;
};
const { useBreakpoint } = Grid;

export const SignInPage = () => {
  const { t } = useTranslation("login");
  const dispatch = useAppDispatch();
  const navigate = useNavigate();
  const { xs } = useBreakpoint();
  const [createLogin, { isLoading }] = useCreateLoginMutation({
    fixedCacheKey: "shared-update-post",
  });

  const onFinish = async (values: any) => {
    createLogin({ password: values.password, username: values.username })
      .unwrap()
      .then((response: any) => {
        dispatch(loginSuccess(response));
        message.open({
          type: "success",
          content: t("msg-login-success"),
        });
        navigate(PATHS.menu);
      })
      .catch((response: ResponseType) => {
        message.open({
          type: "error",
          content: response.data.message,
        });
      });
  };
  const { locale } = useAppSelector((state) => state.locale);

  return (
    <Row style={{ minHeight: "100vh", overflow: "hidden" }}>
      {!xs && (
        <>
          <Col xs={24} lg={13}>
            <Flex
              vertical
              align="center"
              justify="center"
              className="text-center"
              style={{
                backgroundImage: "linear-gradient(#01304A, #005488)",
                height: "100%",
                padding: "1rem",
                zIndex: 4,
              }}
            >
              {locale === "en" ? (
                <NextIcon className="ltr-signin-ellipse" />
              ) : (
                <BackIcon className="rtl-signin-ellipse" />
              )}
            </Flex>
          </Col>
        </>
      )}
      <Col xs={24} lg={11}>
        <Flex
          vertical
          align={xs ? "center" : "center"}
          justify="center"
          gap="middle"
          style={{ height: xs ? "90%" : "100%", padding: "2rem" }}
        >
          {!xs && (
            <LogoutOutlined
              color="white"
              style={{ position: "absolute", top: 20, left: 20 }}
            />
          )}
          {xs && <LogoutOutlined color="white" />}{" "}
          <Title className="m-0">{t("login")}</Title>
          <Flex gap={4}>
            {/* // أهلا بعودتك ! من فضلك قم بتسجيل الدخول لحسابك */}
            <Text>{t("msg-welcome")}</Text>
          </Flex>
          <Form
            name="sign-up-form"
            layout="vertical"
            labelCol={{ span: 24 }}
            wrapperCol={{ span: 24 }}
            initialValues={{
              username: "admin",
              password: "123",
              remember: true,
            }}
            onFinish={onFinish}
            autoComplete="off"
            requiredMark={false}
          >
            <Row gutter={[8, 0]}>
              <Col xs={24}>
                <Form.Item<FieldType>
                  label={t("user name")}
                  name="username"
                  rules={[
                    {
                      required: true,
                      message: t("msg-add-var-err", { var: t("user name") }),
                    },
                  ]}
                >
                  <Input />
                </Form.Item>
              </Col>
              <Col xs={24}>
                <Form.Item<FieldType>
                  label={t("password")}
                  name="password"
                  rules={[
                    {
                      required: true,
                      message: t("msg-add-var-err", { var: t("password") }),
                    },
                  ]}
                >
                  <Input.Password />
                </Form.Item>
              </Col>
              <Col xs={24}>
                <Form.Item<FieldType> name="remember" valuePropName="checked">
                  <Checkbox>{t("remember me")}</Checkbox>
                </Form.Item>
              </Col>
            </Row>
            <Form.Item>
              <Flex align="center" justify="space-between">
                <Button
                  type="primary"
                  htmlType="submit"
                  size="middle"
                  loading={isLoading}
                >
                  {t("login")}
                </Button>
                <Link href={PATH_AUTH.passwordReset}>
                  {t("forget password")}?
                </Link>
              </Flex>
            </Form.Item>
          </Form>
          <Title
            style={{
              position: "absolute",
              bottom: 20,
              left: 20,
              color: "#8A8A8C",
              fontSize: 20,
            }}
          >
            {t("app version")} : 2.0.0
          </Title>
        </Flex>
      </Col>
    </Row>
  );
};
