"use client";
import React, { useEffect } from "react";
import { useDispatch, useSelector } from "react-redux";
import { RootState, AppDispatch } from "../../../redux/store";
import { fetchAnalogeEingaengeThunk } from "../../../redux/thunks/fetchAnalogeEingaengeThunk";

export default function AnalogeEingaengeTable({
  setSelectedId,
}: {
  setSelectedId: (id: number) => void;
}) {
  const dispatch = useDispatch<AppDispatch>();

  useEffect(() => {
    dispatch(fetchAnalogeEingaengeThunk());
  }, [dispatch]);

  const analogeEingaenge = useSelector(
    (state: RootState) => state.analogeEingaengeSlice
  );

  return (
    <div className="w-full">
      <div className="bg-white shadow-lg rounded-lg p-4 border border-gray-200">
        <div className="overflow-x-auto">
          <table className="w-full border-collapse border border-gray-300 text-sm md:text-base">
            <thead>
              <tr className="bg-gray-100 text-gray-700">
                <th className="border p-1 text-left">Eingang</th>
                <th className="border p-3 text-left">Messwert</th>
                <th className="border p-3 text-left">Bezeichnung</th>
              </tr>
            </thead>
            <tbody>
              {Object.values(analogeEingaenge)
                .filter((e) => e?.id !== null && e?.id !== undefined)
                .map((e, index) => (
                  <tr
                    key={index}
                    className="hover:bg-gray-100 cursor-pointer transition"
                    onClick={() => setSelectedId(e.id!)}
                  >
                    <td className="border p-3">{e.id ?? "-"}</td>
                    <td className="border p-3">{e.value ?? "-"}</td>
                    <td className="border p-3">{e.name || "----"}</td>
                  </tr>
                ))}
            </tbody>
          </table>
        </div>
      </div>
    </div>
  );
}
