import { LstCard } from "@/components/extendedUI/LstCard";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
// import {
//     Select,
//     SelectContent,
//     SelectGroup,
//     SelectItem,
//     SelectLabel,
//     SelectTrigger,
//     SelectValue,
// } from "@/components/ui/select";

import { DebugButton } from "@/utils/formStuff/debugButton";
import { userFormOptions } from "@/utils/formStuff/options/userformOptions";
import { generatePassword } from "@/utils/passwordGen";
import { getUsers } from "@/utils/querys/admin/users";
import { useForm } from "@tanstack/react-form";
import { useQuery } from "@tanstack/react-query";
import axios from "axios";
import { toast } from "sonner";

import { CardHeader } from "@/components/ui/card";
import ModuleAccess from "./ModuleAccess";

export default function UserCard(data: any) {
    const token = localStorage.getItem("auth_token");
    const { refetch } = useQuery(getUsers());

    //console.log(userRoles);
    const form = useForm({
        ...userFormOptions(data.user),
        onSubmit: async ({ value }) => {
            // Do something with form data

            const userData = { ...value, user_id: data.user.user_id };

            try {
                const res = await axios.patch(
                    "/api/auth/updateuser",
                    userData,
                    {
                        headers: {
                            Authorization: `Bearer ${token}`,
                        },
                    }
                );

                if (res.data.success) {
                    toast.success(res.data.message);
                    refetch();
                    form.reset();
                } else {
                    res.data.message;
                }
            } catch (error) {
                console.log(error);
            }
        },
    });
    return (
        <div className="flex flex-row">
            <div className="m-2">
                <LstCard>
                    <CardHeader>User Profile</CardHeader>
                    <form
                        onSubmit={(e) => {
                            e.preventDefault();
                            e.stopPropagation();
                        }}
                    >
                        <form.Field
                            name="username"
                            validators={{
                                // We can choose between form-wide and field-specific validators
                                onChange: ({ value }) =>
                                    value.length > 3
                                        ? undefined
                                        : "Username must be longer than 3 letters",
                            }}
                            children={(field) => {
                                return (
                                    <div className="m-2 min-w-48 max-w-96 p-2">
                                        <Label htmlFor="username">
                                            Username
                                        </Label>
                                        <Input
                                            name={field.name}
                                            value={field.state.value}
                                            onBlur={field.handleBlur}
                                            //type="number"
                                            onChange={(e) =>
                                                field.handleChange(
                                                    e.target.value
                                                )
                                            }
                                        />
                                        {field.state.meta.errors.length ? (
                                            <em>
                                                {field.state.meta.errors.join(
                                                    ","
                                                )}
                                            </em>
                                        ) : null}
                                    </div>
                                );
                            }}
                        />
                        <form.Field
                            name="email"
                            validators={{
                                // We can choose between form-wide and field-specific validators
                                onChange: ({ value }) =>
                                    value.length > 3
                                        ? undefined
                                        : "You must enter a correct ",
                            }}
                            children={(field) => {
                                return (
                                    <div className="m-2 min-w-48 max-w-96 p-2">
                                        <Label htmlFor="email">Email</Label>
                                        <Input
                                            name={field.name}
                                            value={field.state.value}
                                            onBlur={field.handleBlur}
                                            //type="number"
                                            onChange={(e) =>
                                                field.handleChange(
                                                    e.target.value
                                                )
                                            }
                                        />
                                        {field.state.meta.errors.length ? (
                                            <em>
                                                {field.state.meta.errors.join(
                                                    ","
                                                )}
                                            </em>
                                        ) : null}
                                    </div>
                                );
                            }}
                        />
                        {/* <form.Field
                            name="role"
                            //listeners={{onChange: ({value})=>{}}}
                            children={(field) => {
                                return (
                                    <div className="m-2 min-w-48 max-w-96 p-2">
                                        <Label htmlFor={field.name}>
                                            Select role
                                        </Label>
                                        <Select
                                            value={field.state.value}
                                            onValueChange={field.handleChange}
                                        >
                                            <SelectTrigger className="w-[180px]">
                                                <SelectValue
                                                    id={field.name}
                                                    placeholder="Select Role"
                                                />
                                            </SelectTrigger>
                                            <SelectContent>
                                                <SelectGroup>
                                                    <SelectLabel>
                                                        Roles
                                                    </SelectLabel>
                                                    <SelectItem value="viewer">
                                                        Viewer
                                                    </SelectItem>
                                                    <SelectItem value="operator">
                                                        Operator
                                                    </SelectItem>
                                                    <SelectItem value="manager">
                                                        Manager
                                                    </SelectItem>
                                                    <SelectItem value="admin">
                                                        Admin
                                                    </SelectItem>
                                                </SelectGroup>
                                            </SelectContent>
                                        </Select>
                                    </div>
                                );
                            }}
                        /> */}
                        <form.Field
                            name="password"
                            validators={{
                                onChangeAsyncDebounceMs: 500,
                                onChangeAsync: ({ value }) => {
                                    if (
                                        window.location.pathname.includes(
                                            "/users"
                                        ) &&
                                        value.length === 0
                                    ) {
                                        return;
                                    }
                                    if (value.length < 4) {
                                        return "Password must be at least 4 characters long.";
                                    }

                                    if (!/[A-Z]/.test(value)) {
                                        return "Password must contain at least one uppercase letter.";
                                    }

                                    if (!/[a-z]/.test(value)) {
                                        return "Password must contain at least one lower case letter.";
                                    }

                                    if (!/[0-9]/.test(value)) {
                                        return "Password must contain at least one number.";
                                    }

                                    if (
                                        !/[!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]/.test(
                                            value
                                        )
                                    ) {
                                        return "Password must contain at least one special character.";
                                    }
                                },
                            }}
                            children={(field) => {
                                return (
                                    <div className="m-2 p-2">
                                        <Label htmlFor="password">
                                            Change Password
                                        </Label>
                                        <div className="mt-2 flex flex-row">
                                            <Input
                                                className="min-w-48 max-w-96"
                                                name={field.name}
                                                value={field.state.value}
                                                onBlur={field.handleBlur}
                                                //type="number"
                                                onChange={(e) =>
                                                    field.handleChange(
                                                        e.target.value
                                                    )
                                                }
                                            />
                                            <Button
                                                className="ml-2"
                                                onClick={() =>
                                                    field.handleChange(
                                                        generatePassword(8)
                                                    )
                                                }
                                            >
                                                Random password
                                            </Button>
                                            <DebugButton
                                                data={form.state.values}
                                            />
                                        </div>
                                        {field.state.meta.errors.length ? (
                                            <em>
                                                {field.state.meta.errors.join(
                                                    ","
                                                )}
                                            </em>
                                        ) : null}
                                    </div>
                                );
                            }}
                        />
                        <div className="mt-4 ml-4">
                            <Button onClick={form.handleSubmit}>Save</Button>
                        </div>
                    </form>
                </LstCard>
            </div>
            <div>
                <LstCard>
                    <ModuleAccess user={data.user} refetch={refetch} />
                </LstCard>
            </div>
        </div>
    );
}
