import { Form, Formik, Field } from "formik";
import FormGroup from "../components/FormGroup";
import type { NPEDErrorValues, NPEDFieldType } from "../../../types/types";
import { useNPEDAuth } from "../../../hooks/useNPEDAuth";
import { toast } from "sonner";
import { faEyeSlash, faEye } from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { useState } from "react";
import { useIntegrationsContext } from "../../../context/IntegrationsContext";

const NPEDFields = () => {
  const { state } = useIntegrationsContext();
  const [showPwd, setShowPwd] = useState(false);
  const { signIn, signOut } = useNPEDAuth();

  const username = state.npedUser?.propUsername?.value;
  const password = state.npedUser?.propPassword?.value;
  const clientId = state.npedUser?.propClientID?.value;
  const frontId = "NPED";
  const rearId = "NPED";

  const initialValues = {
    username: username ?? "",
    password: password ?? "",
    clientId: clientId ?? "",
    frontId: frontId,
    rearId: rearId,
  };

  const handleSubmit = async (values: NPEDFieldType) => {
    const valuesToSend = {
      ...values,
    };
    await signIn(valuesToSend);
  };

  const validateValues = (values: NPEDFieldType) => {
    const errors: NPEDErrorValues = {};
    if (!values.username) errors.username = "Required";
    if (!values.password) errors.password = "Required";
    if (!values.clientId) errors.clientId = "Required";
    return errors;
  };

  const handleLogoutClick = () => {
    signOut();
    toast.warning("logged out of NPED");
  };

  return (
    <Formik initialValues={initialValues} onSubmit={handleSubmit} validate={validateValues} enableReinitialize>
      {({ errors, touched, isSubmitting }) => (
        <Form className="flex flex-col space-y-5 px-2">
          <FormGroup>
            <label htmlFor="username">Username</label>
            {touched.username && errors.username && (
              <small className="absolute right-0 -top-5 text-red-500">{errors.username}</small>
            )}
            <Field
              name="username"
              type="text"
              id="username"
              placeholder="NPED username"
              className="p-1.5 border border-gray-400 rounded-lg"
            />
          </FormGroup>
          <FormGroup>
            <label htmlFor="password">Password</label>
            <div className="flex gap-2 items-center relative mb-4">
              <Field
                name="password"
                type={showPwd ? "text" : "password"}
                id="password"
                placeholder="NPED Password"
                className="p-2 border border-gray-400 rounded-lg w-full"
              />
              {touched.password && errors.password && (
                <small className="absolute right-0 -top-5 text-red-500">{errors.password}</small>
              )}
              <FontAwesomeIcon
                type="button"
                className="absolute right-5 end-0"
                onClick={() => setShowPwd((s) => !s)}
                icon={showPwd ? faEyeSlash : faEye}
              />
            </div>
          </FormGroup>
          <FormGroup>
            <label htmlFor="clientId">Client ID</label>
            {touched.clientId && errors.clientId && (
              <small className="absolute right-0 -top-5 text-red-500">{errors.clientId}</small>
            )}
            <Field
              name="clientId"
              type="text"
              id="clientId"
              placeholder="NPED client ID"
              className="p-1.5 border border-gray-400 rounded-lg"
            />
          </FormGroup>

          {!state.npedUser?.propClientID?.value ? (
            <button
              type="submit"
              className="w-full md:w-1/4 text-white bg-green-700 hover:bg-green-800 font-small rounded-lg text-sm px-2 py-2.5 hover:cursor-pointer"
            >
              {isSubmitting ? "Logging in..." : "Login"}
            </button>
          ) : (
            <button
              type="button"
              className="w-full md:w-1/4  border-red-700 bg-red-800 text-white font-small rounded-lg text-sm px-2 py-2.5 hover:cursor-pointer"
              onClick={handleLogoutClick}
            >
              Logout
            </button>
          )}
        </Form>
      )}
    </Formik>
  );
};

export default NPEDFields;
