import React, { useEffect, useState } from "react";
import {
  LogListIcon,
  CloseIcon,
  ExpandIcon2,
} from "../../icons/ExportCommonIcons"; // Adjust path as needed
import { LogEntry, useLogger } from "./LoggerContext";
import { GetLogIcon } from "../../footer/getLogIcons";
import { RenderInNewWindow } from "../../templates/CreateNewWindow";

// --- Logs Component ---
type LogsProps = {
  selectedTab: "all" | "info" | "warning" | "error";
  setSelectedTab: (tab: "all" | "info" | "warning" | "error") => void;
  clear: () => void;
  filteredLogs: LogEntry[];
  formatTimestamp: (date: Date) => string;
};

const Logs: React.FC<LogsProps> = ({
  selectedTab,
  setSelectedTab,
  clear,
  filteredLogs,
  formatTimestamp,
}) => {
  return (
    <>
      <div className="log-nav-container">
        <div className="log-nav-wrapper">
          {["all", "info", "warning", "error"].map((type) => (
            <button
              id="log-type"
              title="log-type"
              key={type}
              className={`log-nav ${selectedTab === type ? "active" : ""}`}
              onClick={() => setSelectedTab(type as any)}
            >
              {`${type.charAt(0).toUpperCase() + type.slice(1)} Logs`}
            </button>
          ))}
        </div>
        <button
          id="clean-btn"
          title="clear-btn"
          className="clear-button"
          onClick={clear}
        >
          clear
        </button>
      </div>

      {/* Log Entries */}
      <div className="log-entry-wrapper">
        {filteredLogs.length > 0 ? (
          filteredLogs.map((log) => (
            <div key={log.id} className={`log-entry ${log.type}`}>
              <div className="log-icon">{GetLogIcon(log.type)}</div>
              <div className="log-entry-message-container">
                <div className="log-entry-message">{log.message}</div>
                <div className="message-time">
                  {formatTimestamp(log.timestamp)}
                </div>
              </div>
            </div>
          ))
        ) : (
          <div className="no-log">
            There are no logs to display at the moment.
          </div>
        )}
      </div>
    </>
  );
};

// --- LogList Component ---
const LogList: React.FC = () => {
  const {
    logs,
    clear,
    setIsLogListVisible,
    isLogListVisible,
    selectedTab,
    setSelectedTab,
  } = useLogger();

  const formatTimestamp = (date: Date) => new Date(date).toLocaleTimeString();
  const [open, setOpen] = useState(false);

  const filteredLogs =
    selectedTab === "all"
      ? [...logs].reverse()
      : [...logs].filter((log) => log.type === selectedTab).reverse();

  useEffect(() => {
    if (isLogListVisible && logs.length > 0) {
      const lastLog = logs[logs.length - 1];
      const validTypes = ["all", "info", "warning", "error"];
      if (validTypes.includes(lastLog.type)) {
        setSelectedTab(lastLog.type as any);
      } else {
        setSelectedTab("all");
      }
    }
    // eslint-disable-next-line
  }, [isLogListVisible]);

  return (
    <>
      {!open ? (
        <div
          className="log-list-container"
          onClick={() => setIsLogListVisible(false)}
        >
          {/* eslint-disable-next-line */}
          <div
            className="log-list-wrapper"
            onClick={(e) => {
              e.stopPropagation();
            }}
          >
            <div className="log-header">
              <div className="log-header-wrapper">
                <div className="icon">
                  <LogListIcon />
                </div>
                <div className="head">Log List</div>
              </div>
              <div className="action-buttons-container">
                <button
                  id="expand-log-btn"
                  title="open in new tab"
                  className="expand-btn"
                  onClick={() => {
                    setOpen(true);
                  }}
                >
                  <ExpandIcon2 />
                </button>
                <button
                  id="close-btn"
                  title="close"
                  className="close"
                  onClick={() => setIsLogListVisible(false)}
                >
                  <CloseIcon />
                </button>
              </div>
            </div>

            {/* Logs Section */}
            <Logs
              selectedTab={selectedTab as any}
              setSelectedTab={setSelectedTab as any}
              clear={clear}
              filteredLogs={filteredLogs}
              formatTimestamp={formatTimestamp}
            />
          </div>
        </div>
      ) : (
        <RenderInNewWindow
          title="Log list"
          theme={localStorage.getItem("theme")}
          onClose={() => {
            setOpen(false);
            setIsLogListVisible(false);
          }}
        >
          <div className="log-list-new-window-wrapper">
            <Logs
              selectedTab={selectedTab as any}
              setSelectedTab={setSelectedTab as any}
              clear={clear}
              filteredLogs={filteredLogs}
              formatTimestamp={formatTimestamp}
            />
          </div>
        </RenderInNewWindow>
      )}
    </>
  );
};

export default LogList;
