import React, { useState } from "react";
import {
  AddIcon,
  ArrowIcon,
  CloseIcon,
  KebabIcon,
  LocationIcon,
} from "../../../icons/ExportCommonIcons";
import RenameInput from "../../../ui/inputs/RenameInput";
import { useVersionStore } from "../../../../store/builder/store";

const VersionHistory = () => {
  const userName = localStorage.getItem("userName") ?? "Anonymous";

  const { versions, addVersion, setVersions } = useVersionStore();
  const [selectedVersion, setSelectedVersion] = useState(
    versions.length > 0 ? versions[0] : null
  );

  const addNewVersion = () => {
    const newVersion = {
      id: crypto.randomUUID(),
      versionLabel: `v${versions.length + 1}.0`,
      versionName: "",
      timestamp: new Date().toLocaleDateString("en-US", {
        year: "numeric",
        month: "long",
        day: "2-digit",
      }),
      savedBy: userName,
    };

    const newVersions = [newVersion, ...versions];
    addVersion(newVersion);
    setSelectedVersion(newVersion);
    setVersions(newVersions); // bring new one to top
  };

  const handleSelectVersion = (version: any) => {
    setSelectedVersion(version);

    // Move selected version to top, keep others in same order
    const reordered = [version, ...versions.filter((v) => v.id !== version.id)];
    setVersions(reordered);
  };

  const handleTimestampChange = (newTimestamp: string, index: number) => {
    const updated = [...versions];
    updated[index].timestamp = newTimestamp;

    console.warn("Timestamp updated locally but not persisted in store.");
    setVersions(updated); // Optional: persist timestamp change
  };

  return (
    <div className="version-history-container">
      {/* Header */}
      <div className="version-history-header">
        <div className="version-history-title">Version History</div>
        <div className="version-history-icons">
          <button
            id="add-version"
            className="icon add-icon"
            onClick={addNewVersion}
          >
            <AddIcon />
          </button>
          <div id="version-kebab" className="icon kebab-icon">
            <KebabIcon />
          </div>
          <div id="version-close" className="icon close-icon">
            <CloseIcon />
          </div>
        </div>
      </div>

      {/* Shortcut Info */}
      <div className="version-history-shortcut-info">
        <div className="info-icon">i</div>
        <div className="shortcut-text">
          Press Ctrl + Alt + S to add to version history while editing
        </div>
      </div>

      {/* Current Version Display */}
      {selectedVersion && (
        <div className="version-history-location">
          <div className="location-label">
            <LocationIcon />
          </div>
          <div className="location-details">
            <div className="current-version">
              Current Version ({selectedVersion.versionLabel})
            </div>
            <div className="saved-history-count">
              {versions.length} Saved History
            </div>
          </div>
        </div>
      )}

      {/* Versions List or No Versions Message */}
      <div className="saved-versions-list">
        {versions.length === 0 ? (
          <div className="no-versions-message">No saved versions</div>
        ) : (
          versions.map((version, index) => (
            <button
              key={version.id}
              className="saved-version"
              id={`${version.versionName}-${index}`}
              onClick={() => handleSelectVersion(version)}
            >
              <div className="version-name">{version.versionLabel}</div>
              <div className="version-details">
                <div className="details">
                  <span className="timestamp">
                    <RenameInput
                      value={version.timestamp}
                      onRename={(newTimestamp) =>
                        handleTimestampChange(newTimestamp, index)
                      }
                    />
                  </span>
                  <span className="saved-by">
                    <div className="user-profile">{version.savedBy[0]}</div>
                    <div className="user-name">{version.savedBy}</div>
                  </span>
                </div>
                <ArrowIcon />
              </div>
            </button>
          ))
        )}
      </div>
    </div>
  );
};

export default VersionHistory;
