'use client'
import { error } from '@/config/swal';
import { createArticle } from '@/service/article';
import { zodResolver } from '@hookform/resolvers/zod';
import { Button, Card, Chip, Input, Select, SelectItem, Selection } from '@nextui-org/react';
import JoditEditor from 'jodit-react';
import Link from 'next/link';
import { useRouter } from 'next/navigation';
import React, { ChangeEvent, useRef, useState } from 'react';
import { useForm } from 'react-hook-form';
import Swal from 'sweetalert2';
import withReactContent from 'sweetalert2-react-content';
import * as z from "zod";

const articleSchema = z.object({
    title: z.string().min(1, { message: "Required" }),
    article: z.string().min(1, { message: "Required" }),
    slug: z.string().min(1, { message: "Required" }),
    tags: z.string().min(0, { message: "Required" }).optional(),
    description: z.string().min(0, { message: "Required" }).optional(),

});

export default function FormArticle() {
    const router = useRouter();
    const [title, setTitle] = useState<string>("");
    const [article, setArticle] = React.useState<Selection>(new Set([]));
    const [slug, setSlug] = useState<string>("");
    const [tags, setTags] = useState<string[]>([]);
    const [newTags, setNewTags] = useState<string>("");
    const editor = useRef(null);
    const [content, setContent] = useState('');
    const MySwal = withReactContent(Swal);
    const [selectedImages, setSelectedImages] = useState<File[]>([]);

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

    const TypeId = [
        {
            key: 1,
            label: "Article"
        },
        {
            key: 2,
            label: "Magazine"
        },
    ]

    const handleImageChange = (event: ChangeEvent<HTMLInputElement>) => {
        if (event.target.files) {
            const files = Array.from(event.target.files);
            setSelectedImages((prevImages) => [...prevImages, ...files]);
        }
    };

    const handleRemoveImage = (index: number) => {
        setSelectedImages((prevImages) =>
            prevImages.filter((_, i) => i !== index)
        );
    };

    // const handleSubmitImage = (event: any) => {
    //     event.preventDefault();
    //     // Lakukan penanganan pengunggahan gambar di sini
    //     if (selectedImage) {
    //         console.log('Gambar yang dipilih:', selectedImage);
    //         // Anda dapat melakukan pengunggahan gambar ke server di sini
    //     } else {
    //         console.log('Pilih gambar terlebih dahulu.');
    //     }
    // };

    const handleClose = (tagsToRemove: string) => {
        setTags(tags.filter((tag) => tag !== tagsToRemove));
        if (tags.length === 1) {
            setTags([]);
        }
    };

    const handleAddTags = (e: any) => {
        if (newTags.trim() !== "") {
            setTags([...tags, newTags.trim()]);
            setNewTags("");
            e.preventDefault();
        }
    };

    const handleKeyDown = (event: any) => {
        if (event.key === "Enter") {
            handleAddTags(event);
        }
    };


    async function save(data: any) {
        const formData = {
            title: title,
            typeId: parseInt(String(Array.from(article)[0])),
            slug: slug,
            tags: tags.join(','),
            description: content,
            htmlDescription: content,
        };

        console.log("Form Data:", formData);
        const response = await createArticle(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="title"
                            {...register("title")}
                            value={title}
                            onChange={(e) => setTitle(e.target.value)}
                            label="Judul"
                            variant='bordered'
                            placeholder="Enter Text"
                            labelPlacement='outside'
                        />
                        <div className="text-sm text-red-500">
                            {(title.length === 0 && errors.title) && errors.title.message}

                        </div>
                    </div>
                    <div>
                        <Select
                            label="Jenis Artikel"
                            {...register("article")}
                            variant="bordered"
                            labelPlacement='outside'
                            placeholder="Select"
                            selectedKeys={article}
                            className="max-w-xs"
                            onSelectionChange={setArticle}
                        >
                            {TypeId.map((data) => (
                                <SelectItem key={data.key} value={data.key}>
                                    {data.label}
                                </SelectItem>
                            ))}
                        </Select>
                        <div className="text-sm text-red-500">
                            {errors.article?.message}
                        </div>
                        {/* <p>{article}</p> */}
                    </div>
                    <div>
                        <Input
                            type="text"
                            {...register("slug")}
                            value={slug}
                            onChange={(e) => setSlug(e.target.value)}
                            label="Slug"
                            variant='bordered'
                            placeholder="Enter Text"
                            labelPlacement='outside'
                        />
                        <div className="text-sm text-red-500">
                            {(slug.length === 0 && errors.slug) && errors.slug.message}
                        </div>
                    </div>
                    <div>
                        <Input
                            label="Tags (Optional)"
                            {...register("tags")}
                            labelPlacement='outside'
                            type="text"
                            value={newTags}
                            onChange={(e) => setNewTags(e.target.value)}
                            onKeyDown={handleKeyDown}
                            placeholder="Tambahkan tag baru dan tekan Enter"
                        />
                        <div className="text-sm text-red-500">
                            {(tags.length === 0 && errors.tags) && errors.tags.message}
                        </div>
                        <div className="flex gap-2 border border-inherit mt-2 rounded-md p-1 items-center h-11">
                            {tags.map((tag, index) => (
                                <Chip color='primary' key={index} onClose={() => handleClose(tag)}>
                                    {tag}
                                </Chip>
                            ))}
                        </div>
                    </div>
                    <div>
                        <p className='pb-2'>Description</p>
                        <JoditEditor
                            ref={editor}
                            value={content}
                            onChange={(newContent) => setContent(newContent)}
                            className="dark:text-black"

                        />
                        <div className="text-sm text-red-500">
                            {(content.length === 0 && errors.description) && errors.description.message}
                        </div>
                    </div>
                    <div>
                        <p>Attachment (Opsional)</p>
                        <div className="flex items-center justify-center w-full pt-2 ">
                            <label
                                htmlFor="dropzone-file"
                                className="flex flex-col items-center justify-center w-full h-36 border border-gray-100 border-dashed rounded-lg cursor-pointer bg-gray-50 hover:bg-gray-100 dark:border-gray-600 dark:hover:border-gray-500 dark:hover:bg-gray-200"
                            >
                                <div className="flex flex-col items-center justify-center pt-5 pb-6 ">
                                    <svg
                                        className="w-10 h-10 mb-3 text-gray-400"
                                        fill="none"
                                        stroke="currentColor"
                                        viewBox="0 0 24 24"
                                        xmlns="http://www.w3.org/2000/svg"
                                    >
                                        <path
                                            strokeLinecap="round"
                                            strokeLinejoin="round"
                                            strokeWidth="2"
                                            d="M7 16a4 4 0 01-.88-7.903A5 5 0 1115.9 6L16 6a5 5 0 011 9.9M15 13l-3-3m0 0l-3 3m3-3v12"
                                        ></path>
                                    </svg>
                                    <p className="mb-2 text-sm text-gray-500 dark:text-gray-400">
                                        Drag and drop files here
                                    </p>
                                    <p className="mb-2 text-sm text-gray-500 dark:text-gray-400">
                                        {/* or{" "} */}
                                        <span className="font-semibold underline text-amber-800">
                                            Click to upload
                                        </span>
                                    </p>
                                </div>
                                <input id="dropzone-file" type="file" onChange={handleImageChange} />
                            </label>
                        </div>
                        {
                            selectedImages?.length > 0 ?
                                <div>
                                    <h4>Pratinjau:</h4>
                                    <div className='flex gap-2 pt-2'>
                                        {selectedImages.map((image, index) => (
                                            <div key={index} className='flex flex-col items-end'>
                                                <Chip
                                                    color='danger'
                                                    size='sm'
                                                    className='cursor-pointer'
                                                    onClick={() => handleRemoveImage(index)}
                                                >
                                                    X
                                                </Chip>
                                                <img
                                                    src={URL.createObjectURL(image)}
                                                    alt="Pratinjau Gambar"
                                                    style={{ maxWidth: '200px', maxHeight: '200px' }}
                                                />
                                            </div>
                                        ))}
                                    </div>
                                </div>
                                : ""
                        }

                    </div>
                    <div className='flex justify-end gap-3'>
                        <Link href={`/admin/article`}>
                            <Button
                                color='danger'
                                variant="ghost"
                            >
                                Cancel
                            </Button>
                        </Link>
                        <Button
                            type="submit"
                            color='primary'
                            variant="solid"
                        >
                            Save
                        </Button>
                    </div>
                </Card>
            </form>
        </div>
    )
}
