"use client";

import { useContext, useState } from "react";
import { Button } from "@/components/ui/button";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";

interface AddUserButtonProps {
  userRole: string[];
  handleAddUser: (newUser: any) => void;
}

export function AddUserButton({ userRole, handleAddUser }: AddUserButtonProps) {
  const [open, setOpen] = useState(false);
  const [formData, setFormData] = useState({
    username: "",
    firstName: "",
    lastName: "",
    email: "",
    realmRoles: "",
  });
  const [error, setError] = useState<string | null>(null);

  const availableRoles = userRole.includes("admin")
    ? ["admin", "TEACHERS", "STUDENTS"]
    : ["STUDENTS"];

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    try {
      const response = await fetch("/api/users", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(formData),
      });
      const data = await response.json();

      if (!response.ok) {
        setError(data.error);
        return;
      }

      setOpen(false);
      setFormData({
        username: "",
        firstName: "",
        lastName: "",
        email: "",
        realmRoles: "",
      });
      setError(null);
      handleAddUser(data.user);
    } catch (error) {
      console.error("Erreur lors de la création:", error);
    }
  };

  return (
    <Dialog open={open} onOpenChange={setOpen}>
      <DialogTrigger asChild>
        <Button>Ajouter un utilisateur</Button>
      </DialogTrigger>
      <DialogContent>
        <DialogHeader>
          <DialogTitle>Nouvel utilisateur</DialogTitle>
        </DialogHeader>
        <form onSubmit={handleSubmit} className='space-y-4'>
          {error && <div className='text-red-500 text-sm'>{error}</div>}
          <Input
            placeholder="Nom d'utilisateur"
            value={formData.username}
            onChange={(e) =>
              setFormData({ ...formData, username: e.target.value })
            }
          />
          <Input
            placeholder='Prénom'
            value={formData.firstName}
            onChange={(e) =>
              setFormData({ ...formData, firstName: e.target.value })
            }
          />
          <Input
            placeholder='Nom'
            value={formData.lastName}
            onChange={(e) =>
              setFormData({ ...formData, lastName: e.target.value })
            }
          />
          <Input
            type='email'
            placeholder='Email'
            value={formData.email}
            onChange={(e) =>
              setFormData({ ...formData, email: e.target.value })
            }
          />
          <Select
            value={formData.realmRoles}
            onValueChange={(value) =>
              setFormData({ ...formData, realmRoles: value })
            }
          >
            <SelectTrigger>
              <SelectValue placeholder='Sélectionner un rôle' />
            </SelectTrigger>
            <SelectContent>
              {availableRoles.map((role) => (
                <SelectItem key={role} value={role}>
                  {role.charAt(0).toUpperCase() + role.slice(1).toLowerCase()}
                </SelectItem>
              ))}
            </SelectContent>
          </Select>
          <Button type='submit' className='w-full'>
            Créer
          </Button>
        </form>
      </DialogContent>
    </Dialog>
  );
}
