/* eslint-disable @typescript-eslint/no-explicit-any */
"use client";
import React, { useEffect, useState } from "react";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";

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

import { ErrorResponseProps, RoleProps } from "@/lib/features/admin/account/type";
import { ErrorMessage } from "@/components/ui/error-message";
import Loading from "../../components/loading";
import { geOneAccount, getRoles, updateAccount } from "@/lib/features/admin/account/service";
import { useForm } from "react-hook-form";
import z from "zod";
import { UserFormValidation } from "@/lib/features/admin/account/schema";
import { zodResolver } from "@hookform/resolvers/zod";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import { LoaderCircle } from "lucide-react";
import { toast } from "sonner";


interface Props {
    dataId: number;
}

export const UpdateUserFormDialog = ({ dataId }: Props) => {

    // 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);

    // user details
    const {
        data,
        isLoading,
        error
    } = useQuery({
        queryKey: ["view-user-details-for-update"],
        queryFn: () => geOneAccount(dataId),
    });


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


    // Update states
    useEffect(() => {
        if (data?.data?.userDetails) {
            setFirstName(data?.data?.userDetails?.tbl_userFname)
            setLastName(data?.data?.userDetails?.tbl_userLname);

            setEmail(data?.data?.userDetails?.tbl_userEmail)
            setUsername(data?.data?.userDetails?.tbl_userName);

            setRoleId(data?.data?.userDetails?.tbl_roleId)
            setPhone(data?.data?.userDetails?.tbl_userTel);

        }

    }, [data]);



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



    const queryClient = useQueryClient();

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

            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,
                userId: dataId
            }

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

            mutation.mutate(body);
        }
    }



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


    //////////////////////error handling

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

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

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


    return (
        <div>
            <div className="text-sm font-medium text-center text-neutral-600 pb-4">
                Update 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" />
                                : "UPDATE"
                            }
                        </Button>
                    </div>
                </form>
            </Form>
        </div>
    );
};