"use client";
// /pages/meldungen.tsx
import React, { 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);

  // Datum initialisieren: von = heute - 30 Tage, bis = heute
  const today = new Date();
  const prior30 = new Date();
  prior30.setDate(today.getDate() - 30);

  const formatDate = (d: Date) => d.toISOString().split("T")[0];

  const [fromDate, setFromDate] = useState<string>(formatDate(prior30));
  const [toDate, setToDate] = useState<string>(formatDate(today));

  const fetchMessages = async () => {
    const from = new Date(fromDate);
    const to = new Date(toDate);

    const fy = from.getFullYear();
    const fm = String(from.getMonth() + 1).padStart(2, "0");
    const fd = String(from.getDate()).padStart(2, "0");
    const ty = to.getFullYear();
    const tm = String(to.getMonth() + 1).padStart(2, "0");
    const td = String(to.getDate()).padStart(2, "0");

    const isDev =
      typeof window !== "undefined" && window.location.hostname === "localhost";

    const url = isDev
      ? `/api/cpl/messages?MSS1=${fy};${fm};${fd};${ty};${tm};${td};All`
      : `/CPL?Service/ae.ACP&MSS1=${fy};${fm};${fd};${ty};${tm};${td};All`;

    try {
      const res = await fetch(url);
      const raw = await res.json();
      console.log("URL:", url);
      console.log("Daten vom Server:", raw);

      const data = Array.isArray(raw) ? raw : raw.data;
      if (!Array.isArray(data)) {
        console.error("Die empfangenen Daten sind kein Array:", data);
        return;
      }

      setMessages(data);
      setCurrentPage(1);
    } catch (err) {
      console.error("Fehler beim Laden der Meldungen:", err);
    }
  };

  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">Berichte</h1>

      <div className="flex flex-wrap gap-4 mb-4 items-end">
        <div>
          <label className="block text-sm font-medium mb-1">Von Datum</label>
          <input
            type="date"
            value={fromDate}
            onChange={(e) => setFromDate(e.target.value)}
            className="border px-2 py-1 rounded"
          />
        </div>
        <div>
          <label className="block text-sm font-medium mb-1">Bis Datum</label>
          <input
            type="date"
            value={toDate}
            onChange={(e) => setToDate(e.target.value)}
            className="border px-2 py-1 rounded"
          />
        </div>
        <button
          onClick={fetchMessages}
          className="bg-littwin-blue text-white px-4 py-2 rounded "
        >
          Anzeigen
        </button>
      </div>

      <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>
        {messages.length === 0 && (
          <div className="mt-4 text-center text-gray-500 italic">
            Keine Meldungen im gewählten Zeitraum vorhanden.
          </div>
        )}
      </div>

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