"use client";

import type React from "react";

import { useState } from "react";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Checkbox } from "@/components/ui/checkbox";
import { createUser } from "@/app/protected/(admin)/dashboard/user-management/action";
import { toast } from "sonner";
import { Mail, Lock, Loader2, X } from "lucide-react";

interface AddUserDialogProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  onUserAdded: () => void;
}

export function AddUserDialog({
  open,
  onOpenChange,
  onUserAdded,
}: AddUserDialogProps) {
  const [loading, setLoading] = useState(false);
  const [formData, setFormData] = useState({
    email: "",
    password: "",
    emailConfirm: true,
  });

  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const { name, value } = e.target;
    setFormData((prev) => ({ ...prev, [name]: value }));
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setLoading(true);

    try {
      await createUser({
        email: formData.email,
        password: formData.password,
        email_confirm: formData.emailConfirm,
      });

      toast.success("User created successfully.");
      onUserAdded();
      onOpenChange(false);
      setFormData({
        email: "",
        password: "",
        emailConfirm: true,
      });
    } catch (error) {
      toast.error("Failed to create user.");
    } finally {
      setLoading(false);
    }
  };

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="sm:max-w-md border-0 text-white">
        <DialogHeader className="flex flex-row items-center justify-between space-y-0 space-x-4 pb-4">
          <DialogTitle className="text-xl font-semibold text-white">
            Create a new user
          </DialogTitle>
          {/* <Button
            variant="ghost"
            size="icon"
            className="h-8 w-8 text-zinc-400 hover:text-white hover:bg-zinc-800"
            onClick={() => onOpenChange(false)}
          >
            <X className="h-4 w-4" />
          </Button> */}
        </DialogHeader>
        <form onSubmit={handleSubmit} className="space-y-4">
          <div className="space-y-3">
            <div className="space-y-2">
              <label htmlFor="email" className="text-sm text-zinc-400">
                Email address
              </label>
              <div className="relative">
                <Mail className="absolute left-3 top-2.5 h-5 w-5 text-zinc-500" />
                <Input
                  id="email"
                  name="email"
                  type="email"
                  required
                  placeholder="user@example.com"
                  value={formData.email}
                  onChange={handleInputChange}
                  className="pl-10 bg-zinc-900 border-zinc-800 text-white placeholder:text-zinc-500 "
                />
              </div>
            </div>
            <div className="space-y-2">
              <label htmlFor="password" className="text-sm text-zinc-400">
                User Password
              </label>
              <div className="relative">
                <Lock className="absolute left-3 top-2.5 h-5 w-5 text-zinc-500" />
                <Input
                  id="password"
                  name="password"
                  type="password"
                  required
                  placeholder="••••••••"
                  value={formData.password}
                  onChange={handleInputChange}
                  className="pl-10 bg-zinc-900 border-zinc-800 text-white placeholder:text-zinc-500 "
                />
              </div>
            </div>
          </div>

          <div className="space-y-2">
            <div className="flex items-center space-x-2">
              <Checkbox
                id="email-confirm"
                checked={formData.emailConfirm}
                onCheckedChange={(checked) =>
                  setFormData((prev) => ({
                    ...prev,
                    emailConfirm: checked as boolean,
                  }))
                }
                className="border-zinc-700"
              />
              <label htmlFor="email-confirm" className="text-sm text-white">
                Auto Confirm User?
              </label>
            </div>
            <p className="text-sm text-zinc-500 pl-6">
              A confirmation email will not be sent when creating a user via
              this form.
            </p>
          </div>

          <Button
            type="submit"
            disabled={loading}
            className="w-full text-white"
          >
            {loading ? (
              <>
                <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                Creating...
              </>
            ) : (
              "Create user"
            )}
          </Button>
        </form>
      </DialogContent>
    </Dialog>
  );
}
