"use client";

import { toast } from "sonner";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";

import {
    Form,
    FormControl,
    FormField,
    FormItem,
    FormLabel,
    FormMessage,
} from "@/components/ui/form";

import Loading from "@/app/(dashoard)/components/loading";
import { ErrorMessage } from "@/components/ui/error-message";
import React, { useState } from "react";
import { createAccount, getRoles } from "@/lib/features/admin/account/service";
import { ErrorResponseProps, RoleProps } from "@/lib/features/admin/account/type";
import { useForm } from "react-hook-form";
import { UserFormValidation } from "@/lib/features/admin/account/schema";
import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import { LoaderCircle } from "lucide-react";

export const UserFormDialog = () => {

    // states
    const [roleId, setRoleId] = useState<number | null>(null);
    const [email, setEmail] = useState('');

    const [firstName, setFirstName] = useState('');
    const [lastName, setLastName] = useState('');

    const [phone, setPhone] = useState('');
    const [username, setUsername] = useState('');

    const [sending, setSending] = useState(false);

    // roles
    const { data, isLoading, error } = useQuery({
        queryKey: ["roles-for-account-creation"],
        queryFn: () => getRoles(),
    });

    const queryClient = useQueryClient();

    const mutation = useMutation({
        mutationFn: createAccount,
        onSuccess: () => {
            queryClient.invalidateQueries({ queryKey: ["createNewUser"] });
            toast.success("Account created successfully");
            window.location.reload();
        },
        onError: (error) => {

            const newError = error as unknown as ErrorResponseProps;
            toast.error(newError?.response?.data?.message);

            return false;
            //window.location.reload();
        },
    });

    function onSubmit() {

        if (firstName === null || firstName === '') {
            toast.error("First name is required");
            return false;
        }

        else if (lastName === null || lastName === '') {
            toast.error("Last name is required");
            return false;
        }

        else if (roleId === null) {

            toast.error("Role is required");
            return false;

        }

        else if (email === null || email === '') {
            toast.error("Email is required");
            return false;
        }

        else if (phone === null || phone === '') {
            toast.error("Phone number is required");
            return false;
        }

        else if (username === null || username === '') {
            toast.error("Username is required");
            return false;
        }


        else {

            setSending(true);

            const body = {
                email: email,
                firstName: firstName,
                lastName: lastName,
                phone: phone,
                username: username,
                roleId: roleId,
                password: '1234'
            }

            // console.log(body);
            // return false;

            mutation.mutate(body);
        }
    }



    // Form setup
    const form = useForm<z.infer<typeof UserFormValidation>>({
        resolver: zodResolver(UserFormValidation),
        defaultValues: {
        },
    });

    if (isLoading) {
        return <Loading />;
    }

    //error
    if (error) {
        return <ErrorMessage error={error} fallback="Dashboard error" />
    }

    // roles
    const roles: RoleProps[] = data?.data || [];

    return (
        <div>
            <div className="text-sm font-medium text-center text-neutral-600 pb-4">
                Create new user
            </div>

            <Form {...form}>
                <form className="space-y-6">
                    <div className="grid gap-2">

                        <div className="grid grid-cols-2 gap-2">

                            <FormField
                                control={form.control}
                                name="firstName"
                                render={({ }) => (
                                    <FormItem>
                                        <FormLabel>First name</FormLabel>
                                        <FormControl>
                                            <Input type="text" value={firstName} onChange={(e) => setFirstName(e.target.value)} />
                                        </FormControl>
                                        <FormMessage />
                                    </FormItem>
                                )}
                            />

                            <FormField
                                control={form.control}
                                name="lastName"
                                render={({ }) => (
                                    <FormItem>
                                        <FormLabel>Last name</FormLabel>
                                        <FormControl>
                                            <Input type="text" value={lastName} onChange={(e) => setLastName(e.target.value)} />
                                        </FormControl>
                                        <FormMessage />
                                    </FormItem>
                                )}
                            />

                            <FormField
                                control={form.control}
                                name="phone"
                                render={({ }) => (
                                    <FormItem>
                                        <FormLabel>Phone</FormLabel>
                                        <FormControl>
                                            <Input type="number" value={phone} onChange={(e) => setPhone(e.target.value)} />
                                        </FormControl>
                                        <FormMessage />
                                    </FormItem>
                                )}
                            />


                            <FormField
                                control={form.control}
                                name="roleId"
                                render={({ }) => (
                                    <FormItem>
                                        <FormLabel>Role</FormLabel>
                                        <select
                                            className="w-full border border-gray-300 rounded p-2"
                                            value={String(roleId)}
                                            onChange={(e) => setRoleId(Number(e.target.value))}
                                        >
                                            <option value=""></option>

                                            {roles?.length > 0 ? roles?.map((role) => (
                                                <option key={role?.tbl_roleId} value={String(role?.tbl_roleId)}>
                                                    {role?.tbl_roleName}
                                                </option>
                                            ))
                                                : ""}
                                        </select>
                                        <FormMessage />
                                    </FormItem>
                                )}
                            />


                            <FormField
                                control={form.control}
                                name="email"
                                render={({ }) => (
                                    <FormItem>
                                        <FormLabel>Email</FormLabel>
                                        <FormControl>
                                            <Input type="email" value={email} onChange={(e) => setEmail(e.target.value)} />
                                        </FormControl>
                                        <FormMessage />
                                    </FormItem>
                                )}
                            />


                            <FormField
                                control={form.control}
                                name="username"
                                render={({ }) => (
                                    <FormItem>
                                        <FormLabel>Username</FormLabel>
                                        <FormControl>
                                            <Input type="text" value={username} onChange={(e) => setUsername(e.target.value)} />
                                        </FormControl>
                                        <FormMessage />
                                    </FormItem>
                                )}
                            />

                        </div>

                        <Button className="confirm-button mt-4" type="button" onClick={onSubmit}  >
                            {sending ?
                                <LoaderCircle className="animate-spin" />
                                : "SAVE"
                            }
                        </Button>
                    </div>
                </form>
            </Form>
        </div>
    );

}