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

const COLORS = [
  {
    id: 1,
    color: "#6CC551",
    name: "Green",
  },
  {
    id: 2,
    color: "#197BBD",
    name: "Blue",
  },
  {
    id: 3,
    color: "#F3A738",
    name: "Gold",
  },
  {
    id: 4,
    color: "#C0C0C0",
    name: "Gray",
  },
  {
    id: 5,
    color: "#8A2BE2",
    name: "Purple",
  },
  {
    id: 6,
    color: "#FF91AF",
    name: "Pink",
  },
  {
    id: 7,
    color: "#00FFFF",
    name: "Cyan",
  },
  {
    id: 8,
    color: "#B31B1B",
    name: "Red",
  },
  {
    id: 9,
    color: "#FF7F50",
    name: "Coral",
  },
];

let sdk = new MkdSDK();

const ViewMixTypePage = () => {
  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 [showDeleteMixTypeModal, setShowDeleteMixTypeModal] =
    React.useState(false);
  const [subProjects, setSubProjects] = React.useState([]);
  const [isOld, setIsOld] = React.useState(false);

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

  const handleDeleteMixTypeModalClose = () => {
    setShowDeleteMixTypeModal(false);
  };

  const handleDeleteMixType = async () => {
    try {
      const result = await deleteMixTypeAPI(deleteItemId);
      if (!result.error) {
        setShowDeleteMixTypeModal(false);
        navigate(`/${authState.role}/mix-types`);
        showToast(globalDispatch, result.message, 4000);
      } else {
        setShowDeleteMixTypeModal(false);
        showToast(globalDispatch, result.message, 4000, "error");
      }
    } catch (err) {
      showToast(globalDispatch, err.message, 4000, "error");
      setShowDeleteMixTypeModal(false);
      tokenExpireError(dispatch, err.message);
    }
  };

  React.useEffect(function () {
    globalDispatch({
      type: "SETPATH",
      payload: {
        path: "mix-types",
      },
    });

    (async function () {
      try {
        sdk.setTable("mix_type");
        const result = await sdk.callRestAPI({ id: Number(params?.id) }, "GET");
        if (!result.error) {
          setViewModel(result.model);
          setIsOld(result.model.is_old);
          if (result.model.sub_projects) {
            let subProjects = JSON.parse(result.model.sub_projects);
            setSubProjects(subProjects);
          }
        }
      } catch (error) {
        tokenExpireError(dispatch, error.message);
      }
    })();
  }, []);

  return (
    <>
      <div className="max-w-screen h-full p-4 md:p-4 lg:p-6 xl:p-8">
        <div className="shadow-default rounded border 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 Mix Type</h3>
              <div className="flex flex-wrap items-center gap-3">
                <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-mix-type/` + 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={() => {
                    setShowDeleteMixTypeModal(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="space-y-6">
              <div className="grid grid-cols-1 gap-6 md:grid-cols-2">
                <div className="space-y-4">
                  <div className="border-b border-strokedark pb-4 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="border-b border-strokedark pb-4 dark:border-strokedark">
                    <span className="text-sm text-gray-400">Price</span>
                    <p className="mt-1 text-base font-medium text-white">
                      ${Number(viewModel?.price).toFixed(2) || "0.00"}
                    </p>
                  </div>
                  <div className="border-b border-strokedark pb-4 dark:border-strokedark">
                    <span className="text-sm text-gray-400">Color</span>
                    <div className="mt-1 flex items-center gap-3">
                      <div
                        className="h-6 w-6 rounded-full"
                        style={{ backgroundColor: viewModel?.color }}
                      ></div>
                      <span className="text-base font-medium text-white">
                        {COLORS.find((x) => x.color === viewModel?.color)
                          ?.name || "N/A"}
                      </span>
                    </div>
                  </div>
                </div>

                <div className="space-y-4">
                  <div className="border-b border-strokedark pb-4 dark:border-strokedark">
                    <span className="text-sm text-gray-400">Voiceover</span>
                    <div className="mt-1 flex items-center justify-between">
                      <p className="text-base font-medium text-white">
                        {viewModel?.is_voiceover === 1 ? "Yes" : "No"}
                      </p>
                      {viewModel?.is_voiceover === 1 && (
                        <span className="text-base text-white">
                          Count: {viewModel?.voiceover}
                        </span>
                      )}
                    </div>
                  </div>
                  <div className="border-b border-strokedark pb-4 dark:border-strokedark">
                    <span className="text-sm text-gray-400">Song</span>
                    <div className="mt-1 flex items-center justify-between">
                      <p className="text-base font-medium text-white">
                        {viewModel?.is_song === 1 ? "Yes" : "No"}
                      </p>
                      {viewModel?.is_song === 1 && (
                        <span className="text-base text-white">
                          Count: {viewModel?.song}
                        </span>
                      )}
                    </div>
                  </div>
                  <div className="border-b border-strokedark pb-4 dark:border-strokedark">
                    <span className="text-sm text-gray-400">Tracking</span>
                    <div className="mt-1 flex items-center justify-between">
                      <p className="text-base font-medium text-white">
                        {viewModel?.is_tracking === 1 ? "Yes" : "No"}
                      </p>
                      {viewModel?.is_tracking === 1 && (
                        <span className="text-base text-white">
                          Count: {viewModel?.tracking}
                        </span>
                      )}
                    </div>
                  </div>
                </div>
              </div>

              <div className="shadow-default rounded border border-strokedark bg-boxdark dark:border-strokedark dark:bg-boxdark">
                <div className="border-b border-strokedark px-4 py-4 dark:border-strokedark">
                  <h3 className="font-medium text-white">Sub-projects</h3>
                </div>
                <div className="max-h-96 overflow-x-auto">
                  <table className="w-full table-auto">
                    <thead>
                      <tr className="border-b border-strokedark bg-meta-4">
                        <th className="px-4 py-4 font-medium text-white">
                          Quantity
                        </th>
                        <th className="px-4 py-4 font-medium text-white">
                          # of 8 counts
                        </th>
                        <th className="px-4 py-4 font-medium text-white">
                          Type
                        </th>
                      </tr>
                    </thead>
                    <tbody>
                      {subProjects?.length > 0 ? (
                        subProjects.map((row, index) => (
                          <tr
                            key={index}
                            className="border-b border-strokedark"
                          >
                            <td className="px-4 py-5 text-center text-white">
                              {row.quantity}
                            </td>
                            <td className="px-4 py-5 text-center text-white">
                              {row.eight_count}
                            </td>
                            <td className="px-4 py-5 text-center text-white">
                              {row.type}
                            </td>
                          </tr>
                        ))
                      ) : (
                        <tr>
                          <td
                            colSpan="3"
                            className="px-4 py-5 text-center text-white"
                          >
                            No data found
                          </td>
                        </tr>
                      )}
                    </tbody>
                  </table>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      {showDeleteMixTypeModal && (
        <ConfirmModal
          confirmText="Are you sure you want to delete this mix type?"
          setModalClose={handleDeleteMixTypeModalClose}
          setFormYes={handleDeleteMixType}
        />
      )}
    </>
  );
};

export default ViewMixTypePage;
