'use client'
import { error } from '@/config/swal';
import { createMasterUserRole, getMasterUserRoleById } from '@/service/master-user-role';
import { zodResolver } from '@hookform/resolvers/zod';
import { Button, Card, Input, Textarea } from '@nextui-org/react';
import Link from 'next/link';
import { usePathname, useRouter } from 'next/navigation';
import { useEffect, useState } from 'react';
import { useForm } from 'react-hook-form';
import Swal from 'sweetalert2';
import withReactContent from 'sweetalert2-react-content';
import { z } from 'zod';

const masterUserSchema = z.object({
    code: z.string().min(1, { message: "Required" }),
    description: z.string().min(1, { message: "Required" }),
    levelNumber: z.string().min(1, { message: "Required" }),
    name: z.string().min(1, { message: "Required" }),
});

export default function FormDetailMasterUserRole() {
    const router = useRouter();
    const MySwal = withReactContent(Swal);
    const [userRole, setUserRole] = useState<any>();
    const [code, setCode] = useState<string>();
    const [description, setDescription] = useState<string>();
    const [levelNumber, setLevelNumber] = useState<any>(1);
    const [name, setName] = useState<string>();
    const pathname = usePathname();
    const splitPathname = pathname.split('/');
    const id = splitPathname[splitPathname.length - 1];

    const formOptions = { resolver: zodResolver(masterUserSchema) };
    type MicroIssueSchema = z.infer<typeof masterUserSchema>;
    const {
        register,
        control,
        handleSubmit,
        setValue,
        formState: { errors },
    } = useForm<MicroIssueSchema>(formOptions);


    useEffect(() => {
        async function initState() {
            const res = await getMasterUserRoleById(id);
            setUserRole(res.data?.data);
            setCode(res.data?.data?.code)
            setName(res.data.data?.name)
            setDescription(res.data.data?.description)
            setLevelNumber(res.data.data?.level_number)

            console.log("Data MasterUser", userRole);
        }

        initState();
    }, []);


    async function save(data: any) {
        const formData = {
            code: code,
            description: description,
            level_number: levelNumber,
            name: name,
        };

        console.log("Form MasterUser:", formData);
        const response = await createMasterUserRole(formData);

        if (response?.error) {
            error(response.message);
            return false;
        }

        successSubmit("/admin/master-role");
    };

    function successSubmit(redirect: any) {
        MySwal.fire({
            title: "Sukses",
            icon: "success",
            confirmButtonColor: "#3085d6",
            confirmButtonText: "OK",
        }).then((result) => {
            if (result.isConfirmed) {
                router.push(redirect);
            }
        });
    }

    async function onSubmit(data: any) {
        MySwal.fire({
            title: "Simpan Data",
            text: "",
            icon: "warning",
            showCancelButton: true,
            cancelButtonColor: "#d33",
            confirmButtonColor: "#3085d6",
            confirmButtonText: "Simpan",
        }).then((result) => {
            if (result.isConfirmed) {
                save(data);
            }
        });
    }

    return (
        <div className='mx-5 my-5 overflow-y-auto'>
            <form method="POST" onSubmit={handleSubmit(onSubmit)}>
                <Card className='rounded-md p-5 space-y-5'>
                    <div>
                        <Input
                            isReadOnly
                            type="text"
                            {...register("code")}
                            label="Code"
                            variant='bordered'
                            placeholder="Enter Text"
                            labelPlacement='outside'
                            value={code}
                            onChange={(e) => setCode(e.target.value)}
                        />
                        {errors.code?.message}
                    </div>
                    <div>
                        <Input
                            isReadOnly
                            type="text"
                            {...register("name")}
                            label="Role"
                            variant='bordered'
                            placeholder="Enter Text"
                            labelPlacement='outside'
                            value={name}
                            onChange={(e) => setName(e.target.value)}
                        />
                        {errors.name?.message}
                    </div>
                    <div>
                        <Textarea
                            isReadOnly
                            label="Description"
                            {...register("description")}
                            labelPlacement="outside"
                            placeholder="Enter Text"
                            value={description}
                            onValueChange={setDescription}
                        />
                    </div>
                    <div>
                        <Input
                            type="text"
                            {...register("levelNumber")}
                            label="Level Number"
                            variant='bordered'
                            placeholder="Enter Text"
                            labelPlacement='outside'
                            value={levelNumber}
                        />
                        {errors.code?.message}
                    </div>
                    <div className='flex justify-end gap-3'>
                        <Link href={`/admin/master-role`}>
                            <Button
                                color='primary'
                                variant="ghost"
                            >
                                Back
                            </Button>
                        </Link>
                        {/* <Button
                            type="submit"
                            color='primary'
                            variant="solid"
                        >
                            Save
                        </Button> */}
                    </div>
                </Card>
            </form>
        </div >
    )
}
