import { useEffect, useState } from "react";
import { useParams, useNavigate } from "react-router-dom";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { useAuth } from "@/context/AuthContext";

const UserEditPage = () => {
  const { id } = useParams<{ id: string }>();
  const { token, isAuthenticated, isAdmin } = useAuth();
  const navigate = useNavigate();

  const [username, setUsername] = useState("");
  const [password, setPassword] = useState(""); // optional neu setzen
  const [role, setRole] = useState("user");

  useEffect(() => {
    if (!isAuthenticated || !isAdmin) {
      navigate("/admin");
    }
  }, [isAuthenticated, isAdmin, navigate]);

  useEffect(() => {
    const fetchUser = async () => {
      try {
        const res = await fetch(`http://192.168.50.65:3000/api/users/${id}`, {
          headers: {
            Authorization: `Bearer ${token}`,
          },
        });
        const data = await res.json();
        setUsername(data.username);
        setRole(data.role);
      } catch (err) {
        console.error(err);
      }
    };

    if (id) {
      fetchUser();
    }
  }, [id, token]);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    try {
      await fetch(`http://192.168.50.65:3000/api/users/${id}`, {
        method: "PUT",
        headers: {
          "Content-Type": "application/json",
          Authorization: `Bearer ${token}`,
        },
        body: JSON.stringify({
          username,
          password: password || undefined, // Passwort nur mitschicken wenn eingegeben
          role,
        }),
      });

      navigate("/admin/users");
    } catch (err) {
      console.error(err);
      alert("Fehler beim Aktualisieren des Benutzers");
    }
  };

  return (
    <div className="max-w-3xl mx-auto py-12 px-4">
      <Card>
        <CardHeader>
          <CardTitle>Benutzer bearbeiten</CardTitle>
        </CardHeader>
        <CardContent>
          <form onSubmit={handleSubmit} className="space-y-4">
            <Input
              placeholder="Benutzername"
              value={username}
              onChange={(e) => setUsername(e.target.value)}
              required
            />
            <Input
              type="password"
              placeholder="Neues Passwort (leer lassen für kein Wechsel)"
              value={password}
              onChange={(e) => setPassword(e.target.value)}
            />
            <select
              value={role}
              onChange={(e) => setRole(e.target.value)}
              className="w-full border rounded-md p-2"
            >
              <option value="user">User</option>
              <option value="admin">Admin</option>
            </select>
            <Button type="submit" className="w-full bg-frog-500 hover:bg-frog-600 text-white">
              Benutzer speichern
            </Button>
          </form>
        </CardContent>
      </Card>
    </div>
  );
};

export default UserEditPage;
