"use client";
// /components/main/settingsPageComponents/UserManagementSettings.tsx
import React, { useState } from "react";
import { useDispatch } from "react-redux";
import { AppDispatch } from "../../../redux/store";
import { useAdminAuth } from "./hooks/useAdminAuth";
import handleAdminLogin from "./handlers/handleAdminLogin";

const UserManagementSettings: React.FC = () => {
  const dispatch = useDispatch<AppDispatch>();
  const { isAdminLoggedIn, logoutAdmin } = useAdminAuth(true);

  const [username, setUsername] = useState("");
  const [password, setPassword] = useState("");
  const [loginSuccess, setLoginSuccess] = useState(false);
  const [error, setError] = useState("");

  const handleLogin = async () => {
    handleAdminLogin(
      username,
      password,
      () => {
        setLoginSuccess(true);
        setError("");
      },
      (errorMsg) => {
        setLoginSuccess(false);
        setError(errorMsg);
      },
      dispatch
    );
  };

  return (
    <div className="p-6 md:p-3 bg-gray-100 max-w-5xl mr-auto">
      <h2 className="text-sm md:text-md font-bold mb-4">Login Admin-Bereich</h2>

      {/* Admin Login/Logout */}
      <div className="flex flex-col gap-1">
        {isAdminLoggedIn ? (
          <button
            type="button"
            className="bg-littwin-blue text-white px-4 py-2 h-8 text-xs rounded whitespace-nowrap"
            onClick={logoutAdmin}
          >
            Admin abmelden
          </button>
        ) : (
          <>
            <div className="flex flex-row gap-3">
              <input
                type="text"
                placeholder="Benutzername"
                className="border border-gray-300 rounded h-8 p-1 w-full text-xs"
                value={username}
                onChange={(e) => setUsername(e.target.value)}
              />
              <input
                type="password"
                placeholder="Passwort"
                className="border border-gray-300 rounded h-8 p-1 w-full text-xs"
                value={password}
                onChange={(e) => setPassword(e.target.value)}
              />
              <button
                type="button"
                className="bg-littwin-blue text-white px-4 py-2 h-8 text-xs rounded whitespace-nowrap"
                onClick={handleLogin}
              >
                Admin anmelden
              </button>
            </div>
          </>
        )}
      </div>

      {loginSuccess && (
        <p className="text-green-600 text-xs mt-2">Login erfolgreich!</p>
      )}
      {error && <p className="text-red-500 text-xs mt-2">{error}</p>}

      {/* 
        // Benutzerverwaltungstabelle (kommt später)
        <table>...</table>
      */}
    </div>
  );
};

export default UserManagementSettings;
