import { useEffect, useState } from "react";
import {
  FinishEditIcon,
  RenameVersionIcon,
} from "../../../icons/ExportCommonIcons";
import RenderOverlay from "../../../templates/Overlay";
import { useVersionHistoryStore } from "../../../../store/builder/useVersionHistoryStore";
import { createVersionApi } from "../../../../services/factoryBuilder/versionControl/addVersionApi";
import { useParams } from "react-router-dom";
import { getUserData } from "../../../../functions/getUserData";
import { useVersionContext } from "../../../../modules/builder/version/versionContext";

const VersionSaved = () => {
  const { versionHistory, addVersion, createNewVersion, setCreateNewVersion } = useVersionHistoryStore();
  const { selectedVersionStore } = useVersionContext();
  const { setSelectedVersion } = selectedVersionStore();
  const [newName, setNewName] = useState(new Date().toLocaleString("en-US", {
    month: "short",
    day: "numeric",
    year: "numeric",
    hour: "numeric",
    minute: "2-digit",
  }));
  const [description, setDescription] = useState("");
  const [showSaveFinish, setSaveFinish] = useState(false);
  const { projectId } = useParams();
  const { userId } = getUserData();

  const latestVersion = versionHistory?.[0];

  useEffect(() => {
    if (createNewVersion) {
      const defaultName = new Date().toLocaleString("en-US", {
        month: "short",
        day: "numeric",
        year: "numeric",
        hour: "numeric",
        minute: "2-digit",
      });
      setNewName(defaultName);
      setDescription("");
    }
  }, [createNewVersion]);

  const handleSave = () => {
    if (!latestVersion || !projectId) return;

    const updatedName = (newName.trim() || latestVersion.versionName) ?? latestVersion.timeStamp;
    const updatedDescription = (description.trim() || latestVersion.versionName) ?? latestVersion.timeStamp;

    createVersionApi(projectId, userId, latestVersion.versionId, updatedName, updatedDescription).then((data) => {
      setSaveFinish(true);
      setCreateNewVersion(false);

      addVersion({
        version: data.version,
        versionId: data.versionId,
        versionName: data.versionName,
        versionDescription: data.description,
        timeStamp: data.createdAt,
        createdBy: data.createdBy.userName
      })

      setSelectedVersion({
        version: data.version,
        versionId: data.versionId,
        versionName: data.versionName,
        versionDescription: data.description,
        timeStamp: data.createdAt,
        createdBy: data.createdBy.userName
      })

      setTimeout(() => {
        setSaveFinish(false);
      }, 3000);
    }).catch((err) => {
      setSaveFinish(false);
      setCreateNewVersion(false);
    })
  };

  const handleCancel = () => {
    setSaveFinish(false);
    setCreateNewVersion(false);
  };

  if (!latestVersion) return null;

  return (
    <div className={`versionSaved`}>
      {createNewVersion &&
        <RenderOverlay>
          <div className="edit-version-popup-wrapper">
            <div className="details-wrapper-popup-container">
              <div className="header-wrapper">
                <RenameVersionIcon />
                <div className="label">Create Version</div>
              </div>
              <div className="details-wrapper">
                <div className="version-name">
                  <input
                    type="text"
                    value={newName}
                    onChange={(e) => setNewName(e.target.value)}
                    placeholder="Enter new version name"
                  />
                  <div className="label">
                    by @{latestVersion.createdBy}{" "}{new Date(latestVersion.timeStamp).toLocaleDateString("en-US", {
                      year: "numeric",
                      month: "long",
                      day: "2-digit",
                    })}
                  </div>
                </div>
                <div className="version-description">
                  <textarea
                    value={description}
                    onChange={(e) => setDescription(e.target.value)}
                    placeholder="Add description"
                    style={{ resize: "none" }}
                  />
                </div>
              </div>
              <div className="btn-wrapper">
                <button className="cancel" onClick={handleCancel}>
                  Cancel
                </button>
                <button className="save" onClick={handleSave}>
                  Save
                </button>
              </div>
            </div>
          </div>
        </RenderOverlay>
      }

      {showSaveFinish && (
        <RenderOverlay>
          <div className="finishEdit-version-popup-wrapper">
            <div className="finishEdit-wrapper-popup-container">
              <div className="icon">
                <FinishEditIcon />
              </div>
              <div className="versionname">
                {newName.trim()}
              </div>
              <div className="success-message">Saved Successfully!</div>
            </div>
          </div>
        </RenderOverlay>
      )}
    </div>
  );
};

export default VersionSaved;
