import React, { useState, useEffect, useRef } from "react";
import { useVersionStore } from "../../../../store/builder/store";
import {
  CloseIcon,
  FinishEditIcon,
  RenameVersionIcon,
  SaveIcon,
  SaveVersionIcon,
} from "../../../icons/ExportCommonIcons";
import RenderOverlay from "../../../templates/Overlay";

const VersionSaved = () => {
  const { versions, updateVersion } = useVersionStore();
  const [isEditing, setIsEditing] = useState(false);
  const [shouldDismiss, setShouldDismiss] = useState(false);
  const [showNotification, setShowNotification] = useState(false);
  const [newName, setNewName] = useState("");
  const [description, setDescription] = useState("");
  const [showEditedFinish, setShowEditedFinish] = useState(false);
  const [editedVersionName, setEditedVersionName] = useState("");
  const prevVersionCount = useRef(versions.length);
  const dismissTimerRef = useRef<NodeJS.Timeout | null>(null);

  const latestVersion = versions?.[0];

  useEffect(() => {
    return () => {
      if (dismissTimerRef.current) clearTimeout(dismissTimerRef.current);
    };
  }, []);

  useEffect(() => {
    if (versions.length > prevVersionCount.current && latestVersion) {
      setShowNotification(true);
      setShouldDismiss(false);
      setIsEditing(false);
      setNewName(latestVersion.versionName ?? "");
      setDescription(latestVersion.description ?? "");
      setEditedVersionName(latestVersion.versionName ?? ""); // Initialize editedVersionName

      if (!isEditing) {
        startDismissTimer();
      }

      prevVersionCount.current = versions.length;
    } else if (versions.length < prevVersionCount.current) {
      prevVersionCount.current = versions.length;
    }
  }, [versions, isEditing, latestVersion]);

  const startDismissTimer = (delay = 5000) => {
    if (dismissTimerRef.current) clearTimeout(dismissTimerRef.current);
    dismissTimerRef.current = setTimeout(() => {
      setShouldDismiss(true);
    }, delay);
  };

  useEffect(() => {
    if (shouldDismiss) {
      const timer = setTimeout(() => setShowNotification(false), 200);
      return () => clearTimeout(timer);
    }
  }, [shouldDismiss]);

  const handleEditName = () => {
    if (!latestVersion) return;

    setIsEditing(true);
    setNewName(latestVersion.versionName ?? "");
    setDescription(latestVersion.description ?? "");
    if (dismissTimerRef.current) {
      clearTimeout(dismissTimerRef.current);
      dismissTimerRef.current = null;
    }
  };

  const handleFinishEdit = () => {
    if (!latestVersion) return;

    const updatedName =
      (newName.trim() || latestVersion.versionName) ?? latestVersion.timestamp;
    updateVersion(latestVersion.id, {
      versionName: updatedName,
      description,
    });

    setEditedVersionName(updatedName);
    setIsEditing(false);
    setShowEditedFinish(true);

    setTimeout(() => {
      setShowEditedFinish(false);
    }, 5000);

    startDismissTimer();
  };

  const handleCancel = () => {
    setIsEditing(false);
    startDismissTimer();
  };

  const handleClose = () => {
    setShouldDismiss(true);
    if (dismissTimerRef.current) clearTimeout(dismissTimerRef.current);
  };

  if (!showNotification || !latestVersion) return null;

  return (
    <div className={`versionSaved ${shouldDismiss ? "dismissing" : ""}`}>
      {!isEditing && !showEditedFinish && (
        <div className="versionSaved-wrapper">
          <div className="version-header">
            <div className="header-wrapper">
              <div className="icon">
                <SaveIcon />
              </div>
              <span>Saved New Version</span>
            </div>
            <button className="close-btn" onClick={handleClose}>
              <CloseIcon />
            </button>
          </div>

          <div className="version-details">
            <SaveVersionIcon />
            <div className="details">
              <div className="details-wrapper">
                New Version Created {latestVersion.versionLabel}{" "}
                {latestVersion.timestamp.toUpperCase()}
              </div>
              <button onClick={handleEditName}>Edit name</button>
            </div>
          </div>
        </div>
      )}

      {isEditing && (
        <RenderOverlay>
          <div className="edit-version-popup-wrapper">
            <div className="details-wrapper-popup-container">
              <div className="header-wrapper">
                <RenameVersionIcon />
                <div className="label">Rename 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.savedBy}{" "}
                    {new Date(latestVersion.timestamp).toLocaleString("en-US", {
                      month: "short",
                      day: "numeric",
                      year: "2-digit",
                      hour: "numeric",
                      minute: "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={handleFinishEdit}>
                  Save
                </button>
              </div>
            </div>
          </div>
        </RenderOverlay>
      )}

      {showEditedFinish && (
        <RenderOverlay>
          <div className="finishEdit-version-popup-wrapper">
            <div className="finishEdit-wrapper-popup-container">
              <div className="icon">
                <FinishEditIcon />
              </div>
              <div className="versionname">
                {editedVersionName || latestVersion.versionName}
              </div>
              <div className="success-message">Saved Successfully!</div>
            </div>
          </div>
        </RenderOverlay>
      )}
    </div>
  );
};

export default VersionSaved;
