import React, { useState } from 'react';
import { QueryObserverResult, useQueryClient } from '@tanstack/react-query';

import { toast } from 'react-toastify';
import { Page } from 'src/services/commonResponse/PageResponse';
import { MajorCodeListResponse, UpdateMajorNameRequest, useUpdateMajorNameMutation } from '@api/codeAPI';
import AlertModal from '@components/ui/modal/AlertModal';
import { isEmpty } from '@utils/objectUtils';
import Button from '@components/ui/button/Button';

interface Props {
  major: { code: string; name: string };
  onClose: () => void;
  majorListRefetch: () => Promise<QueryObserverResult<Page<MajorCodeListResponse>, Error>>;
}

const MajorNameModal = ({ major, onClose, majorListRefetch }: Props) => {
  const [updateSuccess, setUpdateSuccess] = useState(false);
  const [modal, setModal] = useState({
    isOpen: false,
    txt: ''
  });
  const [updateMajorNameRequest, setUpdateMajorNameRequest] = useState<UpdateMajorNameRequest>({
    data: {
      codeValue: major.name
    },
    path: major.code
  });

  // API
  const queryClient = useQueryClient();
  const { mutate: updateMajorName, isPending: isUpdatingMajorName } = useUpdateMajorNameMutation();

  const handleConfirmClick = () => {
    updateMajorName(updateMajorNameRequest, {
      onSuccess: () => {
        toast.success('Major name has been updated.');
        onClose();
        setUpdateSuccess(true);
        queryClient.invalidateQueries({ queryKey: ['majorCodeList'] });
      },
      onError: (error) => {
        setModal({ isOpen: true, txt: error.response?.data.errorMessage as string });
        setUpdateSuccess(false);
      }
    });
  };

  const handleAlertModalClose = () => {
    setModal({ isOpen: false, txt: '' });

    if (updateSuccess) {
      majorListRefetch();
      onClose();
    }
  };

  return (
    <>
      <AlertModal
        isOpen={modal.isOpen}
        closeBtn={{
          onClose: () => handleAlertModalClose(),
          buttonName: 'Close'
        }}
      >
        {modal.txt}
      </AlertModal>
      <div className="title">
        <span className="modal_title">Major Name</span>
      </div>
      <div className="body">
        <table className="table">
          <tbody>
            <tr>
              <th>Major Code</th>
              <td>{major.code}</td>
            </tr>
            <tr>
              <th>Major Name</th>
              <td>
                <input
                  type="text"
                  className="form_control"
                  defaultValue={major.name}
                  onChange={(e) =>
                    setUpdateMajorNameRequest((prevState) => ({
                      ...prevState,
                      data: { ...prevState.data, codeValue: e.target.value }
                    }))
                  }
                  readOnly={isEmpty(updateMajorNameRequest.data)}
                />
              </td>
            </tr>
          </tbody>
        </table>
      </div>
      <div className="footer">
        <Button size="md" color="close" onClick={onClose}>
          Close
        </Button>
        <Button size="md" color="confirm" onClick={handleConfirmClick} disabled={isUpdatingMajorName}>
          Process
        </Button>
      </div>
    </>
  );
};

export default MajorNameModal;
