import Row from "@admin/ui/Row";
import Col from "@admin/ui/Col";
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 EditSlider from "./EditSlider";

export default function Slider({sliders}){
    const [isEditModalOpen, setIsEditModalOpen] = useState(false);
    const [initialData, setInitialData] = useState(null);
    const [deleteModal, setDeleteModal] = useState({ show: false, slider: null });

    const columns = [
        { header: '', key: 'checkbox' },
        { header: 'Title', key: 'title' },
        { header: 'Description', key: 'description' },
        { header: 'Status', key: 'status' },
      ];

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


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

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

        <DeleteConfirmationModal isOpen={deleteModal.show} onClose={() => setDeleteModal({ show: false, slider: null })}
            onConfirmDelete={() => {
                toast.success("Slider Deleted Successfuly")
            }}
            itemName={deleteModal.slider?.name || 'this slider'}
            itemType="slider"
            deleteEndpoint={`/admin/api/delete_slider/${deleteModal?.slider?.id}`}
        />
        <EditSlider isOpen={isEditModalOpen} onClose={() => setIsEditModalOpen(false)}
            initialData={initialData} />

        </>
    );
}