"use client";
// /pages/meldungen.tsx
import React, { useState, useEffect } from "react";
import DateRangePickerMeldungen from "@/components/main/meldungen/DateRangePickerMeldungen";

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

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

  const [sourceFilter, setSourceFilter] = useState<string>("Alle");

  // 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";
    //http://10.10.0.118/CPL?Service/empty.ACP&MSS1=2025;06;01;2025;06;26;All
    const url = isDev
      ? `/api/cpl/messages`
      : `/CPL?Service/ae.ACP&MSS1=${fy};${fm};${fd};${ty};${tm};${td};All`;

    try {
      const res = await fetch(url);
      const raw = await res.json();
      const data = Array.isArray(raw) ? raw : raw.data;
      if (!Array.isArray(data)) {
        console.error("Die empfangenen Daten sind kein Array:", data);
        return;
      }
      setMessages(data);
    } catch (err) {
      console.error("Fehler beim Laden der Meldungen:", err);
    }
  };

  const filteredMessages =
    sourceFilter === "Alle"
      ? messages
      : messages.filter((m) => m.i === sourceFilter);

  const allSources = Array.from(new Set(messages.map((m) => m.i))).sort();
  // einmal beim laden de Seite die Meldungen abrufen
  useEffect(() => {
    fetchMessages();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

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

      <div className="flex flex-wrap gap-6 mb-6 items-end">
        <DateRangePickerMeldungen
          fromDate={fromDate}
          toDate={toDate}
          setFromDate={setFromDate}
          setToDate={setToDate}
        />
        <button
          onClick={fetchMessages}
          className="bg-littwin-blue text-white px-4 py-2 rounded h-fit"
        >
          Anzeigen
        </button>
        <select
          value={sourceFilter}
          onChange={(e) => setSourceFilter(e.target.value)}
          className=" border border-solid border-spacing-1 px-4 py-3 rounded h-fit ml-6"
        >
          <option value="Alle">Alle Quellen</option>
          {allSources.map((src) => (
            <option key={src} value={src}>
              {src}
            </option>
          ))}
        </select>
      </div>

      <div className="overflow-auto max-h-[80vh]">
        <table className="min-w-full border">
          <thead className="bg-gray-100 text-left sticky top-0 z-10">
            <tr>
              <th className="p-2 border">Prio</th>
              <th className="p-2 border">Zeitstempel</th>
              <th className="p-2 border">Quelle</th>
              <th className="p-2 border">Meldung</th>
              <th className="p-2 border">Status</th>
            </tr>
          </thead>
          <tbody>
            {filteredMessages.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.i}</td>
                <td className="border p-2">{msg.m}</td>
                <td className="border p-2">{msg.s}</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>
  );
}
