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

const apiBase = import.meta.env.VITE_API_URL;

const UserCreatePage = () => {
  const [username, setUsername] = useState("");
  const [password, setPassword] = useState("");
  const [role, setRole] = useState("user");
  const [email, setEmail] = useState("");
  const { token } = useAuth();

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

  const {toast} = useToast();
  const [isLoading, setIsLoading] = useState(false);

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



const handleSubmit = async (e: React.FormEvent) => {
  e.preventDefault();
  setIsLoading(true);
  try {
    const res = await fetch(`${apiBase}/api/users`, {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        Authorization: `Bearer ${token}`,
      },
      body: JSON.stringify({ username, password, role, email }),
    });

    if (!res.ok) {
      throw new Error("Fehler beim Anlegen des Benutzers");
    }

    toast({
      title: "Benutzer erstellt",
      description: `Der Benutzer "${username}" wurde erfolgreich angelegt.`,
      variant: "default",
    });

    navigate("/admin/users");
  } catch (err) {
    console.error(err);
    toast({
      title: "Fehler",
      description: "Benutzer konnte nicht angelegt werden.",
      variant: "destructive",
    });
  } finally {
    setIsLoading(false);
  }
};


  return (
    <div className="max-w-3xl mx-auto py-12 px-4">
      <Card>
        <CardHeader>
          <CardTitle>Benutzer erstellen</CardTitle>
        </CardHeader>
        <CardContent>
          <form onSubmit={handleSubmit} className="space-y-4">
            <Input 
              type="email"
              placeholder="E-Mail"
              value={email}
              onChange={(e) => setEmail(e.target.value)}
              required
            />
            <Input
              placeholder="Benutzername"
              value={username}
              onChange={(e) => setUsername(e.target.value)}
              required
            />
            <Input
              type="password"
              placeholder="Passwort"
              value={password}
              onChange={(e) => setPassword(e.target.value)}
              required
            />
            <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"
              disabled={isLoading}
            >
              {isLoading ? "Speichern..." : "Benutzer anlegen"}
            </Button>
          </form>
        </CardContent>
      </Card>
    </div>
  );
};

export default UserCreatePage;
