import { auth } from "@renderer/util/firebase";
import type { FormProps } from "antd";
import { Alert, Button, Card, Form, Input, Typography } from "antd";
import log from "electron-log/renderer";
import { signInWithEmailAndPassword } from "firebase/auth";
import { useState } from "react";
import { useTranslation } from "react-i18next";
import errorTypeCheck from "../../../../util/errorTypeCheck";
import ipcTypes from "../../../../util/ipcTypes.json";

const { Title } = Typography;

type FieldType = {
  username: string;
  password: string;
  remember?: string;
};

const SignInForm: React.FC = () => {
  const [error, setError] = useState<string | null>(null);
  const [loading, setLoading] = useState<boolean>(false);
  const { t } = useTranslation();
  const onFinish: FormProps<FieldType>["onFinish"] = async (values) => {
    const { username, password } = values;
    setLoading(true);
    try {
      const result = await signInWithEmailAndPassword(auth, username, password);
      log.debug("Login result", result);
    } catch (error) {
      log.error("Login error", errorTypeCheck(error));
      setError(t("auth.login.error"));
    } finally {
      setLoading(false);
    }
  };

  const onFinishFailed: FormProps<FieldType>["onFinishFailed"] = (
    errorInfo,
  ) => {
    log.log("Failed:", errorInfo);
  };

  return (
    <Card
      style={{
        maxWidth: 600,
        margin: "auto auto",
        borderRadius: 8,
        paddingLeft: 48,
        paddingRight: 48,
        boxShadow: "0 4px 12px rgba(0, 0, 0, 0.15)",
      }}
    >
      <div style={{ textAlign: "center", marginBottom: 24 }}>
        <Title level={2}>
          {import.meta.env.VITE_COMPANY === "IMEX"
            ? t("title.imex")
            : t("title.rome")}
        </Title>
      </div>

      <Form
        name="desktop-sign-in"
        layout="vertical"
        onFinish={onFinish}
        onFinishFailed={onFinishFailed}
        autoComplete="off"
        requiredMark={false}
      >
        {error && (
          <Form.Item>
            <Alert
              message={error}
              type="error"
              showIcon
              style={{ marginBottom: 16 }}
            />
          </Form.Item>
        )}

        <Form.Item<FieldType>
          label="Username"
          name="username"
          rules={[
            {
              required: true,
              message: t(
                "auth.login.usernameRequired",
                "Please enter your username",
              ),
            },
          ]}
        >
          <Input size="large" />
        </Form.Item>

        <Form.Item<FieldType>
          label="Password"
          name="password"
          rules={[
            {
              required: true,
              message: t(
                "auth.login.passwordRequired",
                "Please enter your password",
              ),
            },
          ]}
        >
          <Input.Password size="large" />
        </Form.Item>

        <Form.Item>
          <Button
            type="primary"
            loading={loading}
            htmlType="submit"
            size="large"
            block
          >
            {t("auth.login.login")}
          </Button>
        </Form.Item>

        <Form.Item style={{ marginBottom: 0, textAlign: "center" }}>
          <Button
            type="link"
            onClick={(): void => {
              window.electron.ipcRenderer.send(
                ipcTypes.toMain.user.resetPassword,
              );
            }}
          >
            {t("auth.login.resetpassword")}
          </Button>
        </Form.Item>
      </Form>
    </Card>
  );
};

export default SignInForm;
