import Col from "@admin/ui/Col";
import Row from "@admin/ui/Row";
import StyledTable from "@admin/ui/StyledTable";
import { Link } from "@inertiajs/react";
import DeleteConfirmationModal from "@admin/ui/DeleteConfirmationModal";
import { toast,Toaster } from "react-hot-toast";
import { useState } from "react";
import EditEvent from "./EditEvent";

export default function Event({events}){
    const columns = [
        { header: '', key: 'checkbox' },
        { header: 'Title', key: 'title' },
        { header: 'Photo', key: 'photo' },
        { header: 'Status', key: 'status' },
      ];

    const [eventData, setPostData] = useState([]);
    const [isEditModalOpen, setIsEditModalOpen] = useState(false);
    const [initialData, setInitialData] = useState(null);
    const [deleteModal, setDeleteModal] = useState({ show: false, event: null });

    const handleDelete = (row) => {
        setDeleteModal({ show: true, event: row });
    };

    const handleEdit = (row) => {
        fetch(`/admin/edit_event/${row.id}`)
        .then((response) => {
            if (!response.ok) {
            throw new Error('Network response was not ok');
            }
            return response.json();
        })
        .then((eventData) => {
            const formattedData = eventData;
            setInitialData(formattedData);
            setIsEditModalOpen(true);
        })
        .catch((error) => {
            console.error('Error fetching post details:', error);
        });
    };


    return(
        <>
        <Row md="12" >
            <Col lg="12">
            <Toaster />
            <h2 className="page-title">Events</h2>
            <p className="text-muted">Manage upcoming events</p>
            <Link className="btn mb-4 btn-primary" href="/admin/events/create">
            Create new Event
            </Link>
            <Row>
            <Col lg="12">
                <StyledTable 
                data={events} 
                columns={columns} 
                itemsPerPage={5} 
                title="Available Events"
                onEdit={handleEdit}
                onDelete={handleDelete}
                noDataText="No Events found"
                />
            </Col>
            </Row>
            </Col>
        </Row>

        <DeleteConfirmationModal isOpen={deleteModal.show} onClose={() => setDeleteModal({ show: false, event: null })}
            onConfirmDelete={() => {
                toast.success("Event Deleted Successfuly")
                setPostData(prev => prev.filter(item => item.id !== deleteModal.event.id));
            }}
            itemName={deleteModal.event?.title || 'this event'}
            itemType="event"
            deleteEndpoint={`/admin/api/delete_event/${deleteModal?.event?.id}`}
        />

        <EditEvent isOpen={isEditModalOpen} onClose={() => setIsEditModalOpen(false)}
            initialData={initialData}/>

        </>
    );
}