import { useEffect, useState } from "react";
import { Card, CardContent, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from "@/components/ui/dialog";
import { useAuth } from "@/context/AuthContext";
import { useNavigate } from "react-router-dom";

const apiBase = import.meta.env.VITE_API_URL;

interface User {
  id: number;
  username: string;
  email: string;
  role: string;
}

const UserManagementPage = () => {
  const [users, setUsers] = useState<User[]>([]);
  const [isDeleteModalOpen, setIsDeleteModalOpen] = useState(false);
  const [userToDelete, setUserToDelete] = useState<User | null>(null);
  const { token } = useAuth();

  const {isAuthenticated, isAdmin} = useAuth();
const navigate = useNavigate();

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

  useEffect(() => {
    const fetchUsers = async () => {
      try {
        const res = await fetch(`${apiBase}/api/users`, {
          headers: {
            Authorization: `Bearer ${token}`,
          },
        });
        const data = await res.json();
        setUsers(data);
      } catch (err) {
        console.error(err);
      }
    };

    fetchUsers();
  }, [token]);

  const handleDelete = async () => {
    if (!userToDelete) return;

    try {
      await fetch(`${apiBase}/api/users/${userToDelete.id}`, {
        method: "DELETE",
        headers: {
          Authorization: `Bearer ${token}`,
        },
      });

      // Nach dem Löschen die Liste neu laden
      setUsers((prev) => prev.filter((u) => u.id !== userToDelete.id));
      setIsDeleteModalOpen(false);
    } catch (err) {
      console.error(err);
    }
  };

  return (
    <div className="max-w-6xl mx-auto py-12 px-4">
      <div className="flex justify-between items-center mb-8">
        <h1 className="text-3xl font-bold text-frog-600">Benutzerverwaltung</h1>
        <Button
          className="bg-frog-500 hover:bg-frog-600 text-white"
          onClick={() => navigate("/admin/users/new")}
        >
          ➕ Benutzer hinzufügen
        </Button>
      </div>

      <div className="grid md:grid-cols-2 gap-6">
        {users.map((user) => (
          <Card key={user.id} className="hover:shadow-lg transition-shadow">
            <CardContent className="p-6">
              <CardTitle className="text-frog-600">{user.username}</CardTitle>
              <p className="text-gray-600 text-sm">{user.email}</p>
              <p className="text-sm mt-1">
                Rolle: <span className={user.role === "admin" ? "text-frog-500 font-semibold" : "text-gray-500"}>{user.role}</span>
              </p>

              <div className="flex gap-4 mt-4">
                <Button
                  variant="outline"
                  onClick={() => navigate(`/admin/users/edit/${user.id}`)}
                  className="border-frog-500 text-frog-600 hover:bg-frog-50"
                >
                  Bearbeiten
                </Button>
                <Button
                  variant="destructive"
                  onClick={() => {
                    setUserToDelete(user);
                    setIsDeleteModalOpen(true);
                  }}
                >
                  Löschen
                </Button>
              </div>
            </CardContent>
          </Card>
        ))}
      </div>

      {/* Delete Confirm Modal */}
      <Dialog open={isDeleteModalOpen} onOpenChange={setIsDeleteModalOpen}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>Möchtest du {userToDelete?.username} wirklich löschen?</DialogTitle>
          </DialogHeader>
          <DialogFooter>
            <Button variant="ghost" onClick={() => setIsDeleteModalOpen(false)}>
              Abbrechen
            </Button>
            <Button variant="destructive" onClick={handleDelete}>
              Löschen
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
};

export default UserManagementPage;
