"use client";
import React, { useEffect, useState } from "react";
import { useDispatch, useSelector } from "react-redux";
import { getMessagesThunk } from "@/redux/thunks/getMessagesThunk";
import type { AppDispatch } from "@/redux/store";
import type { RootState } from "@/redux/store";
import DateRangePickerMeldungen from "./DateRangePickerMeldungen";
import MeldungenTabelle from "./MeldungenTabelle";

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

export default function MeldungenView() {
  const dispatch = useDispatch<AppDispatch>();
  const messages = useSelector((state: RootState) => state.messages.data);

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

  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)]">
      <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 px-4 py-3 rounded h-fit ml-6"
        >
          <option value="Alle">Alle Quellen</option>
          {allSources.map((src) => (
            <option key={String(src)} value={String(src)}>
              {String(src)}
            </option>
          ))}
        </select>
      </div>

      <MeldungenTabelle messages={filteredMessages} />
    </div>
  );
}
