// /pages/meldungen.tsx
"use client";

import React, { useEffect, useState } from "react";

type Meldung = {
  t: string;
  s: number;
  c: string;
  m: string;
  i: string;
};

const ITEMS_PER_PAGE = 10;

export default function Messages() {
  const [messages, setMessages] = useState<Meldung[]>([]);
  const [currentPage, setCurrentPage] = useState(1);

  useEffect(() => {
    const fetchMessages = async () => {
      // https://10.10.0.222/CPL?Service/ae.ACP&MSS1=2025;01;01;2025;2;28;All
      try {
        const res = await fetch("/CPLmockData/meldungen/messages.json");
        const data = await res.json();
        setMessages(data);
      } catch (err) {
        console.error("Fehler beim Laden der Meldungen:", err);
      }
    };

    fetchMessages();
  }, []);

  const totalPages = Math.ceil(messages.length / ITEMS_PER_PAGE);
  const currentMessages = messages.slice(
    (currentPage - 1) * ITEMS_PER_PAGE,
    currentPage * ITEMS_PER_PAGE
  );

  return (
    <div className="p-4">
      <h1 className="text-xl font-bold mb-4">Meldungen</h1>

      <div className="overflow-x-auto">
        <table className="min-w-full border">
          <thead className="bg-gray-100 text-left">
            <tr>
              <th className="p-2 border">Status</th>
              <th className="p-2 border">Zeitstempel</th>
              <th className="p-2 border">Gewicht</th>
              <th className="p-2 border">Text</th>
              <th className="p-2 border">Quelle</th>
            </tr>
          </thead>
          <tbody>
            {currentMessages.map((msg, index) => (
              <tr key={index} className="hover:bg-gray-50">
                <td className="border p-2">
                  <div
                    className="w-4 h-4 rounded"
                    style={{ backgroundColor: msg.c }}
                  ></div>
                </td>
                <td className="border p-2">{msg.t}</td>
                <td className="border p-2">{msg.s}</td>
                <td className="border p-2">{msg.m}</td>
                <td className="border p-2">{msg.i}</td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>

      {/* Pagination */}
      <div className="flex justify-between items-center mt-4">
        <button
          onClick={() => setCurrentPage((prev) => Math.max(prev - 1, 1))}
          disabled={currentPage === 1}
          className="bg-blue-500 text-white px-4 py-2 rounded disabled:opacity-50"
        >
          Zurück
        </button>
        <span>
          Seite {currentPage} von {totalPages}
        </span>
        <button
          onClick={() =>
            setCurrentPage((prev) => Math.min(prev + 1, totalPages))
          }
          disabled={currentPage === totalPages}
          className="bg-blue-500 text-white px-4 py-2 rounded disabled:opacity-50"
        >
          Weiter
        </button>
      </div>
    </div>
  );
}
