import StyledTable from "@/Components/Admin/ui/StyledTable";
import { useEffect, useState, useRef } from "react";
import { router, usePage } from '@inertiajs/react';
import { toast, Toaster } from "react-hot-toast";
import DeleteConfirmationModal from "@/Components/Admin/ui/DeleteConfirmationModal";

export default function Hostel({ hostels, pagination, filters }) {
    const { flash } = usePage().props;
    const processedMessages = useRef(new Set());
    
    const [hostelData, setHostelData] = useState([]);
    const [deleteModal, setDeleteModal] = useState({ show: false, hostel: null });

    useEffect(() => {
        if (flash?.success) {
            const message = typeof flash.success === 'object' ? flash.success.message : flash.success;
            if (message && !processedMessages.current.has(`success-${message}`)) {
                toast.success(message);
                processedMessages.current.add(`success-${message}`);
            }
        }
        if (flash?.error) {
            const message = typeof flash.error === 'object' ? flash.error.message : flash.error;
            if (message && !processedMessages.current.has(`error-${message}`)) {
                toast.error(message);
                processedMessages.current.add(`error-${message}`);
            }
        }
    }, [flash]);

    useEffect(() => {
        setHostelData(hostels || []);
    }, [hostels]);

    const columns = [
        { key: 'sn', header: 'SN' },
        { key: 'property_title', header: 'Property' },
        { key: 'property_address', header: 'Address' },
        { key: 'landlord_name', header: 'Landlord' },
        { key: 'university_nearby_text', header: 'University' },
        { key: 'distance_text', header: 'Distance' },
        { key: 'room_sharing_name', header: 'Room Type' },
        { key: 'gender_restriction_name', header: 'Gender' },
    ];

    const transformedData = hostelData.map(hostel => ({
        ...hostel,
    }));

    const handlePageChange = (page) => {
        router.get('/admin/hostels', { ...filters, page }, { preserveState: true, preserveScroll: true });
    };

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

    const handleEdit = (row) => {
        router.visit(`/admin/hostels/${row.id}`);
    };

    return (
        <>
            <Toaster />
            <div className="row">
                <StyledTable
                    data={transformedData}
                    columns={columns}
                    title="Hostel Management"
                    onDelete={handleDelete}
                    onEdit={handleEdit}
                    noDataText="No hostels found in the system"
                    disablePagination={true}
                    serverPagination={pagination}
                    onPageChange={handlePageChange}
                    itemType="hostels"
                    showEdit={true}
                />
            </div>

            <DeleteConfirmationModal
                isOpen={deleteModal.show}
                onClose={() => setDeleteModal({ show: false, hostel: null })}
                onConfirmDelete={() => {
                    router.delete(`/admin/hostels/${deleteModal.hostel?.id}`, {
                        onSuccess: () => {
                            setDeleteModal({ show: false, hostel: null });
                            toast.success('Hostel and property deleted successfully');
                        },
                        onError: () => {
                            toast.error('Failed to delete hostel');
                        }
                    });
                }}
                itemName={`Hostel #${deleteModal.hostel?.id}` || 'this hostel'}
                itemType="hostel"
                deleteEndpoint={`/admin/hostels/${deleteModal?.hostel?.id}`}
            />
        </>
    );
}






