import React, { useState, useEffect, useRef } from "react";
import { useVersionStore } from "../../../../store/builder/store";
import {
  CloseIcon,
  SaveIcon,
  SaveVersionIcon,
} from "../../../icons/ExportCommonIcons";
import { RenameIcon } from "../../../icons/ContextMenuIcons";
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 prevVersionCount = useRef(versions.length);
  const dismissTimerRef = useRef<NodeJS.Timeout | null>(null);

  const latestVersion = versions?.[0];

  // Clear dismiss timer when component unmounts
  useEffect(() => {
    return () => {
      if (dismissTimerRef.current) clearTimeout(dismissTimerRef.current);
    };
  }, []);

  // Handle new version notification and setup dismiss timer
  useEffect(() => {
    if (versions.length > prevVersionCount.current) {
      setShowNotification(true);
      setShouldDismiss(false);
      setIsEditing(false);
      setNewName(versions[0].versionName ?? "");
      setDescription(versions[0]?.description ?? "");

      // Only start dismiss timer if not in edit mode
      if (!isEditing) {
        startDismissTimer();
      }

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

  // Start or restart the dismiss timer
  const startDismissTimer = (delay = 5000) => {
    if (dismissTimerRef.current) clearTimeout(dismissTimerRef.current);
    dismissTimerRef.current = setTimeout(() => {
      console.log("isEditing: ", isEditing);
      setShouldDismiss(true);
    }, delay);
  };

  // Hide notification after dismiss animation delay
  useEffect(() => {
    if (shouldDismiss) {
      const timer = setTimeout(() => setShowNotification(false), 200);
      return () => clearTimeout(timer);
    }
  }, [shouldDismiss]);

  const handleEditName = () => {
    setIsEditing(true);
    setNewName(latestVersion?.versionName ?? "");
    setDescription(latestVersion?.description ?? "");

    // Clear any existing dismiss timer when editing starts
    if (dismissTimerRef.current) {
      clearTimeout(dismissTimerRef.current);
      dismissTimerRef.current = null;
    }
  };

  const handleFinishEdit = () => {
    if (latestVersion) {
      updateVersion(latestVersion.id, {
        versionName: newName,
        description,
      });
      console.log("saved");
      startDismissTimer(); // Restart 5s timer after save
    }
    startDismissTimer(); // Restart 5s timer after save
    setIsEditing(false);
  };

  const handleCancel = () => {
    setIsEditing(false);
    startDismissTimer(); // Restart 5s timer after cancel
  };

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

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

  return (
    <div className={`versionSaved ${shouldDismiss ? "dismissing" : ""}`}>
      <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>

      {isEditing && (
        <RenderOverlay>
          <div className="edit-version-popup-wrapper">
            <div className="details-wrapper-popup-container">
              <div className="header-wrapper">
                <RenameIcon />
                <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">
                  {/* <input
                    type="text"
                    value={description}
                    onChange={(e) => setDescription(e.target.value)}
                    placeholder="Add description"
                  /> */}
                  <textarea
                    value={description}
                    onChange={(e) => setDescription(e.target.value)}
                    placeholder="Add description"
                  />
                </div>
              </div>
              <div className="btn-wrapper">
                <button className="cancel" onClick={handleCancel}>
                  Cancel
                </button>
                <button className="save" onClick={handleFinishEdit}>
                  Save
                </button>
              </div>
            </div>
          </div>
        </RenderOverlay>
      )}
    </div>
  );
};

export default VersionSaved;
