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";
import { generateUniqueId } from "../../../../functions/generateUniqueId";

const VersionHistory = () => {
  const userName = localStorage.getItem("userName") ?? "Anonymous";
  const { versions, addVersion, setVersions, updateVersion } =
    useVersionStore();
  const [selectedVersion, setSelectedVersion] = useState(
    versions.length > 0 ? versions[0] : null
  );

  const addNewVersion = () => {
    const newVersion = {
      id: generateUniqueId(),
      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);
  };

  const handleSelectVersion = (version: any) => {
    setSelectedVersion(version);
    const reordered = [version, ...versions.filter((v) => v.id !== version.id)];
    setVersions(reordered);
  };

  const handleVersionNameChange = (newName: string, versionId: string) => {
    const updated = versions.map((v) =>
      v.id === versionId ? { ...v, versionName: newName } : v
    );
    setVersions(updated);
    updateVersion(versionId, { versionName: newName });
  };

  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 */}
      <div className="saved-versions-list">
        {versions.length === 0 ? (
          <div className="no-versions-message">No saved versions</div>
        ) : (
          versions.map((version) => (
            <button
              key={version.id}
              className="saved-version"
              onClick={() => handleSelectVersion(version)}
            >
              <div className="version-name">{version.versionLabel}</div>
              <div className="version-details">
                <div className="details">
                  <span className="timestamp">
                    {version.versionName ? (
                      <RenameInput
                        value={version.versionName}
                        onRename={(newName) =>
                          handleVersionNameChange(newName, version.id)
                        }
                      />
                    ) : (
                      <RenameInput
                        value={version.timestamp}
                        onRename={(newName) =>
                          handleVersionNameChange(newName, version.id)
                        }
                      />
                    )}
                  </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;
