"use client";
// /pages/meldungen.tsx
import React, { useState, useEffect } from "react";
import DateRangePickerMeldungen from "@/components/main/reports/DateRangePickerMeldungen";
import { useSelector, useDispatch } from "react-redux";
import { getMessagesThunk } from "@/redux/thunks/getMessagesThunk";

type Meldung = {
  t: string;
  s: number;
  c: string;
  m: string;
  i: string;
  v: string; // NEU: für Anzeige
};

export default function Messages() {
  const dispatch = useDispatch();
  const { data: messages, loading } = useSelector(
    (state: any) => state.messages
  );

  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));

  useEffect(() => {
    dispatch(getMessagesThunk({ fromDate, toDate }));
  }, [dispatch, fromDate, toDate]);

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

  const allSources = Array.from(
    new Set(messages.map((m: Meldung) => m.i))
  ).sort();

  return (
    <div className="flex flex-col gap-3 p-4 h-[calc(100vh-13vh-8vh)] laptop:h-[calc(100vh-10vh-5vh)] xl:h-[calc(100vh-10vh-6vh)] laptop:gap-0">
      <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={() => dispatch(getMessagesThunk({ fromDate, toDate }))}
          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">Wert</th> {/* statt Status */}
            </tr>
          </thead>
          <tbody>
            {filteredMessages.map((msg: Meldung, index: number) => (
              <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.v}</td> {/* NEU */}
              </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>
  );
}
