"use client";

import { useState } from "react";

import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogFooter,
} from "@/components/ui/dialog";

import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";

import { api } from "@/lib/api";

export default function UserDialog() {

  const [open, setOpen] = useState(false);

  const [username, setUsername] = useState("");
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");

  async function saveUser() {

  console.log("Speichern geklickt");

  try {

    const response = await api.post("/users/", {
      username,
      email,
      password,
    });

    console.log(response.data);

    setOpen(false);

    window.location.reload();

  } catch (error) {

    console.error(error);

  }

}

  return (

    <>

      <Button onClick={() => setOpen(true)}>

        + Neuer Benutzer

      </Button>

      <Dialog open={open} onOpenChange={setOpen}>

        <DialogContent>

          <DialogHeader>

            <DialogTitle>

              Neuer Benutzer

            </DialogTitle>

          </DialogHeader>

          <div className="space-y-4">

            <div>

              <Label>Benutzername</Label>

              <Input
                value={username}
                onChange={(e) => setUsername(e.target.value)}
              />

            </div>

            <div>

              <Label>E-Mail</Label>

              <Input
                value={email}
                onChange={(e) => setEmail(e.target.value)}
              />

            </div>

            <div>

              <Label>Passwort</Label>

              <Input
                type="password"
                value={password}
                onChange={(e) => setPassword(e.target.value)}
              />

            </div>

          </div>

          <DialogFooter>

            <Button onClick={saveUser}>

              Speichern

            </Button>

          </DialogFooter>

        </DialogContent>

      </Dialog>

    </>

  );

}