import Button from "@/components/Low/Button";
import Input from "@/components/Low/Input";
import useUsers from "@/hooks/useUsers";
import { User } from "@/interfaces/user";
import { sendEmailVerification } from "@/utils/email";
import axios from "axios";
import { Divider } from "primereact/divider";
import { useState } from "react";
import { toast } from "react-toastify";
import { KeyedMutator } from "swr";
import Select from "react-select";
import moment from "moment";
import useAcceptedTerms from "@/hooks/useAcceptedTerms";

interface Props {
  isLoading: boolean;
  setIsLoading: (isLoading: boolean) => void;
  mutateUser: KeyedMutator<User>;
  sendEmailVerification: typeof sendEmailVerification;
}

const availableDurations = {
  "1_month": { label: "1 Month", number: 1 },
  "3_months": { label: "3 Months", number: 3 },
  "6_months": { label: "6 Months", number: 6 },
  "12_months": { label: "12 Months", number: 12 },
};

export default function RegisterCorporate({
  isLoading,
  setIsLoading,
  mutateUser,
  sendEmailVerification,
}: Props) {
  const [name, setName] = useState("");
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [confirmPassword, setConfirmPassword] = useState("");
  const [referralAgent, setReferralAgent] = useState<string | undefined>();

  const [companyName, setCompanyName] = useState("");
  const [companyUsers, setCompanyUsers] = useState(0);
  const [subscriptionDuration, setSubscriptionDuration] = useState(1);
  const {acceptedTerms, renderCheckbox} = useAcceptedTerms();

  const { users } = useUsers();

  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: "corporate",
        profilePicture: "/defaultAvatar.png",
        subscriptionExpirationDate: moment().subtract(1, "days").toISOString(),
        corporateInformation: {
          companyInformation: {
            name: companyName,
            userAmount: companyUsers,
          },
          monthlyDuration: subscriptionDuration,
          referralAgent,
        },
      })
      .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-4"
      onSubmit={register}
    >
      <div className="flex w-full gap-4">
        <Input
          type="text"
          name="name"
          onChange={(e) => setName(e)}
          placeholder="Enter your name"
          defaultValue={name}
          required
        />
        <Input
          type="email"
          name="email"
          onChange={(e) => setEmail(e.toLowerCase())}
          placeholder="Enter email address"
          defaultValue={email}
          required
        />
      </div>

      <div className="flex w-full gap-4">
        <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>

      <Divider className="!my-2 w-full" />

      <div className="flex w-full gap-4">
        <Input
          type="text"
          name="companyName"
          onChange={(e) => setCompanyName(e)}
          placeholder="Corporate name"
          label="Corporate name"
          defaultValue={companyName}
          required
        />
        <Input
          type="number"
          name="companyUsers"
          onChange={(e) => setCompanyUsers(parseInt(e))}
          label="Number of users"
          defaultValue={companyUsers}
          required
        />
      </div>

      <div className="flex w-full gap-4">
        <div className="flex w-full flex-col gap-3">
          <label className="text-mti-gray-dim text-base font-normal">
            Referral *
          </label>
          <Select
            className="placeholder:text-mti-gray-cool disabled:bg-mti-gray-platinum/40 disabled:text-mti-gray-dim border-mti-gray-platinum w-full rounded-full border bg-white px-4 py-4 text-sm font-normal focus:outline-none disabled:cursor-not-allowed"
            options={[
              { value: "", label: "No referral" },
              ...users
                .filter((u) => u.type === "agent")
                .map((x) => ({ value: x.id, label: `${x.name} - ${x.email}` })),
            ]}
            defaultValue={{ value: "", label: "No referral" }}
            onChange={(value) => setReferralAgent(value?.value)}
            styles={{
              control: (styles) => ({
                ...styles,
                paddingLeft: "4px",
                border: "none",
                outline: "none",
                ":focus": {
                  outline: "none",
                },
              }),
              option: (styles, state) => ({
                ...styles,
                backgroundColor: state.isFocused
                  ? "#D5D9F0"
                  : state.isSelected
                    ? "#7872BF"
                    : "white",
                color: state.isFocused ? "black" : styles.color,
              }),
            }}
          />
        </div>

        <div className="flex w-full flex-col gap-3">
          <label className="text-mti-gray-dim text-base font-normal">
            Subscription Duration *
          </label>
          <Select
            className="placeholder:text-mti-gray-cool disabled:bg-mti-gray-platinum/40 disabled:text-mti-gray-dim border-mti-gray-platinum w-full rounded-full border bg-white px-4 py-4 text-sm font-normal focus:outline-none disabled:cursor-not-allowed"
            options={Object.keys(availableDurations).map((value) => ({
              value,
              label:
                availableDurations[value as keyof typeof availableDurations]
                  .label,
            }))}
            defaultValue={{
              value: "1_month",
              label: availableDurations["1_month"].label,
            }}
            onChange={(value) =>
              setSubscriptionDuration(
                value
                  ? availableDurations[
                      value.value as keyof typeof availableDurations
                    ].number
                  : 1,
              )
            }
            styles={{
              control: (styles) => ({
                ...styles,
                paddingLeft: "4px",
                border: "none",
                outline: "none",
                ":focus": {
                  outline: "none",
                },
              }),
              option: (styles, state) => ({
                ...styles,
                backgroundColor: state.isFocused
                  ? "#D5D9F0"
                  : state.isSelected
                    ? "#7872BF"
                    : "white",
                color: state.isFocused ? "black" : styles.color,
              }),
            }}
          />
        </div>
      </div>
      <div className="flex w-full flex-col items-start gap-4">
            {renderCheckbox()}
      </div>
      <Button
        className="w-full lg:mt-8"
        color="purple"
        disabled={
          isLoading ||
          !email ||
          !name ||
          !password ||
          !confirmPassword ||
          password !== confirmPassword ||
          !companyName ||
          companyUsers <= 0
        }
      >
        Create account
      </Button>
    </form>
  );
}
