"use client"; // /components/main/uebersicht/Last20MessagesTable.tsx
import React, { useEffect } from "react";
import { useSelector, useDispatch } from "react-redux";
import { RootState } from "../../../redux/store";
import { setLast20Messages } from "../../../redux/slices/last20MessagesSlice";

type Props = {
  className?: string;
};

const Last20MessagesTable: React.FC<Props> = ({ className }) => {
  const dispatch = useDispatch();

  const rawLast20Messages = useSelector(
    (state: RootState) => state.last20MessagesSlice.last20Messages
  );

  useEffect(() => {
    const loadWindowMessages = () => {
      if (typeof window !== "undefined" && (window as any).win_last20Messages) {
        dispatch(setLast20Messages((window as any).win_last20Messages));
      }
    };

    loadWindowMessages();
    const interval = setInterval(loadWindowMessages, 1000);
    return () => clearInterval(interval);
  }, [dispatch]);

  const parseMessages = (messages: string | null) => {
    if (!messages) return [];

    return messages
      .split("<tr>")
      .slice(1)
      .map((row) =>
        row
          .replace(/<\/tr>/, "")
          .split("</td><td>")
          .map((col) => col.replace(/<[^>]+>/g, ""))
      );
  };

  const allMessages = parseMessages(rawLast20Messages);

  return (
    <div className={`bg-white  p-1 rounded-lg overflow-auto ${className}`}>
      {/*     <h1 className="text-xl font-bold mb-4">Letzte 20 Meldungen</h1> */}

      <div className="overflow-x-auto overflow-y-auto border rounded shadow-sm h-[95%] pt-1">
        <table className="min-w-full border">
          <thead className="bg-gray-100 text-left sticky top-0 z-10">
            <tr>
              <th className="p-2 border">ID</th>
              <th className="p-2 border">Modul</th>
              <th className="p-2 border">Zeitstempel</th>
              <th className="p-2 border">Meldung</th>
              <th className="p-2 border">Status</th>
            </tr>
          </thead>
          <tbody>
            {allMessages.length === 0 ? (
              <tr>
                <td
                  colSpan={5}
                  className="text-center italic text-gray-500 p-4"
                >
                  Keine Meldungen verfügbar.
                </td>
              </tr>
            ) : (
              allMessages.map((msg, index) => (
                <tr key={index} className="hover:bg-gray-50">
                  <td className="border p-2">{msg[0]}</td>
                  <td className="border p-2">{msg[1]}</td>
                  <td className="border p-2 whitespace-nowrap">{msg[2]}</td>

                  <td className="border p-2">{msg[3]}</td>
                  <td className="border p-2">{msg[4]}</td>
                </tr>
              ))
            )}
          </tbody>
        </table>
      </div>
    </div>
  );
};

export default Last20MessagesTable;
