'use client'
import { error } from '@/config/swal';
import { createMasterUser } from '@/service/master-user';
import { MasterUser } from '@/types/globals';
import { zodResolver } from '@hookform/resolvers/zod';
import { Button, Card, Input, Radio, RadioGroup, Select, SelectItem, Selection, Textarea } from '@nextui-org/react'
import Link from 'next/link';
import { useRouter } from 'next/navigation';
import React, { 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({
    fullname: z.string().min(1, { message: "Required" }),
    username: z.string().min(1, { message: "Required" }),
    email: z.string().min(1, { message: "Required" }),
    identityType: z.string().min(1, { message: "Required" }),
    lastEducation: z.string().min(1, { message: "Required" }),
    phoneNumber: z.string().min(1, { message: "Required" }),
    workingType: z.string().min(1, { message: "Required" }),
});

export default function FormMasterUser() {
    const router = useRouter();
    const MySwal = withReactContent(Swal);
    const [address, setAddress] = useState<string>();
    const [dateOfBirt, setDateOfBirt] = useState<string>("13-april-1995");
    const [email, setEmail] = useState<string>();
    const [fullName, setFullname] = useState<string>();
    const [genderType, setGenderType] = React.useState("");
    const [identityNumber, setIdentityNumber] = useState<string>();
    const [lastEducation, setLastEducation] = useState<any>([]);
    const [phoneNumber, setPhoneNumber] = useState<string>();
    const [userLevelsId, setUserLevelsId] = useState<number>(1);
    const [userRoleId, setUserRoleId] = useState<number>(1);
    const [username, setUsername] = useState<string>();
    const [workType, setWorkType] = useState<string>("Tets");
    const [identityType, setIdentityType] = useState<any>([])
    const [showNumberInput, setShowNumberInput] = useState(false);

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

    const typeIdentity = [
        {
            id: 1,
            value: "KTP",
        },
        {
            id: 2,
            value: "SIM",
        },
        {
            id: 3,
            value: "Passport",
        },
    ]

    const workingBackground = [
        {
            id: 1,
            value: "Pegawai Negri Sipil",
        },
        {
            id: 2,
            value: "Wiraswasta",
        },
        {
            id: 3,
            value: "Guru",
        },
        {
            id: 4,
            value: "Dokter",
        },
    ]

    const educationGrade = [
        {
            id: 1,
            value: "SMA / Sederajat",
        },
        {
            id: 2,
            value: "Diploma 1",
        },
        {
            id: 3,
            value: "Diploma 2",
        },
        {
            id: 4,
            value: "Diploma 3",
        },
        {
            id: 5,
            value: "Diploma 4",
        },
        {
            id: 6,
            value: "S1",
        },
        {
            id: 7,
            value: "S2",
        },
        {
            id: 8,
            value: "S3",
        },
    ]


    async function save(data: any) {
        const formData = {
            address: address,
            dateOfBirt: dateOfBirt,
            email: email,
            fullName: fullName,
            genderType: genderType,
            identityNumber: identityNumber,
            identityType: identityType.anchorKey,
            lastEducation: Array.from(lastEducation)[0],
            phoneNumber: phoneNumber,
            userLevelsId: userLevelsId,
            userRoleId: userRoleId,
            username: username,
            workType: workType,
        };

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

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

        successSubmit("/admin/article");
    };

    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
                            type="text"
                            {...register("fullname")}
                            label="Fullname"
                            variant='bordered'
                            placeholder="Enter Text"
                            labelPlacement='outside'
                            value={fullName}
                            onChange={(e) => setFullname(e.target.value)}
                        />
                        {errors.fullname?.message}
                    </div>
                    <div>
                        <Input
                            type="text"
                            {...register("username")}
                            label="Username"
                            variant='bordered'
                            placeholder="Enter Text"
                            labelPlacement='outside'
                            value={username}
                            onChange={(e) => setUsername(e.target.value)}

                        />
                        {errors.username?.message}
                    </div>
                    <div>
                        <Input
                            type="email"
                            {...register("email")}
                            label="Email"
                            variant='bordered'
                            placeholder="Enter Text"
                            labelPlacement='outside'
                            value={email}
                            onChange={(e) => setEmail(e.target.value)}
                        />
                        {errors.email?.message}
                    </div>
                    <div>
                        <Select
                            variant='bordered'
                            {...register("identityType")}
                            labelPlacement='outside'
                            label="Identity Type"
                            placeholder="Select"
                            className="max-w-xs"
                            selectedKeys={identityType}
                            onSelectionChange={setIdentityType}
                        >
                            {typeIdentity.map((type) => (
                                <SelectItem key={type.value}>
                                    {type.value}
                                </SelectItem>
                            ))}
                        </Select>
                        {/* <p>selected : {identityType}</p> */}
                        {errors.identityType?.message}
                        {/* {showNumberInput && ( */}
                        <Input
                            type="text"
                            className='pt-2'
                            variant='bordered'
                            placeholder="Enter Identity Number"
                            labelPlacement='outside'
                            value={identityNumber}
                            onChange={(e) => setIdentityNumber(e.target.value)}
                        />
                        {/* )} */}
                    </div>
                    <div>
                        <RadioGroup
                            orientation='horizontal'
                            label="Select your favorite city"
                            value={genderType}
                            onValueChange={setGenderType}
                        >
                            <Radio value="laki-laki">Laki-laki</Radio>
                            <Radio value="perempuan">Perempuan</Radio>
                        </RadioGroup>
                        <p className="text-default-500 text-small">Selected: {genderType}</p>
                    </div>
                    <div>
                        <Select
                            variant='bordered'
                            {...register("lastEducation")}
                            labelPlacement='outside'
                            label="Last Education"
                            selectedKeys={lastEducation}
                            onSelectionChange={setLastEducation}
                            placeholder="Select"
                            className="max-w-xs"
                        >
                            {educationGrade.map((grade) => (
                                <SelectItem key={grade.value}>
                                    {grade.value}
                                </SelectItem>
                            ))}
                        </Select>
                        <p className="text-default-500 text-small">Selected: {lastEducation}</p>
                        {errors.lastEducation?.message}
                    </div>
                    <div>
                        <Input
                            type="text"
                            {...register("phoneNumber")}
                            label="Phone Number"
                            className='pt-2'
                            variant='bordered'
                            placeholder="Enter Number"
                            labelPlacement='outside'
                            value={phoneNumber}
                            onChange={(e) => setPhoneNumber(e.target.value)}
                        />
                        {errors.phoneNumber?.message}
                    </div>
                    <div>
                        <Select
                            variant='bordered'
                            {...register("workingType")}
                            labelPlacement='outside'
                            label="Working Type"
                            placeholder="Select"
                            className="max-w-xs"
                        >
                            {workingBackground.map((type) => (
                                <SelectItem key={type.id} value={type.id}>
                                    {type.value}
                                </SelectItem>
                            ))}
                        </Select>
                        {errors.workingType?.message}
                    </div>
                    <div>
                        <Textarea
                            label="Address"
                            labelPlacement="outside"
                            placeholder="Enter Text"
                            value={address}
                            onValueChange={setAddress}
                        />
                    </div>
                    <div className='flex justify-end gap-3'>
                        <Link href={`/admin/master-user`}>
                            <Button
                                color='danger'
                                variant="ghost"
                            >
                                Cancel
                            </Button>
                        </Link>
                        <Button
                            type="submit"
                            color='primary'
                            variant="solid"
                        >
                            Save
                        </Button>
                    </div>
                </Card>
            </form>
        </div >
    )
}
