'use client'
import { Button } from "@nextui-org/button";
import { Card, Checkbox, CheckboxGroup, Divider, Image, Input, Radio, RadioGroup, Select, SelectItem, SelectSection, Slider, Switch, Tab, Table, Tabs, Textarea, User } from "@nextui-org/react";
import React, { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { TimesIcon } from "@/components/icons";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { close, error, loading } from "@/config/swal";
import Swal from 'sweetalert2';
import withReactContent from 'sweetalert2-react-content';
import dynamic from 'next/dynamic';
import { useForm } from "react-hook-form";
import * as z from "zod";
import { zodResolver } from "@hookform/resolvers/zod";

const platform = [
    { label: "Article", value: "article", id: 1 },
    { label: "Caption", value: "caption", id: 2 },
    { label: "Meme", value: "meme", id: 3 },
    { label: "Video", value: "video", id: 4 },
    { label: "Master Data", value: "master-data", id: 5 },
];

export default function CreateMasterModuleForm() {
    const router = useRouter();
    const JoditEditor = dynamic(() => import('jodit-react'), { ssr: false });
    const MySwal = withReactContent(Swal);
    const [isVisible, setIsVisible] = useState(false);
    const [tabs, setTabs] = useState<string>("personal-info")
    const editor = useRef(null);
    const [content, setContent] = useState('');
    const [haveChildren, setHaveChildren] = useState("no");
    const [active, setActive] = useState("1");
    const handleTab = (tab: any) => {
        setTabs(tab);
    };

    const handleActive = (e: React.ChangeEvent<HTMLInputElement>) => {
        setActive(e.target.value);
    };

    const handleHaveChildren = (e: React.ChangeEvent<HTMLInputElement>) => {
        setHaveChildren(e.target.value);
    };

    let [files, setFiles] = useState<File[]>([]);

    const removeFile = (name: string) => {
        const arrayFile: File[] = [];
        for (const element of files) {
            if (element.name !== name) {
                arrayFile.push(element);
            }
        }
        setFiles(arrayFile);
    };

    const handleFileChange = (event: any) => {
        const newFiles: FileList | null = event.target.files;
        if (newFiles) {
            const allowedExtensions = ['.doc', '.docx', '.pdf', '.ppt', '.pptx', '.xlsx', '.csv'];
            let temp: File[] = [...files]; // Salin file-file yang sudah ada
            for (let i = 0; i < newFiles.length; i++) {
                const file = newFiles[i];
                const fileExtension = file.name.split('.').pop()?.toLowerCase();
                if (fileExtension && allowedExtensions.includes(`.${fileExtension}`)) {
                    temp.push(file);
                } else {
                    alert('Format file tidak valid. Hanya file .doc, .docx, .ppt, .pptx, .xlsx, .csv atau .pdf yang diperbolehkan.');
                }
            }
            setFiles(temp);
        }
    };

    const toggleVisibility = () => setIsVisible(!isVisible);

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

    const formOptions = { resolver: zodResolver(validationSchema) };
    type ArticleSchema = z.infer<typeof validationSchema>;

    const { register, handleSubmit, formState: { errors }, formState, setValue } = useForm<ArticleSchema>(formOptions);

    const save = async (data: any) => {

        const request = {
            name: data.name,
            description: data.description,
            pathUrl: data.pathUrl,
            status: 1,
        };

        console.log(request);
        // loading();
        // // const res = await saveManualContext(request);
        // if (res.error) {
        //     error(res.message);
        //     return false; 
        // }
        close();
        successSubmit("/admin/master/master-module")
    }

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

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

    return (
        <div className="mx-3 my-5">
            <div className="flex flex-col gap-3 mb-4">
                <Card className="w-full ">
                    <div className="w-full mr-2 p-5 ">
                        <form method="POST" onSubmit={handleSubmit(onSubmit)}>
                            <>
                                <div className="flex flex-row gap-1">
                                    <div className="w-6/12 justify-start items-start mt-2 gap-3">
                                        <div className="flex flex-col ">
                                            <Input
                                                type="text"
                                                label="Name"
                                                id="name"
                                                {...register("name")}
                                                placeholder="Input Name"
                                                labelPlacement="outside"
                                                className=" font-semibold"
                                                classNames={{
                                                    label: "!text-black dark:!text-white",
                                                    input: "!text-black dark:!text-white hover:!text-black focus:!text-black",
                                                    inputWrapper: "max-h-[40px] bg-transparant border text-black",
                                                }}
                                                startContent={
                                                    <div className="pointer-events-none flex items-center">
                                                        <span className="text-default-400 text-small"></span>
                                                    </div>
                                                }
                                            />
                                            {errors.name?.message && (
                                                <p className="text-red-400 text-sm">
                                                    {errors.name?.message}
                                                </p>
                                            )}
                                        </div>
                                        <div className="flex flex-col mt-3">
                                            <Input
                                                type="text"
                                                label="Description"
                                                id="description"
                                                {...register("description")}
                                                placeholder="Input Description"
                                                labelPlacement="outside"
                                                className=" font-semibold"
                                                classNames={{
                                                    label: "!text-black dark:!text-white",
                                                    input: "!text-black dark:!text-white hover:!text-black focus:!text-black",
                                                    inputWrapper: "max-h-[40px] bg-transparant border text-black",
                                                }}
                                                startContent={
                                                    <div className="pointer-events-none flex items-center">
                                                        <span className="text-default-400 text-small"></span>
                                                    </div>
                                                }
                                            />
                                            {errors.description?.message && (
                                                <p className="text-red-400 text-sm">
                                                    {errors.description?.message}
                                                </p>
                                            )}
                                        </div>
                                        <div className="flex flex-col mt-3">
                                            <Input
                                                type="text"
                                                label="pathUrl"
                                                id="pathUrl"
                                                {...register("pathUrl")}
                                                placeholder="Input PathUrl"
                                                labelPlacement="outside"
                                                className=" font-semibold"
                                                classNames={{
                                                    label: "!text-black dark:!text-white",
                                                    input: "!text-black dark:!text-white hover:!text-black focus:!text-black",
                                                    inputWrapper: "max-h-[40px] bg-transparant border text-black",
                                                }}
                                                startContent={
                                                    <div className="pointer-events-none flex items-center">
                                                        <span className="text-default-400 text-small"></span>
                                                    </div>
                                                }
                                            />
                                            {errors.description?.message && (
                                                <p className="text-red-400 text-sm">
                                                    {errors.description?.message}
                                                </p>
                                            )}
                                        </div>
                                        <div className="text-black mt-3">
                                            <label className="text-black dark:text-white text-sm ">Status</label>
                                            <RadioGroup
                                                orientation="horizontal"
                                                id="radio-banned"
                                                className="text-gray-950 pt-2"
                                                onChange={handleActive}
                                                defaultValue={active}
                                                classNames={{
                                                    label: "!text-black dark:!text-white",
                                                    description: "!text-black",
                                                    base: "!text-black",
                                                    wrapper: "!text-black",
                                                }}
                                            >
                                                <Radio
                                                    classNames={{
                                                        label: "!text-black dark:!text-white",
                                                    }}
                                                    value="1"
                                                >
                                                    Active
                                                </Radio>
                                                <Radio
                                                    classNames={{
                                                        label: "!text-black dark:!text-white",
                                                    }}
                                                    value="2"
                                                >
                                                    Inactive
                                                </Radio>
                                            </RadioGroup>
                                        </div>
                                        <div className="flex flex-row gap-3 my-3">
                                            <Link href="/admin/master/master-module">
                                                <Button
                                                    variant="bordered"
                                                    className="bg-white border-grey-100  rounded-full text-[#8E5C18] mr-5"
                                                >
                                                    Cancel
                                                </Button>{" "}
                                            </Link>
                                            <Button
                                                className="w-[50px]"
                                                color="primary"
                                                size="md"
                                                type="submit">
                                                Submit
                                            </Button>
                                        </div>
                                    </div>
                                    <div className="w-6/12 ">
                                        <div className="flex items-center justify-center justify-items-center h-full">
                                            <Image
                                                width={400}
                                                alt="NextUI hero Image"
                                                src="/account-category.jpg"
                                            />
                                        </div>
                                    </div>
                                </div>
                            </>
                        </form>
                    </div>
                </Card>
            </div>
        </div >

    )
}
