import Select from 'react-select';
import { useEffect, useRef, useState } from 'react';
import { useQueryClient } from '@tanstack/react-query';
import { toast } from 'react-toastify';
import { useSimpleCodeListQuery } from '@api/codeAPI';
import { useAdminGroupCodeQuery } from '@api/adminGroupAPI';
import { AddAdminRequest, useAddAdminMutation } from '@api/adminAPI';
import { isEmpty } from '@utils/objectUtils';
import Button from '@components/ui/button/Button';

interface Props {
  onCloseModal: () => void;
}

const AUTH_CODE = '008';

const AdministratorAddModal = ({ onCloseModal }: Props) => {
  const [addAdminRequest, setAddAdminRequest] = useState<AddAdminRequest>({
    email: '',
    name: '',
    phone: '',
    grp: '',
    auth: ''
  });

  // Ref
  const nameRef = useRef<HTMLInputElement>(null);
  const contactRef = useRef<HTMLInputElement>(null);
  const emailRef = useRef<HTMLInputElement>(null);

  // API
  const queryClient = useQueryClient();
  const { data: authCodeList } = useSimpleCodeListQuery(AUTH_CODE);
  const { data: groupCodeList } = useAdminGroupCodeQuery();
  const { mutate: addAdmin, isPending: isPostingAdmin } = useAddAdminMutation();

  const groupCodeOptions =
    groupCodeList?.map((group) => ({
      label: group.groupName,
      value: group.groupCd
    })) ?? [];

  const authCodeOptions =
    authCodeList?.map((auth) => ({
      label: auth.codeName,
      value: auth.code
    })) ?? [];

  useEffect(() => {
    if (authCodeList && authCodeList.length > 0) {
      setAddAdminRequest((prevState) => ({ ...prevState, auth: authCodeList[0].code }));
    }
  }, [authCodeList]);

  useEffect(() => {
    if (groupCodeList && groupCodeList.length > 0) {
      setAddAdminRequest((prevState) => ({ ...prevState, grp: groupCodeList[0].groupCd }));
    }
  }, [groupCodeList]);

  // Func
  const handleConfirmClick = () => {
    if (addAdminRequest.name === '') {
      toast.error('Please enter your name.');
      nameRef.current?.focus();

      return;
    } else if (!/^[\d-]+$/.test(addAdminRequest.phone)) {
      toast.error('Please enter your contact.');
      contactRef.current?.focus();

      return;
    } else if (!/^[\w.-]+\w@[\w.-]+\w$/.test(addAdminRequest.email)) {
      toast.error('Please enter your email in the correct format.');
      emailRef.current?.focus();

      return;
    }

    addAdmin(addAdminRequest, {
      onSuccess: () => {
        toast.success('A new Admin has been created.');
        onCloseModal();
        queryClient.invalidateQueries({ queryKey: ['adminList'] });
        queryClient.invalidateQueries({ queryKey: ['adminInfo'] });
      }
    });
  };

  return (
    <>
      <div className="title">
        <span className="modal_title">Add Administrator</span>
      </div>
      <div className="body">
        <table className="table">
          <tbody>
            <tr>
              <th>Administrator</th>
              <td>Admin + Number (Auto Create)</td>
            </tr>
            <tr>
              <th>Person in charge</th>
              <td>
                <input
                  ref={nameRef}
                  type="text"
                  className="form_control"
                  onChange={(e) => setAddAdminRequest((prevState) => ({ ...prevState, name: e.target.value }))}
                  placeholder="Name"
                  disabled={isEmpty(addAdminRequest)}
                />
              </td>
            </tr>
            <tr>
              <th>Contact</th>
              <td>
                <input
                  ref={contactRef}
                  type="text"
                  className="form_control"
                  onChange={(e) => setAddAdminRequest((prevState) => ({ ...prevState, phone: e.target.value }))}
                  placeholder="000-0000-0000"
                  disabled={isEmpty(addAdminRequest)}
                />
              </td>
            </tr>
            <tr>
              <th>Email</th>
              <td>
                <input
                  ref={emailRef}
                  type="text"
                  className="form_control"
                  onChange={(e) => setAddAdminRequest((prevState) => ({ ...prevState, email: e.target.value }))}
                  placeholder="AngkorLife@email.com"
                  disabled={isEmpty(addAdminRequest)}
                />
              </td>
            </tr>
            <tr>
              <th>Group</th>
              <td>
                <Select
                  menuPortalTarget={document.getElementsByClassName('modal_wrapper')[0] as HTMLElement}
                  options={groupCodeOptions}
                  value={groupCodeOptions.find((item) => item.value === addAdminRequest.grp)}
                  onChange={(newValue) =>
                    setAddAdminRequest((prevState) => ({ ...prevState, grp: newValue?.value ?? '' }))
                  }
                  isDisabled={isEmpty(addAdminRequest)}
                />
              </td>
            </tr>
            <tr>
              <th>Permission</th>
              <td>
                <Select
                  menuPortalTarget={document.getElementsByClassName('modal_wrapper')[0] as HTMLElement}
                  options={authCodeOptions}
                  value={authCodeOptions.find((item) => item.value === addAdminRequest.auth)}
                  onChange={(newValue) =>
                    setAddAdminRequest((prevState) => ({ ...prevState, auth: newValue?.value ?? '' }))
                  }
                  isDisabled={isEmpty(addAdminRequest)}
                />
              </td>
            </tr>
          </tbody>
        </table>
      </div>
      <div className="footer">
        <Button size="md" color="close" onClick={onCloseModal}>
          Close
        </Button>
        <Button size="md" color="confirm" onClick={handleConfirmClick} disabled={isPostingAdmin}>
          Process
        </Button>
      </div>
    </>
  );
};

export default AdministratorAddModal;
