import Button from "@/components/Low/Button";
import Checkbox from "@/components/Low/Checkbox";
import Input from "@/components/Low/Input";
import { User } from "@/interfaces/user";
import { sendEmailVerification } from "@/utils/email";
import axios from "axios";
import { useEffect, useState } from "react";
import { toast } from "react-toastify";
import { KeyedMutator } from "swr";

interface Props {
  queryCode?: string;
  defaultInformation?: {
    email: string;
    name: string;
    passport_id?: string;
  };
  isLoading: boolean;
  setIsLoading: (isLoading: boolean) => void;
  mutateUser: KeyedMutator<User>;
  sendEmailVerification: typeof sendEmailVerification;
}

export default function RegisterIndividual({
  queryCode,
  defaultInformation,
  isLoading,
  setIsLoading,
  mutateUser,
  sendEmailVerification,
}: Props) {
  const [name, setName] = useState(defaultInformation?.name || "");
  const [email, setEmail] = useState(defaultInformation?.email || "");
  const [password, setPassword] = useState("");
  const [confirmPassword, setConfirmPassword] = useState("");
  const [code, setCode] = useState(queryCode || "");
  const [hasCode, setHasCode] = useState<boolean>(!!queryCode);

  const onSuccess = () =>
    toast.success(
      "An e-mail has been sent, please make sure to check your spam folder!",
    );

  const onError = (e: Error) => {
    console.error(e);
    toast.error("Something went wrong, please logout and re-login.", {
      toastId: "send-verify-error",
    });
  };

  const register = (e: any) => {
    e.preventDefault();

    if (confirmPassword !== password) {
      toast.error("Your passwords do not match!", {
        toastId: "password-not-match",
      });
      return;
    }

    setIsLoading(true);
    axios
      .post("/api/register", {
        name,
        email,
        password,
        type: "individual",
        code,
        passport_id: defaultInformation?.passport_id,
        profilePicture: "/defaultAvatar.png",
      })
      .then((response) => {
        mutateUser(response.data.user).then(() =>
          sendEmailVerification(setIsLoading, onSuccess, onError),
        );
      })
      .catch((error) => {
        console.log(error.response.data);

        if (error.response.status === 401) {
          toast.error("There is already a user with that e-mail!");
          return;
        }

        if (error.response.status === 400) {
          toast.error("The provided code is invalid!");
          return;
        }

        toast.error("There was something wrong, please try again!");
      })
      .finally(() => setIsLoading(false));
  };

  return (
    <form
      className="flex w-full flex-col items-center gap-6"
      onSubmit={register}
    >
      <Input
        type="text"
        name="name"
        onChange={(e) => setName(e)}
        placeholder="Enter your name"
        value={name}
        required
      />
      <Input
        type="email"
        name="email"
        onChange={(e) => setEmail(e.toLowerCase())}
        placeholder="Enter email address"
        value={email}
        disabled={!!defaultInformation?.email}
        required
      />
      <Input
        type="password"
        name="password"
        onChange={(e) => setPassword(e)}
        placeholder="Enter your password"
        defaultValue={password}
        required
      />
      <Input
        type="password"
        name="confirmPassword"
        onChange={(e) => setConfirmPassword(e)}
        placeholder="Confirm your password"
        defaultValue={confirmPassword}
        required
      />

      <div className="flex w-full flex-col items-start gap-4">
        <Checkbox isChecked={hasCode} onChange={setHasCode}>
          I have a code
        </Checkbox>
        {hasCode && (
          <Input
            type="text"
            name="code"
            onChange={(e) => setCode(e)}
            placeholder="Enter your registration code (optional)"
            defaultValue={code}
            required
          />
        )}
      </div>

      <Button
        className="w-full lg:mt-8"
        color="purple"
        disabled={
          isLoading ||
          !email ||
          !name ||
          !password ||
          !confirmPassword ||
          password !== confirmPassword ||
          (hasCode ? !code : false)
        }
      >
        Create account
      </Button>
    </form>
  );
}
