import { auth } from "@renderer/util/firebase";
import type { FormProps } from "antd";
import { Alert, Button, Form, Input, Space } 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";

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 (
    <Form
      name="desktop-sign-in"
      labelCol={{ span: 8 }}
      wrapperCol={{ span: 16 }}
      style={{ maxWidth: 600 }}
      initialValues={{ remember: true }}
      onFinish={onFinish}
      onFinishFailed={onFinishFailed}
      autoComplete="off"
    >
      <Form.Item<FieldType>
        label="Username"
        name="username"
        rules={[{ required: true }]}
      >
        <Input />
      </Form.Item>
      <Form.Item<FieldType>
        label="Password"
        name="password"
        rules={[{ required: true }]}
      >
        <Input.Password />
      </Form.Item>
      <Form.Item label={null}>
        <Space>
          <Button type="primary" loading={loading} htmlType="submit">
            {t("auth.login.login")}
          </Button>
          <Button
            onClick={(): void => {
              window.electron.ipcRenderer.send(
                ipcTypes.toMain.user.resetPassword,
              );
            }}
          >
            {t("auth.login.resetpassword")}
          </Button>
        </Space>
      </Form.Item>
      {error && (
        <Form.Item label={null}>
          <Alert message={error} type="error" />
        </Form.Item>
      )}
      <Form.Item label={null}></Form.Item>
    </Form>
  );
};
export default SignInForm;
