import React from "react";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { GlobalContext, showToast } from "Src/globalContext";
import AudioPlayer from "Components/AudioPlayer";
import SimpleFileUpload from "Components/FileUpload/SimpleFileUpload";
import ConfirmModal from "Components/Modal/ConfirmModal";
import { sendEmailAPIV3 } from "Src/services/emailService";
import {
  uploadS3FilesAPI,
  uploadFilesDataAPI,
} from "Src/services/workOrderService";
import { addProducerWorkOrderAPI } from "Src/services/producerWorkOrderService";
import SunEditor from "suneditor-react";
import "suneditor/dist/css/suneditor.min.css";
import { uuidv4 } from "Utils/utils";
import CustomSelect2 from "Components/CustomSelect2";
import { Download } from "lucide-react";

const audioFileTypes = ["mp3", "wav", "ogg", "flac", "aac", "wma", "m4a"];

const Tracking = ({
  authState,
  isEdit,
  expandAll,
  subProject,
  producers,
  producer,
  programName,
  setDeleteFileId,
  setEightCountPayload,
  setProducerPayload,
  setProducerCostPayload,
  setSelectedSubProjectIdForDelete,
  setUnSelectedSubProjectIdForDelete,
}) => {
  const { dispatch: globalDispatch } = React.useContext(GlobalContext);

  const editor = React.useRef();
  const [html, setHtml] = React.useState(null);

  const getSunEditorInstance = (sunEditor) => {
    editor.current = sunEditor;
  };

  const [selectedProducerId, setSelectedProducerId] = React.useState("");
  const [tempProducerId, setTempProducerId] = React.useState("");
  const [producerCost, setProducerCost] = React.useState(0);
  const [totalCost, setTotalCost] = React.useState(0);
  const [localEightCount, setLocalEightCount] = React.useState(0);
  const [localSelectedSubProjectId, setLocalSelectedSubProjectId] =
    React.useState(null);
  const [showCheckboxToDelete, setShowCheckboxToDelete] = React.useState(false);

  const [localDeleteFileId, setLocalDeleteFileId] = React.useState(null);
  const [showDeleteFileConfirmModal, setShowDeleteFileConfirmModal] =
    React.useState(false);

  const [producerEmail, setProducerEmail] = React.useState("");

  const handleNoteSubmit = async (e) => {
    try {
      e.preventDefault();
      if (!html) {
        showToast(globalDispatch, "Please enter some text", 3000, "error");
        return;
      }

      let localUuidV4 = uuidv4();

      const producerWorkOrderPayload = {
        uuidv4: localUuidV4,
        producer_id: Number(selectedProducerId),
        producer_cost: Number(producerCost),
        subproject_id: Number(subProject.id),
        project_id: Number(subProject.project_id),
      };
      //

      const producerWorkOrderResult = await addProducerWorkOrderAPI(
        producerWorkOrderPayload
      );

      if (!producerWorkOrderResult.error) {
        const producerUploadUrl = `https://equalityrecords.com/work-order/producer/${localUuidV4}`;

        let payload = {
          from: "myeq@equalityrecords.com",
          to: producerEmail,
          subject: `Tracking Order for ${programName}`,
          body:
            `A tracking order has been place for you. Please use this link ` +
            producerUploadUrl +
            ` to upload your file.<br><br><br>` +
            html,
        };
        const result = await sendEmailAPIV3(payload);
        if (!result.error) {
          showToast(globalDispatch, result.message, 5000);
          return;
        } else {
          showToast(globalDispatch, result.message, 5000, "error");
          return;
        }
      } else {
        showToast(
          globalDispatch,
          producerWorkOrderResult.message,
          5000,
          "error"
        );
        return;
      }
    } catch (error) {}
  };

  const handleDeleteFileModalClose = () => {
    setShowDeleteFileConfirmModal(false);
  };

  const handleDeleteFileSubmit = () => {
    setDeleteFileId(localDeleteFileId);
    setShowDeleteFileConfirmModal(false);
  };

  const handleProducerChange = (value) => {
    if (value === "") {
      setSelectedProducerId("");
      setProducerCost(0);
      setTotalCost(0);
      return;
    }
    const producer = producers.find((x) => x.id === Number(value));
    if (producer && producer.is_producer) {
      setSelectedProducerId(producer.id);
      let producerCost =
        producer && producer.producer_cost ? Number(producer.producer_cost) : 0;
      setProducerCost(producerCost);
      setTotalCost(producerCost);
      setProducerPayload({
        subproject_id: Number(subProject.id),
        employee_type: "producer",
        old_employee_id: tempProducerId ?? "",
        new_employee_id: Number(producer.id),
        employee_cost: Number(producer.producer_cost),
      });
    } else {
      setSelectedProducerId("");
      setProducerCost(0);
      setTotalCost(0);
    }
  };

  const handleEightCountChange = (e) => {
    e.preventDefault();
    setLocalEightCount(e.target.value);
    setEightCountPayload({
      eight_count: Number(e.target.value),
      subproject_id: Number(subProject.id),
    });
  };

  const handleSelectedSubProjectId = (id) => {
    setLocalSelectedSubProjectId(null);
    if (localSelectedSubProjectId === id) {
      setLocalSelectedSubProjectId(null);
      // setSelectedTrackingId(null);
    } else {
      setLocalSelectedSubProjectId(id);
      // setSelectedTrackingId(id);
    }
  };

  const handleFileUploads = async (formData) => {
    try {
      // setIsLoading(true);
      const result = await uploadS3FilesAPI(formData);
      if (!result.error) {
        const payload = {
          project_id: Number(subProject.project_id),
          subproject_id: Number(subProject.id),
          workorder_id: Number(subProject.workorder_id),
          employee_id: null,
          employee_type: "producer",
          type: "instrumental",
          attachments: result.attachments,
          is_from_admin: 1,
        };

        // let urls = JSON.parse(result.attachments);
        // push the urls to the beginning of html
        // urls.forEach((url) => {
        //   let html = `<p><a href="${url}" target="_blank">${url}</a></p>`;
        //   editor.current.insertHTML(html);
        // });

        const fileUploadDataResult = await uploadFilesDataAPI(payload);
        if (!fileUploadDataResult.error) {
          showToast(globalDispatch, "Files updated successfully", 5000);
          window.location.reload();
        } else {
          showToast(
            globalDispatch,
            fileUploadDataResult.message,
            5000,
            "error"
          );
        }
        // setIsLoading(false);
      } else {
        showToast(globalDispatch, result.message, 5000, "error");
        // setIsLoading(false);
      }
    } catch (error) {
      showToast(globalDispatch, error.message, 5000, "error");
    }
  };

  React.useEffect(() => {
    if (producer) {
      let producerCost =
        producer && producer.length > 0 ? Number(producer[0].emp_cost) : 0;
      setSelectedProducerId(producer[0]?.id);
      setProducerCost(producerCost);
      setTotalCost(producerCost);
      setProducerEmail(producer[0]?.email);
    }
  }, [producer]);

  React.useEffect(() => {
    if (subProject) {
      setLocalEightCount(subProject.eight_count);

      // if (
      //   subProject.admin_producer_instrumentals &&
      //   subProject.admin_producer_instrumentals.length > 0
      // ) {
      //   let extraHtml = "";
      //   subProject.admin_producer_instrumentals.map((file) => {
      //     extraHtml += `<p><a href="${file.url}" target="_blank">${file.url}</a></p>`;
      //   });
      //   setHtml(extraHtml + "<br>");
      // }
    }
  }, [subProject]);

  React.useEffect(() => {
    if (expandAll) {
      handleSelectedSubProjectId(subProject.id);
    } else {
      handleSelectedSubProjectId(null);
    }
  }, [expandAll]);

  React.useEffect(() => {
    if (isEdit) {
      setShowCheckboxToDelete(true);
    } else {
      setShowCheckboxToDelete(false);
    }
  }, [isEdit]);

  return (
    <>
      <div className="my-4 w-full rounded-md border border-gray-500 bg-gray-800 p-5 shadow">
        <div className="flex w-full flex-row flex-wrap justify-between gap-2">
          <div
            className="cursor-pointer"
            style={{
              position: "relative",
              top: "30px",
              // right: '10px',
            }}
            onClick={() => {
              handleSelectedSubProjectId(subProject.id);
            }}
          >
            {localSelectedSubProjectId === subProject.id ? (
              <FontAwesomeIcon
                icon="fa-solid fa-chevron-down"
                width={16}
                height={16}
              />
            ) : (
              <FontAwesomeIcon
                icon="fa-solid fa-chevron-up"
                width={16}
                height={16}
              />
            )}
          </div>
          {showCheckboxToDelete && (
            <div className="mx-2 flex flex-col items-center justify-center">
              <input
                type="checkbox"
                className="ml-2 h-4 w-4 rounded border-gray-300 bg-gray-100 text-blue-600 focus:ring-2 focus:ring-blue-500 dark:focus:ring-blue-600"
                onChange={(e) => {
                  if (e.target.checked) {
                    setSelectedSubProjectIdForDelete(subProject.id);
                  } else {
                    setUnSelectedSubProjectIdForDelete(subProject.id);
                  }
                }}
              />
            </div>
          )}

          <div className="flex w-full flex-row flex-wrap items-end justify-start gap-2 xl:justify-between">
            <div className="relative mt-6">
              <input
                type="text"
                className={`h-[42px] w-[104px] cursor-default rounded-lg border border-stone-500 bg-purple-600 p-2.5 text-sm font-medium text-white placeholder-stone-300 focus:border-blue-500 focus:ring-blue-500`}
                placeholder="Type"
                value={subProject.type_name}
                readOnly
              />
            </div>

            <div className="relative mt-6">
              <input
                type="number"
                id="eightCountInput"
                className="border-1 peer block h-[42px] w-20 appearance-none rounded-lg border-stroke/50 bg-transparent px-2.5 pb-2.5 pt-4 text-sm text-white focus:border-blue-500 focus:outline-none focus:ring-0 dark:text-white dark:focus:border-blue-500"
                placeholder=" "
                min="0"
                value={localEightCount}
                onChange={handleEightCountChange}
              />
              <label
                htmlFor="eightCountInput"
                class="absolute start-1 top-2  z-[4] origin-[0] -translate-y-4 scale-75 transform bg-gray-800 px-2  text-sm font-medium  text-white duration-300  disabled:text-white/40 peer-placeholder-shown:top-1/2 peer-placeholder-shown:-translate-y-1/2 peer-placeholder-shown:scale-100 peer-focus:top-2 peer-focus:-translate-y-4 peer-focus:scale-75  peer-focus:px-2 peer-focus:text-blue-500  rtl:peer-focus:left-auto rtl:peer-focus:translate-x-1/4 dark:bg-gray-800  dark:text-white"
              >
                # of 8cts
              </label>
            </div>

            <div className="relative mt-6">
              <CustomSelect2
                name="producer"
                label="Producer"
                position="up"
                value={selectedProducerId}
                onChange={(e) => handleProducerChange(e)}
                className="peer block h-[42px] !w-[120px] appearance-none text-ellipsis rounded-lg border border-stroke/50 bg-transparent p-2.5 pr-5 text-sm text-white focus:border-blue-500 focus:outline-none focus:ring-0 disabled:opacity-30 dark:text-white dark:focus:border-blue-500"
              >
                <option className="bg-gray-800 text-white" value="">
                  Select
                </option>
                {producers?.map((producer) => (
                  <option
                    className="bg-gray-800 text-white"
                    key={producer.id}
                    value={producer.id}
                  >
                    {producer.name}
                  </option>
                ))}
              </CustomSelect2>
              <label
                htmlFor="producer"
                class="absolute start-1 top-2  z-[4] origin-[0] -translate-y-4 scale-75 transform bg-gray-800  px-2 text-sm  font-medium text-white duration-300 disabled:text-white/40 peer-placeholder-shown:top-1/2 peer-placeholder-shown:-translate-y-1/2 peer-placeholder-shown:scale-100 peer-focus:top-2 peer-focus:-translate-y-4 peer-focus:scale-75  peer-focus:px-2 peer-focus:text-blue-500  rtl:peer-focus:left-auto rtl:peer-focus:translate-x-1/4 dark:bg-gray-800  dark:text-white"
              >
                Producer
              </label>
            </div>
            <div className="relative mt-6">
              <input
                type="number"
                id="writer_cost"
                className="border-1 peer block h-[42px] w-20 appearance-none rounded-lg border-stroke/50 bg-transparent px-2.5 pb-2.5 pt-4 text-sm font-medium text-white focus:border-blue-500 focus:outline-none focus:ring-0 dark:text-white dark:focus:border-blue-500"
                value={producerCost}
                min="0"
                onChange={(e) => {
                  if (!selectedProducerId) {
                    showToast(
                      globalDispatch,
                      "Please select a producer",
                      5000,
                      "warning"
                    );
                    return;
                  }
                  setProducerCost(Number(e.target.value));
                  setTotalCost(Number(e.target.value));
                  setProducerCostPayload({
                    subproject_id: Number(subProject.id),
                    employee_type: "producer",
                    employee_id: Number(selectedProducerId),
                    employee_cost: Number(e.target.value),
                  });
                }}
              />
              <label
                for="producer_cost"
                className="absolute start-1 top-2 z-[4] origin-[0] -translate-y-4 scale-75 transform bg-gray-800 px-2 text-sm text-white duration-300 peer-placeholder-shown:top-1/2 peer-placeholder-shown:-translate-y-1/2 peer-placeholder-shown:scale-100 peer-focus:top-2 peer-focus:-translate-y-4 peer-focus:scale-75 peer-focus:px-2 peer-focus:text-blue-500 rtl:peer-focus:left-auto rtl:peer-focus:translate-x-1/4 dark:bg-gray-800 dark:text-white"
              >
                Cost
              </label>
            </div>

            <div className="invisible relative mt-6">
              <CustomSelect2
                name="artist"
                position="up"
                label="Artist"
                className="peer block h-[42px] !w-[120px] appearance-none text-ellipsis rounded-lg border border-stroke/50 bg-transparent p-2.5 pr-5 text-sm text-white focus:border-blue-500 focus:outline-none focus:ring-0 disabled:opacity-30 dark:text-white dark:focus:border-blue-500"
              >
                <option className="bg-gray-800 text-white" value="">
                  Select
                </option>
              </CustomSelect2>
              <label
                htmlFor="artist"
                class="absolute start-1 top-2  z-[4] origin-[0] -translate-y-4 scale-75 transform bg-gray-800  px-2 text-sm  text-white duration-300  disabled:text-white/40 peer-placeholder-shown:top-1/2 peer-placeholder-shown:-translate-y-1/2 peer-placeholder-shown:scale-100 peer-focus:top-2 peer-focus:-translate-y-4 peer-focus:scale-75  peer-focus:px-2 peer-focus:text-blue-500  rtl:peer-focus:left-auto rtl:peer-focus:translate-x-1/4 dark:bg-gray-800  dark:text-white"
              >
                Artist
              </label>
            </div>

            <div className="invisible relative mt-6">
              <CustomSelect2
                name="engineer"
                label="Engineer"
                disabled
                className="border-1 peer invisible block h-[42px] w-28 appearance-none text-ellipsis rounded-lg border-zinc-500 bg-zinc-700 p-2.5 pr-5 text-sm text-white focus:border-blue-500 focus:outline-none focus:ring-0 dark:border-zinc-500 dark:text-white dark:focus:border-blue-500"
              >
                <option className="bg-gray-800 text-white" value="">
                  Select
                </option>
              </CustomSelect2>
              <label
                htmlFor="engineer"
                className="absolute start-1 top-2 z-[4] origin-[0] -translate-y-4 scale-75 transform rounded-[40px] bg-gray-800 px-2 text-sm font-medium text-white duration-300 peer-placeholder-shown:top-1/2 peer-placeholder-shown:-translate-y-1/2 peer-placeholder-shown:scale-100 peer-focus:top-2 peer-focus:-translate-y-4 peer-focus:scale-75 peer-focus:px-2 peer-focus:text-blue-500 rtl:peer-focus:left-auto rtl:peer-focus:translate-x-1/4 dark:text-white peer-focus:dark:text-blue-500"
              >
                Engineer
              </label>
            </div>

            <div className="invisible relative mt-6">
              <input
                type="number"
                id="artist_cost"
                className="border-1 peer invisible block h-[42px] w-20 appearance-none rounded-lg border-stroke/50 bg-transparent px-2.5 pb-2.5 pt-4 text-sm text-white focus:border-blue-500 focus:outline-none focus:ring-0 dark:text-white dark:focus:border-blue-500"
                placeholder="Cost"
                min="0"
              />
              <label
                for="artist_cost"
                className="absolute start-1 top-2 z-[4] origin-[0] -translate-y-4 scale-75 transform bg-gray-800 px-2 text-sm font-medium text-white duration-300 peer-placeholder-shown:top-1/2 peer-placeholder-shown:-translate-y-1/2 peer-placeholder-shown:scale-100 peer-focus:top-2 peer-focus:-translate-y-4 peer-focus:scale-75 peer-focus:px-2 peer-focus:text-blue-500 rtl:peer-focus:left-auto rtl:peer-focus:translate-x-1/4 dark:bg-gray-800 dark:text-white"
              >
                Cost
              </label>
            </div>

            <div className="relative mt-6">
              <input
                type="text"
                id="total"
                className="border-1 peer block h-[42px] w-20 appearance-none rounded-lg border-zinc-500 bg-zinc-700 bg-zinc-700 px-2.5 pb-2.5 pt-4 text-sm font-medium text-white focus:border-blue-600 focus:outline-none focus:ring-0 dark:border-zinc-500 dark:text-white dark:focus:border-blue-500"
                value={totalCost}
                disabled
              />
              <label
                for="total"
                className="absolute start-1 top-2 z-[4] origin-[0] -translate-y-4 scale-75 transform rounded-[40px] bg-gray-800 px-2 text-sm text-white duration-300 peer-placeholder-shown:top-1/2 peer-placeholder-shown:-translate-y-1/2 peer-placeholder-shown:scale-100 peer-focus:top-2 peer-focus:-translate-y-4 peer-focus:scale-75 peer-focus:px-2 peer-focus:text-blue-500 rtl:peer-focus:left-auto rtl:peer-focus:translate-x-1/4 dark:text-white peer-focus:dark:text-blue-500"
              >
                Total
              </label>
            </div>
          </div>
        </div>
      </div>

      {localSelectedSubProjectId === subProject.id && (
        <div className="flex w-full flex-col items-start justify-start gap-4 rounded border border-gray-500 bg-slate-500 p-5 shadow">
          <div className="my-1 flex w-full flex-col items-start justify-start gap-2 border-b-2 pb-2 md:flex-row">
            <div className="w-1/2">
              <div className="mb-2 flex flex-col">
                <div className="mb-2 text-xl font-semibold">File Uploads</div>

                {subProject.admin_producer_instrumentals &&
                  subProject.admin_producer_instrumentals.length < 2 && (
                    <SimpleFileUpload
                      label={"File"}
                      maxFileSize={500}
                      setFormData={handleFileUploads}
                    />
                  )}

                {subProject.admin_producer_instrumentals &&
                  subProject.admin_producer_instrumentals.length > 0 &&
                  subProject.admin_producer_instrumentals.map((file, index) => {
                    let fileSrc = `${file.url}`;
                    // only keep the file name which is last part of the url
                    let fileSrcTemp = fileSrc.split("/").pop();
                    let fileExtension = fileSrc.split(".").pop();
                    return (
                      <div key={index} className="mb-4 flex flex-col gap-1">
                        {audioFileTypes.includes(fileExtension) && (
                          <div className="flex items-center gap-3">
                            <a
                              className="truncate text-sm text-white underline"
                              href={fileSrc}
                              rel="noreferrer"
                              target="_blank"
                            >
                              {fileSrcTemp}
                            </a>
                            <Download
                              onClick={() => {
                                const link = document.createElement("a");
                                link.href = fileSrc;
                                link.download = fileSrcTemp;
                                document.body.appendChild(link);
                                link.click();
                                document.body.removeChild(link);
                              }}
                              className="h-5 w-5 text-primary"
                            />
                          </div>
                        )}

                        <div className="flex flex-row items-center gap-4">
                          {audioFileTypes.includes(fileExtension) && (
                            <AudioPlayer fileSource={fileSrc} />
                          )}
                          {!audioFileTypes.includes(fileExtension) && (
                            <a
                              className="truncate text-sm text-white underline"
                              href={fileSrc}
                              rel="noreferrer"
                              target="_blank"
                            >
                              {fileSrcTemp}
                            </a>
                          )}
                          <button
                            onClick={(e) => {
                              e.stopPropagation();
                              setShowDeleteFileConfirmModal(true);
                              setLocalDeleteFileId(file.id);
                            }}
                            className="group rounded-full p-2 hover:bg-danger/5"
                          >
                            <FontAwesomeIcon
                              icon="fa-solid fa-trash"
                              className="h-4 w-4 text-danger group-hover:text-danger/90"
                            />
                          </button>
                        </div>
                      </div>
                    );
                  })}
              </div>

              {!subProject.workorder_id ? (
                <div className="flex flex-col">
                  <label
                    className="block text-sm font-bold text-gray-100"
                    htmlFor="note"
                  >
                    Notes
                  </label>
                  <SunEditor
                    width="100%"
                    height="200px"
                    onChange={(newContent) => {
                      setHtml(newContent);
                    }}
                    defaultValue={html}
                    getSunEditorInstance={getSunEditorInstance}
                    setOptions={{
                      buttonList: [
                        ["undo", "redo"],
                        ["font", "fontSize", "formatBlock"],
                        [
                          "bold",
                          "underline",
                          "italic",
                          "subscript",
                          "superscript",
                        ],
                        ["fontColor", "hiliteColor"],
                        ["outdent", "indent"],
                        ["align", "horizontalRule", "list", "table"],
                        ["link"],
                        ["print"],
                      ],
                    }}
                  />
                  <button
                    type="button"
                    className="mt-1 w-max rounded bg-green-600 px-2 py-1 text-sm font-medium text-white hover:bg-green-700"
                    onClick={(e) => handleNoteSubmit(e)}
                  >
                    Send to Producer
                  </button>
                </div>
              ) : (
                <div>Workorder exists</div>
              )}
            </div>

            <div className="flex w-1/2 flex-col gap-1">
              <div className="mb-2 text-xl font-semibold">
                Files from Producer
              </div>

              <div className="flex flex-row flex-wrap justify-between gap-2">
                {subProject.producer_files &&
                  subProject.producer_files.length > 0 &&
                  subProject.producer_files.map((file, index) => {
                    let fileSrc = `${file.url}`;
                    // only keep the file name which is last part of the url
                    let fileSrcTemp = fileSrc.split("/").pop();
                    let fileExtension = fileSrc.split(".").pop();
                    return (
                      <div key={index} className="mb-4 flex flex-col gap-1">
                        {audioFileTypes.includes(fileExtension) && (
                          <a
                            className="truncate text-sm text-white underline"
                            href={fileSrc}
                            rel="noreferrer"
                            target="_blank"
                          >
                            {fileSrcTemp}
                          </a>
                        )}
                        <div className="flex flex-row items-center gap-4">
                          {audioFileTypes.includes(fileExtension) && (
                            <AudioPlayer fileSource={fileSrc} />
                          )}
                          {!audioFileTypes.includes(fileExtension) && (
                            <a
                              className="truncate text-sm text-white underline"
                              href={fileSrc}
                              rel="noreferrer"
                              target="_blank"
                            >
                              {fileSrcTemp}
                            </a>
                          )}
                          <button
                            onClick={(e) => {
                              e.stopPropagation();
                              setShowDeleteFileConfirmModal(true);
                              setLocalDeleteFileId(file.id);
                            }}
                            className="group rounded-full p-2 hover:bg-danger/5"
                          >
                            <FontAwesomeIcon
                              icon="fa-solid fa-trash"
                              className="h-4 w-4 text-danger group-hover:text-danger/90"
                            />
                          </button>
                        </div>
                      </div>
                    );
                  })}
              </div>
            </div>
          </div>
        </div>
      )}

      {showDeleteFileConfirmModal ? (
        <ConfirmModal
          confirmText={`Are you sure you want to delete this file?`}
          setModalClose={handleDeleteFileModalClose}
          setFormYes={handleDeleteFileSubmit}
        />
      ) : null}
    </>
  );
};

export default Tracking;
