import { LockOutlined, UserOutlined } from "@ant-design/icons";
import { t, Trans } from "@lingui/macro";
import { useLingui } from "@lingui/react";
import {
  Button,
  Col,
  Form,
  FormProps,
  Input,
  notification,
  Row,
  Typography,
} from "antd";
import { AxiosError } from "axios";
import { useEffect, useState } from "react";
import styled from "styled-components";
import { LanguageSelect } from "../../components/language-select";
import { TOKEN_KEY } from "../../consts";
import "./style.css";

export const DIVERGE_FORM_ICON_COLOR = "rgba(0, 0, 0, 0.25)";

export function getErrorMessage(error: any) {
  if (error instanceof AxiosError) {
    return error.response?.data?.message;
  }

  return "";
}

export interface LogInPayload {
  username: string;
  password: string;
}

const StyledLoginContainer = styled.div`
  width: 100%;
  height: 100%;
  background-image: url(/login_bg.svg);
  background-position: center;
  background-repeat: no-repeat;
  background-size: cover;
  display: flex;
  justify-content: center;
  align-items: center;
  position: relative;
`;

const StyledFormContainer = styled(Form)`
  .login-form__title {
    color: white;
    text-align: justify;
    font-size: 52px;
    margin-bottom: 0;
  }

  .login-form__subtitle {
    color: #84b1e3;
    text-align: right;
    font-weight: 300;
    margin-top: 0 !important;
  }

  .login-form__form-title {
    color: white;
    text-align: right;
    font-weight: 400;
    margin-top: 0.8em !important;
  }

  .ant-form-item-control-input .ant-input-affix-wrapper {
    border: none;
  }

  .login-form__helper-text {
    font-size: 18px;
    color: #83afdf;
  }

  .login-form__submit-button {
    display: block;
    width: 100%;
  }

  a {
    color: white;
    text-decoration: underline;
  }
`;

export default function LoginPage() {
  const { i18n } = useLingui();
  const [isAuthenticating, setIsAuthenticating] = useState(false);

  useEffect(() => {
    const token = localStorage.getItem(TOKEN_KEY);
    if (token) {
      window.location.href = "/";
    }
  }, []);

  const handleLogin: FormProps<LogInPayload>["onFinish"] = async (payload) => {
    setIsAuthenticating(true);
    try {
      const resp = await fetch("/api/ctel/login/", {
        headers: {
          Accept: "application/json",
          "Content-Type": "application/json",
        },
        method: "POST",
        body: JSON.stringify(payload),
      });
      const message = await resp.json();
      if (!resp.ok) {
        throw new Error(message?.detail);
      }
      let token = message?.token || "";
      token = token.trim();
      localStorage.setItem(TOKEN_KEY, JSON.stringify(token));
      notification.success({
        message: t(i18n)`User log in successfully`,
      });
      setTimeout(() => {
        window.location.href = "/";
      }, 1000);
    } catch (error) {
      setIsAuthenticating(false);
      notification.error({
        message: t(i18n)`Could not login with provided username and password!`,
      });
    }
  };

  return (
    <StyledLoginContainer>
      <StyledFormContainer className="login-form" onFinish={handleLogin as any}>
        <Typography.Title level={1} className="login-form__title">
          OCR APIs
        </Typography.Title>
        <Typography.Title level={3} className="login-form__subtitle">
          <Trans>Intelligent Document Processing Solutions</Trans>
        </Typography.Title>
        <Typography.Title level={2} className="login-form__form-title">
          <Trans>Login</Trans>
        </Typography.Title>

        <Form.Item
          name="username"
          rules={[
            {
              required: true,
              message: t(i18n)`Please specify a username`,
              whitespace: true,
            },
          ]}
        >
          <Input
            autoComplete="username"
            prefix={<UserOutlined style={{ color: DIVERGE_FORM_ICON_COLOR }} />}
            placeholder={t(i18n)`Username`}
            size="large"
          />
        </Form.Item>

        <Form.Item
          name="password"
          rules={[
            {
              required: true,
              message: t(i18n)`Please specify a password`,
              whitespace: true,
            },
          ]}
        >
          <Input.Password
            autoComplete="current-password"
            prefix={<LockOutlined style={{ color: DIVERGE_FORM_ICON_COLOR }} />}
            placeholder={t(i18n)`Password`}
            size="large"
          />
        </Form.Item>

        <Form.Item>
          <Button
            type="primary"
            htmlType="submit"
            className="login-form__submit-button"
            size="large"
            loading={isAuthenticating}
          >
            {t(i18n)`Login`}
          </Button>
        </Form.Item>
      </StyledFormContainer>
    </StyledLoginContainer>
  );
}
