"use client";

import { FormEvent, useState } from "react";
import {
  Input,
  Modal,
  ModalBody,
  ModalContent,
  ModalFooter,
  ModalHeader,
  Radio,
  RadioGroup,
} from "@nextui-org/react";
import toast from "react-hot-toast";

import Button from "@/components/common/button";
import { useClientPortalAuth } from "@/components/pages/client/participant-list/common/client-portal-auth-context";
import { submitContactRequestFromPortal } from "@/services/client/participant-list/portal-actions";

type AddClientContactModalProps = {
  isOpen: boolean;
  onClose: () => void;
};

const emptyForm = {
  firstName: "",
  lastName: "",
  email: "",
  phone: "",
  jobTitle: "",
  clientPortalAccessLevel: "0",
};

function AddClientContactModal({
  isOpen,
  onClose,
}: AddClientContactModalProps) {
  const { auth, handlePortalStatus } = useClientPortalAuth();
  const [form, setForm] = useState(emptyForm);
  const [emailFeedback, setEmailFeedback] = useState<string | null>(null);
  const [isSubmitting, setIsSubmitting] = useState(false);

  const close = () => {
    if (isSubmitting) return;
    setForm(emptyForm);
    setEmailFeedback(null);
    onClose();
  };

  const submit = async (event: FormEvent<HTMLFormElement>) => {
    event.preventDefault();
    if (!auth || isSubmitting) return;
    const values = Object.fromEntries(
      Object.entries(form).map(([key, value]) => [key, value.trim()]),
    ) as typeof form;
    if (Object.values(values).some((value) => !value)) {
      toast.error("Please complete every contact field.");
      return;
    }
    if (!/^\S+@\S+\.\S+$/.test(values.email)) {
      toast.error("Enter a valid email address.");
      return;
    }

    setEmailFeedback(null);
    setIsSubmitting(true);
    try {
      const result = await submitContactRequestFromPortal(auth, {
        ...values,
        clientPortalAccessLevel: values.clientPortalAccessLevel === "1" ? 1 : 0,
      });
      if (result.ok) {
        toast.success("Contact request sent for approval.");
        setForm(emptyForm);
        setEmailFeedback(null);
        onClose();
      } else if (
        result.status === 409 &&
        result.reason === "contact_already_assigned"
      ) {
        setEmailFeedback("This email is already connected to this project.");
      } else if (
        result.status === 409 &&
        result.reason === "contact_request_pending"
      ) {
        setEmailFeedback(
          "A request for this email is already awaiting review.",
        );
      } else if (!handlePortalStatus(result.status)) {
        if (result.status === 400) {
          toast.error(
            "Some contact details are invalid or too long. Please check them and try again.",
          );
        } else if (result.status === 0) {
          toast.error(
            "We couldn't connect. Check your internet connection and try again.",
          );
        } else if (result.status >= 500) {
          toast.error(
            "We couldn't submit the request right now. Please try again later.",
          );
        } else {
          toast.error(
            "We couldn't submit the contact request. Please try again.",
          );
        }
      }
    } catch {
      toast.error("Couldn't send this request. Please try again.");
    } finally {
      setIsSubmitting(false);
    }
  };

  return (
    <Modal isOpen={isOpen} placement="center" onClose={close}>
      <ModalContent>
        <form onSubmit={submit}>
          <ModalHeader className="flex flex-col gap-1">
            Request client contact
          </ModalHeader>
          <ModalBody>
            <p className="text-sm text-default-500">
              PFR will review and approve this contact before they can access
              the project.
            </p>
            <div className="grid grid-cols-1 gap-3 sm:grid-cols-2">
              <Input
                isRequired
                label="First name"
                maxLength={100}
                value={form.firstName}
                onValueChange={(firstName) =>
                  setForm((current) => ({ ...current, firstName }))
                }
              />
              <Input
                isRequired
                label="Last name"
                maxLength={100}
                value={form.lastName}
                onValueChange={(lastName) =>
                  setForm((current) => ({ ...current, lastName }))
                }
              />
            </div>
            <Input
              isRequired
              errorMessage={emailFeedback ?? undefined}
              isInvalid={Boolean(emailFeedback)}
              label="Email"
              maxLength={254}
              type="email"
              value={form.email}
              onValueChange={(email) => {
                setEmailFeedback(null);
                setForm((current) => ({ ...current, email }));
              }}
            />
            <Input
              isRequired
              label="Phone"
              maxLength={50}
              type="tel"
              value={form.phone}
              onValueChange={(phone) =>
                setForm((current) => ({ ...current, phone }))
              }
            />
            <Input
              isRequired
              label="Job title"
              maxLength={150}
              value={form.jobTitle}
              onValueChange={(jobTitle) =>
                setForm((current) => ({ ...current, jobTitle }))
              }
            />
            <RadioGroup
              label="Portal rights"
              value={form.clientPortalAccessLevel}
              onValueChange={(clientPortalAccessLevel) =>
                setForm((current) => ({ ...current, clientPortalAccessLevel }))
              }
            >
              <Radio value="0">Read only</Radio>
              <Radio value="1">Edit</Radio>
            </RadioGroup>
          </ModalBody>
          <ModalFooter>
            <Button
              btnLabel="Cancel"
              customVariant="transparent-black"
              isDisabled={isSubmitting}
              onClick={close}
            />
            <Button
              btnLabel="Send request"
              customVariant="client"
              isLoading={isSubmitting}
              type="submit"
            />
          </ModalFooter>
        </form>
      </ModalContent>
    </Modal>
  );
}

export default AddClientContactModal;
