import React from "react";
import MkdSDK from "../utils/MkdSDK";
import { useNavigate, useParams } from "react-router-dom";
import { AuthContext, tokenExpireError } from "../authContext";
import { GlobalContext, showToast } from "../globalContext";
import { empty } from "../utils/utils";
import ConfirmModal from "Components/Modal/ConfirmModal";
import { deleteEmployeeAPI } from "Src/services/employeeService";

let sdk = new MkdSDK();

const ViewEmployeePage = () => {
  const { dispatch, state: authState } = React.useContext(AuthContext);
  const { dispatch: globalDispatch } = React.useContext(GlobalContext);

  const [viewModel, setViewModel] = React.useState({});
  const [deleteItemId, setDeleteItemId] = React.useState(null);
  const [showDeleteEmployeeModal, setShowDeleteEmployeeModal] =
    React.useState(false);

  const params = useParams();
  const navigate = useNavigate();

  const handleDeleteEmployeeModalClose = () => {
    setShowDeleteEmployeeModal(false);
  };

  const handleDeleteEmployee = async () => {
    try {
      const result = await deleteEmployeeAPI(deleteItemId);
      if (!result.error) {
        setShowDeleteEmployeeModal(false);
        navigate(`/${authState.role}/employees`);
        showToast(globalDispatch, result.message, 4000);
      } else {
        setShowDeleteEmployeeModal(false);
        showToast(globalDispatch, result.message, 4000, "error");
      }
    } catch (err) {
      showToast(globalDispatch, err.message, 4000, "error");
      setShowDeleteEmployeeModal(false);
      tokenExpireError(dispatch, err.message);
    }
  };

  React.useEffect(function () {
    (async function () {
      try {
        sdk.setTable("employee");
        const result = await sdk.callRestAPI({ id: Number(params?.id) }, "GET");
        if (!result.error) {
          setViewModel(result.model);
        }
      } catch (error) {
        tokenExpireError(dispatch, error.message);
      }
    })();
  }, []);

  return (
    <>
      <div className="p-4 h-full max-w-screen md:p-4 lg:p-6 xl:p-8">
        <div className="rounded border shadow-default border-strokedark bg-boxdark dark:border-strokedark dark:bg-boxdark">
          <div className="sm:px-6.5 border-b border-strokedark px-4 py-4 dark:border-strokedark">
            <div className="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
              <h3 className="text-xl font-medium text-white">View Employee</h3>
              <div className="flex flex-wrap gap-3 items-center">
                <button
                  onClick={() => navigate(-1)}
                  className="inline-flex items-center justify-center rounded-md border border-strokedark bg-meta-4 px-6 py-2.5 text-center font-medium text-white hover:bg-opacity-90"
                >
                  Back
                </button>
                <button
                  onClick={() =>
                    navigate(`/${authState.role}/edit-employee/` + params?.id)
                  }
                  className="inline-flex items-center justify-center rounded-md bg-primary px-6 py-2.5 text-center font-medium text-white hover:bg-opacity-90"
                >
                  Edit
                </button>
                <button
                  onClick={() => {
                    setShowDeleteEmployeeModal(true);
                    setDeleteItemId(params?.id);
                  }}
                  className="inline-flex items-center justify-center rounded-md bg-danger px-6 py-2.5 text-center font-medium text-white hover:bg-opacity-90"
                >
                  Delete
                </button>
              </div>
            </div>
          </div>

          <div className="p-4 md:p-6 2xl:p-10">
            <div className="grid grid-cols-1 gap-6 md:grid-cols-2">
              <div className="space-y-4">
                <div className="pb-4 border-b border-strokedark dark:border-strokedark">
                  <span className="text-sm text-gray-400">Name</span>
                  <p className="mt-1 text-base font-medium text-white">
                    {viewModel?.name || "N/A"}
                  </p>
                </div>
                <div className="pb-4 border-b border-strokedark dark:border-strokedark">
                  <span className="text-sm text-gray-400">Email</span>
                  <p className="mt-1 text-base font-medium text-white">
                    {viewModel?.email || "N/A"}
                  </p>
                </div>
                <div className="pb-4 border-b border-strokedark dark:border-strokedark">
                  <span className="text-sm text-gray-400">Gender</span>
                  <p className="mt-1 text-base font-medium text-white capitalize">
                    {viewModel?.gender || "N/A"}
                  </p>
                </div>
              </div>

              <div className="space-y-4">
                {viewModel.is_writer === 1 && (
                  <div className="pb-4 border-b border-strokedark dark:border-strokedark">
                    <div className="flex justify-between items-center">
                      <span className="text-sm text-gray-400">Writer</span>
                      <span className="text-sm text-meta-3">Active</span>
                    </div>
                    <p className="mt-1 text-base font-medium text-white">
                      Cost: $
                      {Number(viewModel.writer_cost).toFixed(2) || "0.00"}
                    </p>
                  </div>
                )}

                {viewModel.is_artist === 1 && (
                  <div className="pb-4 border-b border-strokedark dark:border-strokedark">
                    <div className="flex justify-between items-center">
                      <span className="text-sm text-gray-400">Artist</span>
                      <span className="text-sm text-meta-3">Active</span>
                    </div>
                    <p className="mt-1 text-base font-medium text-white">
                      Cost: $
                      {Number(viewModel.artist_cost).toFixed(2) || "0.00"}
                    </p>
                  </div>
                )}

                {viewModel.is_engineer === 1 && (
                  <div className="pb-4 border-b border-strokedark dark:border-strokedark">
                    <div className="flex justify-between items-center">
                      <span className="text-sm text-gray-400">Engineer</span>
                      <span className="text-sm text-meta-3">Active</span>
                    </div>
                    <p className="mt-1 text-base font-medium text-white">
                      Cost: $
                      {Number(viewModel.engineer_cost).toFixed(2) || "0.00"}
                    </p>
                  </div>
                )}

                {viewModel.is_producer === 1 && (
                  <div className="pb-4 border-b border-strokedark dark:border-strokedark">
                    <div className="flex justify-between items-center">
                      <span className="text-sm text-gray-400">Producer</span>
                      <span className="text-sm text-meta-3">Active</span>
                    </div>
                    <p className="mt-1 text-base font-medium text-white">
                      Cost: $
                      {Number(viewModel.producer_cost).toFixed(2) || "0.00"}
                    </p>
                  </div>
                )}
              </div>

              <div className="md:col-span-2">
                <div className="p-4 rounded border border-stroke dark:border-strokedark">
                  <span className="block mb-4 text-sm text-gray-400">
                    W-9 Document
                  </span>
                  <div className="min-h-[300px] w-full rounded-sm bg-meta-4">
                    {!empty(viewModel?.w_nine) ? (
                      <embed
                        src={viewModel?.w_nine}
                        type="application/pdf"
                        className="w-full h-full rounded-sm"
                      />
                    ) : (
                      <div className="flex justify-center items-center h-full text-gray-400">
                        No W-9 document available
                      </div>
                    )}
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      {showDeleteEmployeeModal && (
        <ConfirmModal
          confirmText="Are you sure you want to delete this employee?"
          setModalClose={handleDeleteEmployeeModalClose}
          setFormYes={handleDeleteEmployee}
        />
      )}
    </>
  );
};

export default ViewEmployeePage;
