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

export default function Booking({ bookings, pagination, filters }) {
    const { flash } = usePage().props;
    const processedMessages = useRef(new Set());
    
    const [bookingData, setBookingData] = useState([]);
    const [isViewModalOpen, setIsViewModalOpen] = useState(false);
    const [selectedBooking, setSelectedBooking] = useState(null);
    const [deleteModal, setDeleteModal] = useState({ show: false, booking: null });

    // Handle flash messages from trait (simple format) - prevent duplicates
    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]);

    // Update booking data when props change
    useEffect(() => {
        setBookingData(bookings || []);
    }, [bookings]);

    // Define columns for booking data
    const columns = [
        { key: 'sn', header: 'SN' },
        { key: 'property_title', header: 'Property' },
        { key: 'tenant_name', header: 'Tenant' },
        { key: 'landlord_name', header: 'Landlord' },
        { key: 'check_in_date', header: 'Check In' },
        { key: 'check_out_date', header: 'Check Out' },
        { key: 'status', header: 'Status' }
    ];

    // Status mapping (based on database schema)
    const getStatusName = (status) => {
        const statusMap = {
            1: 'pending',
            2: 'approved',
            3: 'rejected',
            4: 'cancelled',
            5: 'completed'
        };
        return statusMap[status] || 'N/A';
    };

    // Transform data for display
    const transformedData = bookingData.map(booking => ({
        ...booking,
        status: getStatusName(booking.status),
        check_in_date: new Date(booking.check_in_date).toLocaleDateString(),
        check_out_date: booking.check_out_date ? new Date(booking.check_out_date).toLocaleDateString() : 'N/A',
        property_title: booking.property_title?.length > 30 ? `${booking.property_title.substring(0, 30)}...` : booking.property_title || 'N/A',
    }));

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

    const handleView = (row) => {
        fetch(`/admin/bookings/${row.id}`)
            .then((response) => {
                if (!response.ok) {
                    throw new Error('Network response was not ok');
                }
                return response.json();
            })
            .then((bookingData) => {
                setSelectedBooking(bookingData);
                setIsViewModalOpen(true);
            })
            .catch((error) => {
                console.error('Error fetching booking details:', error);
                toast.error('Failed to load booking details');
            });
    };

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

    return (
        <>
            <Toaster />
            <div className="row">
                <StyledTable
                    data={transformedData}
                    columns={columns}
                    title="Booking Management"
                    onView={handleView}
                    onDelete={handleDelete}
                    noDataText="No bookings found in the system"
                    disablePagination={true}
                    serverPagination={pagination}
                    onPageChange={handlePageChange}
                    itemType="bookings"
                    showEdit={false}
                />
            </div>

            <DeleteConfirmationModal
                isOpen={deleteModal.show}
                onClose={() => setDeleteModal({ show: false, booking: null })}
                onConfirmDelete={() => {
                    // Let Inertia handle the response and page refresh
                    // The trait will redirect back with success/error messages
                }}
                itemName={`Booking #${deleteModal.booking?.id}` || 'this booking'}
                itemType="booking"
                deleteEndpoint={`/admin/bookings/${deleteModal?.booking?.id}`}
            />
            <ViewBooking
                isOpen={isViewModalOpen}
                onClose={() => setIsViewModalOpen(false)}
                booking={selectedBooking}
            />
        </>
    );
}
