import React, { useState } from "react";
import { AuthContext, tokenExpireError } from "Src/authContext";
import { GlobalContext, showToast } from "Src/globalContext";
import {
  retrieveAllSettingsAPI,
  createOrUpdateAllSettingsAPI,
  uploadSettingFileAPI,
  updateSettingAPI,
} from "Src/services/settingService";
import {
  getSurveyEmailTemplateAPI,
  updateSurveyEmailTemplateAPI,
} from "Src/services/surveyService";
import PhotoUpload from "Components/PhotoUpload";
import SunEditor, { buttonList } from "suneditor-react";
import "suneditor/dist/css/suneditor.min.css";
import { retrieveAllUserAPI } from "Src/services/userService";
import ConfirmModal from "Components/Modal/ConfirmModal";
import DuoConfirmModal from "Components/Modal/DuoConfirmModal";
import { retrieveAllMixSeasonsAPI } from "Src/services/mixSeasonService";
import { deleteAllProjectForUserAPI } from "Src/services/projectService";
import PhotoUpload2 from "Components/PhotoUpload2";
import CustomSelect from "Components/CustomSelect";
import CustomSelect2 from "Components/CustomSelect2";

const ListAdminSettingPage = () => {
  const { dispatch } = React.useContext(AuthContext);
  const { dispatch: globalDispatch } = React.useContext(GlobalContext);

  const [managementValue, setManagementValue] = React.useState(null);
  const [managementValueType, setManagementValueType] = React.useState(null);
  const [artistDeadline, setArtistDeadline] = React.useState(null);
  const [engineerDeadline, setEngineerDeadline] = React.useState(null);
  const [artistEngineerDeadline, setArtistEngineerDeadline] =
    React.useState(null);
  const [voiceoverEightCount, setVoiceoverEightCount] = React.useState(null);
  const [songEightCount, setSongEightCount] = React.useState(null);
  const [trackingEightCount, setTrackingEightCount] = React.useState(null);
  const [siteLogoUrl, setSiteLogoUrl] = React.useState(null);
  const [landingImageUrl, setLandingImageUrl] = React.useState(null);
  const [selectedMemberId, setSelectedMemberId] = React.useState("");
  const [showRealProjectModal, setShowRealProjectModal] = React.useState(false);
  const [showDeleteProjectModal, setShowDeleteProjectModal] =
    React.useState(false);
  const [mixSeasons, setMixSeasons] = React.useState([]);
  const [selectedMixSeason, setSelectedMixSeason] = React.useState(null);
  const dropdownRef = React.useRef(null);
  const editor = React.useRef();
  const [surveyRowId, setSurveyRowId] = React.useState(null);
  const [html, setHtml] = React.useState(null);
  const [content, setContent] = React.useState("");
  const [members, setMembers] = React.useState([]);
  const [activeTab, setActiveTab] = useState("site_images");

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

  async function getMixSeasons() {
    try {
      const result = await retrieveAllMixSeasonsAPI(1, 10000, {
        user_id: selectedMemberId,
      });
      !result.error && setMixSeasons(result.list);
    } catch (error) {
      tokenExpireError(dispatch, error.message);
    }
  }

  const handleManagementValueChange = (e) => {
    setManagementValue(e.target.value);
  };

  const handleManagementValueTypeChange = (e) => {
    setManagementValueType(e.target.value);
  };

  const handleArtistDeadlineChange = (e) => {
    setArtistDeadline(e.target.value);
  };

  const handleEngineerDeadlineChange = (e) => {
    setEngineerDeadline(e.target.value);
  };

  const handleArtistEngineerDeadlineChange = (e) => {
    setArtistEngineerDeadline(e.target.value);
  };

  const handleVoiceoverEightCountChange = (e) => {
    setVoiceoverEightCount(e.target.value);
  };

  const handleSongEightCountChange = (e) => {
    setSongEightCount(e.target.value);
  };

  const handleTrackingEightCountChange = (e) => {
    setTrackingEightCount(e.target.value);
  };

  const retrieveAllSettings = async () => {
    try {
      const result = await retrieveAllSettingsAPI({
        user_id: parseInt(localStorage.getItem("user")),
      });
      if (!result.error) {
        // set all settings that matches with SETTING_KEYS
        if (result.list.length > 0) {
          result.list.forEach((row) => {
            if (row.setting_key === "management_value") {
              setManagementValue(row.setting_value);
            }
            if (row.setting_key === "management_value_type") {
              setManagementValueType(row.setting_value);
            }
            if (row.setting_key === "artist_deadline") {
              setArtistDeadline(row.setting_value);
            }
            if (row.setting_key === "engineer_deadline") {
              setEngineerDeadline(row.setting_value);
            }
            if (row.setting_key === "artist_engineer_deadline") {
              setArtistEngineerDeadline(row.setting_value);
            }
            if (row.setting_key === "voiceover_eight_count") {
              setVoiceoverEightCount(row.setting_value);
            }
            if (row.setting_key === "song_eight_count") {
              setSongEightCount(row.setting_value);
            }
            if (row.setting_key === "tracking_eight_count") {
              setTrackingEightCount(row.setting_value);
            }
            if (row.setting_key === "site_logo") {
              setSiteLogoUrl(row.setting_value);
            }
            if (row.setting_key === "landing_image") {
              setLandingImageUrl(row.setting_value);
            }
          });
        }
      }
    } catch (error) {
      tokenExpireError(dispatch, error.message);
    }
  };

  const createOrUpdateAllSettings = async () => {
    try {
      const payload = {
        settings: [
          {
            setting_key: "management_value",
            setting_value: managementValue ?? 0,
          },
          {
            setting_key: "management_value_type",
            setting_value: managementValueType ?? "%",
          },
          {
            setting_key: "artist_deadline",
            setting_value: artistDeadline ?? 3,
          },
          {
            setting_key: "engineer_deadline",
            setting_value: engineerDeadline ?? 3,
          },
          {
            setting_key: "artist_engineer_deadline",
            setting_value: artistEngineerDeadline ?? 3,
          },
          {
            setting_key: "voiceover_eight_count",
            setting_value: voiceoverEightCount ?? 4,
          },
          {
            setting_key: "song_eight_count",
            setting_value: songEightCount ?? 8,
          },
          {
            setting_key: "tracking_eight_count",
            setting_value: trackingEightCount ?? 4,
          },
        ],
      };
      const result = await createOrUpdateAllSettingsAPI(payload);
      if (!result.error) {
        showToast(globalDispatch, result.message, 4000);
        await retrieveAllSettings();
      }
    } catch (error) {
      tokenExpireError(dispatch, error.message);
    }
  };

  const handleSiteLogoUpload = async (formData) => {
    try {
      const result = await uploadSettingFileAPI(formData);
      if (!result.error) {
        const updateResult = await updateSettingAPI({
          setting_key: "site_logo",
          setting_value: result.url,
        });
        if (!updateResult.error) {
          setSiteLogoUrl(result.url);
          globalDispatch({
            type: "SITE_IMAGES",
            payload: {
              siteLogo: `https://app.equalityrecords.com/${result.url}`,
              landingImage: `https://app.equalityrecords.com/${landingImageUrl}`,
            },
          });
          showToast(globalDispatch, updateResult.message, 5000);
        } else {
          showToast(globalDispatch, updateResult.message, 3000, "error");
          return;
        }
      } else {
        showToast(globalDispatch, result.message, 2000, "error");
        return;
      }
    } catch (error) {
      tokenExpireError(dispatch, error.message, 4000);
    }
  };

  const handleLandingImageUrlUpload = async (formData) => {
    try {
      const result = await uploadSettingFileAPI(formData);
      if (!result.error) {
        const updateResult = await updateSettingAPI({
          setting_key: "landing_image",
          setting_value: result.url,
        });
        if (!updateResult.error) {
          setLandingImageUrl(result.url);
          globalDispatch({
            type: "SITE_IMAGES",
            payload: {
              siteLogo: `https://app.equalityrecords.com/${siteLogoUrl}`,
              landingImage: `https://app.equalityrecords.com/${result.url}`,
            },
          });
          showToast(globalDispatch, updateResult.message, 5000);
        } else {
          showToast(globalDispatch, updateResult.message, 3000, "error");
          return;
        }
      } else {
        showToast(globalDispatch, result.message, 2000, "error");
        return;
      }
    } catch (error) {
      tokenExpireError(dispatch, error.message, 4000);
    }
  };

  const getSurveyEmailTemplate = async () => {
    try {
      const result = await getSurveyEmailTemplateAPI();
      if (!result.error) {
        setContent(result.model.html);
        setHtml(result.model.html);
        editor?.current?.setContents(result.model.html);
        setSurveyRowId(result.model.id);
      }
    } catch (error) {
      tokenExpireError(dispatch, error.message, 4000);
    }
  };

  const updateSurveyEmailTemplate = async () => {
    try {
      const result = await updateSurveyEmailTemplateAPI({
        html,
        id: surveyRowId,
      });
      if (!result.error) {
        showToast(globalDispatch, result.message, 4000);
        await getSurveyEmailTemplate();
        return;
      }
    } catch (error) {
      tokenExpireError(dispatch, error.message, 4000);
    }
  };

  const retrieveAllUsers = async () => {
    try {
      let filter = {
        role: "member",
        status: 1,
      };
      const result = await retrieveAllUserAPI(1, 4000, filter);
      if (!result.error) {
        if (result.list.length > 0) {
          let list = result.list;
          // concat first_name and last_name into user_name
          // then sort by ascending order of user_name
          list = list.map((row) => {
            row.user_name = row.first_name + " " + row.last_name;
            return row;
          });
          list = list.sort((a, b) => {
            return a.user_name.localeCompare(b.user_name);
          });

          setMembers(list);
        }
      }
    } catch (error) {
      tokenExpireError(dispatch, error.message);
    }
  };

  React.useEffect(() => {
    globalDispatch({
      type: "SETPATH",
      payload: {
        path: "setting",
      },
    });

    (async function () {
      await retrieveAllSettings();
      await retrieveAllUsers();
      await getMixSeasons();
      await getSurveyEmailTemplate();
    })();
  }, []);

  React.useEffect(() => {
    (async function () {
      selectedMemberId && (await getMixSeasons());
    })();
  }, [selectedMemberId]);

  const handleDeleteProjectModalClose = () => {
    setShowDeleteProjectModal(false);
  };

  const handleDeleteProject = async () => {
    try {
      const result = await deleteAllProjectForUserAPI({
        user_id: parseInt(selectedMemberId),
        mix_season_id: parseInt(selectedMixSeason),
      });
      if (!result.error) {
        setShowRealProjectModal(false);
        // navigate(`/${authState.role}/projects`);
        setSelectedMixSeason("");
        setSelectedMemberId("");
        await getMixSeasons();
        showToast(globalDispatch, result.message, 4000);
      } else {
        setShowRealProjectModal(false);
        showToast(globalDispatch, result.message, 4000, "error");
      }
    } catch (err) {
      showToast(globalDispatch, err.message, 4000, "error");
      setShowRealProjectModal(false);
      tokenExpireError(dispatch, err.message);
    }
  };

  const handleRealProjectModalClose = () => {
    setShowRealProjectModal(false);
  };

  const openSecondDelete = () => {
    setShowDeleteProjectModal(false);

    setTimeout(() => {
      setShowRealProjectModal(true);
    }, 500);
  };

  return (
    <>
      <div className="max-w-screen h-full p-4 md:p-4 lg:p-6 xl:p-8">
        <div className="rounded border border-strokedark bg-boxdark">
          {/* Tab Navigation */}
          <div className="flex flex-wrap border-b border-strokedark">
            <button
              onClick={() => setActiveTab("site_images")}
              className={`border-r border-strokedark px-6 py-3 text-sm font-medium transition-colors ${
                activeTab === "site_images"
                  ? "bg-primary text-white"
                  : "text-white hover:bg-meta-4"
              }`}
            >
              Site Images
            </button>

            <button
              onClick={() => setActiveTab("email_template")}
              className={`border-r border-strokedark px-6 py-3 text-sm font-medium transition-colors ${
                activeTab === "email_template"
                  ? "bg-primary text-white"
                  : "text-white hover:bg-meta-4"
              }`}
            >
              Email Template
            </button>

            <button
              onClick={() => setActiveTab("project_management")}
              className={`border-r border-strokedark px-6 py-3 text-sm font-medium transition-colors ${
                activeTab === "project_management"
                  ? "bg-primary text-white"
                  : "text-white hover:bg-meta-4"
              }`}
            >
              Mix Seasons Management
            </button>
          </div>

          {/* Tab Content */}
          {activeTab === "site_images" && (
            <div className="p-4 md:p-6 2xl:p-10">
              <div className="flex flex-col gap-4 md:flex-row">
                {/* Site Logo Section */}
                <div className="w-full rounded-md border-2 border-strokedark p-4 md:w-1/2">
                  <label className="mb-2.5 block text-sm font-medium text-white">
                    Site Logo
                  </label>
                  <PhotoUpload2
                    maxFileSize={1}
                    setFileUpload={handleSiteLogoUpload}
                  />
                  {siteLogoUrl && (
                    <>
                      <span className="text-xs italic text-gray-400">
                        Change site logo
                      </span>
                      <div className="mb-2">
                        <img
                          crossOrigin="anonymous"
                          className="h-20 w-36"
                          src={`https://app.equalityrecords.com/${siteLogoUrl}`}
                          alt="site_logo"
                        />
                      </div>
                    </>
                  )}
                  <span className="text-xs italic text-gray-400">
                    Note: Please upload a square image (1:1) for best results or
                    maintain 3:1 aspect ratio.
                  </span>
                </div>

                {/* Landing Image Section */}
                <div className="w-full rounded-md border-2 border-strokedark p-4 md:w-1/2">
                  <label className="mb-2.5 block text-sm font-medium text-white">
                    Landing Image
                  </label>
                  <PhotoUpload2
                    maxFileSize={3}
                    setFileUpload={handleLandingImageUrlUpload}
                  />
                  {landingImageUrl && (
                    <>
                      <span className="text-xs italic text-gray-400">
                        Change landing image
                      </span>
                      <div className="mb-2">
                        <img
                          crossOrigin="anonymous"
                          className="h-40 w-32"
                          src={`https://app.equalityrecords.com/${landingImageUrl}`}
                          alt="landing_image"
                        />
                      </div>
                    </>
                  )}
                  <span className="text-xs italic text-gray-400">
                    Note: Please maintain 1:3 aspect ratio.
                  </span>
                </div>
              </div>
            </div>
          )}

          {activeTab === "email_template" && (
            <div className="p-4 md:p-6 2xl:p-10">
              <div className="flex flex-col gap-4">
                <h4 className="text-xl font-medium text-white">
                  Survey Email Template
                </h4>
                <div className="flex flex-col gap-4 md:flex-row">
                  <SunEditor
                    width="100%"
                    height="220px"
                    onChange={(newContent) => {
                      setContent(newContent);
                      setHtml(newContent);
                    }}
                    getSunEditorInstance={getSunEditorInstance}
                    setOptions={{ buttonList: buttonList.complex }}
                  />
                </div>
                <div className="mt-2">
                  <button
                    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"
                    onClick={() => updateSurveyEmailTemplate()}
                  >
                    Update
                  </button>
                </div>
              </div>
            </div>
          )}

          {activeTab === "project_management" && (
            <div className="p-4 md:p-6 2xl:p-10">
              <div className="flex flex-col gap-4">
                <h4 className="text-xl font-medium text-white">
                  Delete All Projects for Member within Certain Mix Season
                </h4>
                <div className="flex w-1/2 flex-col gap-4">
                  <div>
                    <label className="mb-2.5 block text-sm font-medium text-white">
                      Select Member
                    </label>
                    <CustomSelect2
                      label="Select Member"
                      value={selectedMemberId}
                      onChange={setSelectedMemberId}
                    >
                      {members.map((elem) => {
                        return (
                          <option value={elem.id}>{elem.user_name}</option>
                        );
                      })}
                    </CustomSelect2>
                  </div>

                  <div>
                    <label className="mb-2.5 block text-sm font-medium text-white">
                      Mix Season
                    </label>
                    <CustomSelect2
                      dropdownRef={dropdownRef}
                      label="Mix Season"
                      value={selectedMixSeason}
                      onChange={setSelectedMixSeason}
                    >
                      {mixSeasons?.map((elem) => {
                        return <option value={elem.id}>{elem.name}</option>;
                      })}
                    </CustomSelect2>
                  </div>

                  <div className="mt-2">
                    <button
                      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"
                      onClick={() => {
                        if (!selectedMemberId || !selectedMixSeason) {
                          showToast(
                            globalDispatch,
                            "All fields should be selected",
                            5000,
                            "error"
                          );
                        } else {
                          setShowDeleteProjectModal(true);
                        }
                      }}
                    >
                      Delete
                    </button>
                  </div>
                </div>
              </div>
            </div>
          )}
        </div>
      </div>

      {/* Modals */}
      {showDeleteProjectModal && (
        <ConfirmModal
          confirmText={`Are you sure you want to delete all the projects of this member within the selected mix-season?`}
          setModalClose={handleDeleteProjectModalClose}
          setFormYes={openSecondDelete}
        />
      )}

      {showRealProjectModal && (
        <DuoConfirmModal
          confirmText={`Are you sure you want to delete all the projects of this member within the selected mix-season? This action cannot be undone.`}
          setModalClose={handleRealProjectModalClose}
          setFormYes={handleDeleteProject}
        />
      )}
    </>
  );
};

export default ListAdminSettingPage;
