import InputError from "@/Components/InputError";
import Paginator from "@/Components/Paginator";
import AuthenticatedLayout from "@/Layouts/AuthenticatedLayout";
import { Head, useForm } from "@inertiajs/react";
import { Button, FileInput, Label, Modal, Progress, Select, Table, Textarea, TextInput } from "flowbite-react";
import { FaPencilAlt } from "react-icons/fa";
import { useState, useRef } from "react";
import { ToastContainer, toast } from "react-toastify";
import { INSERTED, UPDATED } from "@/Config/Constant";
import Editor from 'react-simple-wysiwyg';
export default function Event({ auth, events }) {
    const { data, setData, post, processing, progress, errors, reset } = useForm({ title: "", details: "", date: '', file_path: null });
    const [openModal, setOpenModal] = useState(false);
    const [editingItemId, setEditingItemId] = useState(null);
    const firstInputRef = useRef(null);

    const submit = (e) => {
        e.preventDefault();
        post(route("event.store", data), {
            forceFormData: true,
            onSuccess: () => {
                reset('title', 'details', 'date', 'file_path');
                setOpenModal(false);
                toast.success(INSERTED);
                console.log(errors);

            }
        });
    };
    const handleEdit = (itemId) => {
        const event = events.data.find((item) => item.id === itemId);
        setData({
            title: event.title,
            details: event.details,
            date: event.date,
        });
        setEditingItemId(itemId);
        setOpenModal(true);
    };
    const handleUpdate = (e, itemId) => {
        e.preventDefault();
        const newData = {
            ...data,
            _method: "put",
        };
        post(route("event.update", { event: itemId, ...newData }), {
            forceFormData: true,
            onSuccess: () => {
                reset("title", 'details', 'date', 'file_path');
                setEditingItemId(null);
                setOpenModal(false);
                toast.success(UPDATED);
            }
        });
    };
    return (
        <AuthenticatedLayout
            user={auth.user}
            header={
                <h2 className="font-semibold text-xl text-gray-800 leading-tight">
                    Events
                </h2>
            }
        >
            <Head
                title={"Events"}
            />

            <div className="p-3 sm:p-6">
                <div className="bg-gray-50 overflow-hidden shadow-sm sm:rounded-lg dark:bg-gray-800 p-6">
                    <div className="flex justify-between border-b border-gray-400 pb-2">
                        <h2 className="font-semibold text-2xl text-gray-800 dark:text-gray-200 leading-tight">
                            Events
                        </h2>
                        <Button onClick={() => setOpenModal(true)}>
                            Add new
                        </Button>
                    </div>
                    <ToastContainer position="bottom-right" theme="colored" />
                    <div className="overflow-x-auto">
                        <Table hoverable>
                            <Table.Head>
                                <Table.HeadCell className="text-start">#</Table.HeadCell>
                                <Table.HeadCell>
                                    Title
                                </Table.HeadCell>
                                <Table.HeadCell>
                                    Image
                                </Table.HeadCell>
                                <Table.HeadCell>
                                    Date
                                </Table.HeadCell>
                                <Table.HeadCell className="text-start">
                                    Action
                                </Table.HeadCell>
                            </Table.Head>
                            <Table.Body className="divide-y">
                                {events?.data?.map((item, index) => (
                                    <Table.Row key={index} className="bg-white dark:border-gray-700 dark:bg-gray-800 text-start">
                                        <Table.Cell>{index + 1}</Table.Cell>
                                        <Table.Cell className="whitespace-nowrap font-medium text-gray-900 dark:text-white">
                                            {item.title}
                                        </Table.Cell>
                                        <Table.Cell >
                                            <img src={item.file_path ? item.file_path : "https://placehold.co/50x50?text=IMG"}
                                                alt="Product img" style={{ height: "60px" }} />
                                        </Table.Cell>
                                        <Table.Cell >
                                            {item.date}
                                        </Table.Cell>

                                        <Table.Cell className="flex gap-1">
                                            <a href="#" size={"xs"} onClick={() => handleEdit(item.id)} title="Edit">
                                                <FaPencilAlt />
                                            </a>
                                        </Table.Cell>
                                    </Table.Row>
                                ))}

                                {events.data.length == 0 && (
                                    <tr className="text-center">
                                        <td colSpan={6}>No data available!</td>
                                    </tr>
                                )}
                            </Table.Body>
                        </Table>
                        <Paginator paginationData={events} />
                    </div>
                </div>
            </div>

            <Modal show={openModal} size="3xl" popup onClose={() => {
                setOpenModal(false);
                setEditingItemId(null);
                setData({ title: '', details: '', date: '', file_path: null });
            }}
                initialFocus={firstInputRef}>
                <Modal.Header>
                    {editingItemId ? "Update" : "Add new"}
                </Modal.Header>
                <Modal.Body>
                    <form onSubmit={editingItemId ? (e) => handleUpdate(e, editingItemId) : submit}>
                        <div className="grid grid-cols-2 gap-4">
                            <div className="col-span-2">
                                <div className="mb-2 block">
                                    <Label htmlFor="title" value='title' />
                                </div>
                                <TextInput id="title" name="title" value={data.title}
                                    onChange={(e) =>
                                        setData("title", e.target.value)
                                    }
                                    ref={firstInputRef} />
                                <InputError message={errors.title} className="mt-2 dark:text-gray-100" />
                            </div>
                            <div className="col-span-2">
                                <div className="mb-2 block">
                                    <Label htmlFor="details" value='details' />
                                </div>
                                <Editor value={data.details} onChange={(e) => setData('details', e.target.value)} />
                                <InputError message={errors.details} className="mt-2 dark:text-gray-100" />
                            </div>
                            <div className="col-span-2">
                                <div className="mb-2 block">
                                    <Label htmlFor="date" value='date' />
                                </div>
                                <TextInput type="date" id="date" name="date" value={data.date}
                                    onChange={(e) =>
                                        setData("date", e.target.value)
                                    }/>
                                <InputError message={errors.date} className="mt-2 dark:text-gray-100" />
                            </div>
                            <div className="col-span-2">
                                <div className="mb-1 block">
                                    <Label htmlFor="file_path" value="Image" />
                                </div>
                                <FileInput onChange={(e) =>
                                    setData("file_path", e.target.files[0])
                                } />
                                {progress && (
                                    <Progress
                                        progress={progress.percentage}
                                        progressLabelPosition="inside"
                                        textLabel="Uploading..."
                                        textLabelPosition="inside"
                                        size="lg"
                                        labelProgress
                                        labelText
                                    />
                                )}
                                <InputError message={errors.file_path} className="mt-2 dark:text-gray-100" />
                            </div>
                            <div className="col-span-2">
                                <Button type="submit" isProcessing={processing} disabled={processing}>
                                    {editingItemId ? "Update" : "Save"}
                                </Button>
                            </div>
                        </div>
                    </form>
                </Modal.Body>
            </Modal>
        </AuthenticatedLayout>
    );
}
