import { LstCard } from "@/components/extendedUI/LstCard";
import { Button } from "@/components/ui/button";
import { CardHeader } from "@/components/ui/card";
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 { useSessionStore } from "@/lib/store/sessionStore";
import { getProdPerms } from "@/utils/querys/prodUser/getProdPerms";

import { useForm } from "@tanstack/react-form";
import { useState } from "react";
import { useQuery } from "@tanstack/react-query";
import axios from "axios";
import { toast } from "sonner";

export default function ProdUserCard() {
    const { token } = useSessionStore();
    const { data, isError, isLoading } = useQuery(getProdPerms(token ?? ""));
    const [creating, setCreating] = useState(false);

    const form = useForm({
        defaultValues: {
            username: "",
            remark: "",
            pcname: "",
            role: "",
        },

        onSubmit: async ({ value }) => {
            setCreating(true);
            //console.log(value);

            if (value.role === "") {
                toast.error(
                    "Role is missing please select a role and try again."
                );
            }

            try {
                const res = await axios.post("/api/produser/produser", value, {
                    headers: { Authorization: `Bearer ${token}` },
                });

                //console.log(res.data);

                if (!res.data.success) {
                    const errMSG: string = res.data.data.errors
                        ? res.data.data?.errors[0].message
                        : res.data.data;

                    toast.error(`${errMSG}`);
                    setCreating(false);
                }

                if (res.data.success) {
                    toast.success(res.data.message);
                    form.reset();
                    setCreating(false);
                }
            } catch (error) {
                console.log(error);
                setCreating(false);
            }
        },
    });

    if (isError)
        return (
            <>
                <p>There was an error loading the prod Perms</p>
            </>
        );
    if (isLoading)
        return (
            <>
                <p>Loading.....</p>
            </>
        );
    return (
        <div className="m-4">
            <LstCard>
                <CardHeader>
                    <p>Alpla Prod user create/update</p>
                </CardHeader>
                <div className="m-2">
                    <p>
                        Please enter the windows username. <br /> To check the
                        user head here{" "}
                        <a
                            target="_blank"
                            href="https://alplaservicedesk.service-now.com/sp?id=sc_cat_item&sys_id=0c266831c32f41107cba16c4e40131c0&sysparm_category=564428bdc3eb41107cba16c4e40131f2"
                        >
                            <u>Active Directory</u>
                        </a>
                    </p>
                </div>
                <form
                    onSubmit={(e) => {
                        e.preventDefault();
                        e.stopPropagation();
                    }}
                >
                    {/* Windows username */}
                    <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>
                            );
                        }}
                    />
                    {/* Remark for the user */}
                    <form.Field
                        name="remark"
                        validators={{
                            // We can choose between form-wide and field-specific validators
                            onChange: ({ value }) =>
                                value.length > 3
                                    ? undefined
                                    : "The remark should be longer than 3 letters",
                        }}
                        children={(field) => {
                            return (
                                <div className="m-2 min-w-48 max-w-96 p-2">
                                    <Label htmlFor="remark">Remark</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>
                            );
                        }}
                    />
                    {/* Select the type of role we will be granting/updating */}
                    <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>

                                                {data.map((i: any) => {
                                                    return (
                                                        <SelectItem
                                                            key={i.prodPerm_id}
                                                            value={i.name}
                                                        >
                                                            {i.name}
                                                        </SelectItem>
                                                    );
                                                })}
                                            </SelectGroup>
                                        </SelectContent>
                                    </Select>
                                </div>
                            );
                        }}
                    />
                    <div className="flex justify-end mr-3">
                        <Button onClick={form.handleSubmit} disabled={creating}>
                            Submit
                        </Button>
                    </div>
                </form>
            </LstCard>
        </div>
    );
}
