"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";
import { Listbox } from "@headlessui/react";

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

  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 Quellen"
      ? messages
      : messages.filter((m: Meldung) => m.i === sourceFilter);

  const allSources = Array.from(
    new Set(messages.map((m: Meldung) => m.i))
  ).sort();
  const sources = ["Alle Quellen", ...allSources];

  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>

        <Listbox value={sourceFilter} onChange={setSourceFilter}>
          <div className="relative ml-6 w-64">
            <Listbox.Button className="w-full border px-4 py-3 rounded text-left bg-white flex justify-between items-center">
              <span>{sourceFilter}</span>
              <svg
                className="w-5 h-5 text-gray-400"
                xmlns="http://www.w3.org/2000/svg"
                viewBox="0 0 20 20"
                fill="currentColor"
                aria-hidden="true"
              >
                <path
                  fillRule="evenodd"
                  d="M5.23 7.21a.75.75 0 011.06.02L10 10.585l3.71-3.355a.75.75 0 111.02 1.1l-4.25 3.85a.75.75 0 01-1.02 0l-4.25-3.85a.75.75 0 01.02-1.06z"
                  clipRule="evenodd"
                />
              </svg>
            </Listbox.Button>
            <Listbox.Options className="absolute z-50 mt-1 w-full border rounded bg-white shadow max-h-60 overflow-auto">
              {sources.map((src) => (
                <Listbox.Option
                  key={src}
                  value={src}
                  className={({ selected, active }) =>
                    `px-4 py-2 cursor-pointer ${
                      selected
                        ? "bg-littwin-blue text-white"
                        : active
                        ? "bg-blue-100"
                        : ""
                    }`
                  }
                >
                  {src}
                </Listbox.Option>
              ))}
            </Listbox.Options>
          </div>
        </Listbox>
      </div>

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