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, useMemo } from "react";
import EditRoom from "./EditRoom";
import { formatDate } from "@/utils/dateFormatter";

export default function Room({ rooms = [], accommodations = [] }) {
    const [isEditModalOpen, setIsEditModalOpen] = useState(false);
    const [initialData, setInitialData] = useState(null);
    const [deleteModal, setDeleteModal] = useState({ show: false, room: null });
    const [selectedCategory, setSelectedCategory] = useState('');
    
    const columns = [
        { header: '', key: 'checkbox' },
        { header: 'Room Number', key: 'room_number' },
        { header: 'Category', key: 'accommodation_name' },
        { header: 'Availability', key: 'is_available' },
        { header: 'Created', key: 'created_at' },
    ];

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

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

    // Format availability status for display
    const formatAvailability = (room) => {
        if (room.is_booked) {
            return <span className="badge badge-warning">Booked</span>;
        }
        return room.is_available ? (
            <span className="badge badge-success">Available</span>
        ) : (
            <span className="badge badge-danger">Unavailable</span>
        );
    };

    // Get unique categories from accommodations
    const uniqueCategories = useMemo(() => {
        const categories = accommodations.map(acc => ({
            id: acc.id,
            name: acc.name
        }));
        // Remove duplicates based on id
        return categories.filter((cat, index, self) => 
            index === self.findIndex(c => c.id === cat.id)
        );
    }, [accommodations]);

    // Filter rooms by selected category
    const filteredRooms = useMemo(() => {
        if (!selectedCategory) {
            return rooms;
        }
        return rooms.filter(room => room.accommodation_id.toString() === selectedCategory);
    }, [rooms, selectedCategory]);

    // Transform data for table display
    const transformedRooms = filteredRooms.map(room => ({
        ...room,
        is_available: formatAvailability(room),
        created_at: formatDate(room.created_at),
    }));

    return (
        <>
            <Toaster />
            <Row md="12">
                <Col lg="12">
                    <div className="d-flex flex-column flex-md-row justify-content-between align-items-start align-items-md-center mb-4">
                        <div className="mb-3 mb-md-0">
                            <h2 className="page-title mb-1">Individual Rooms</h2>
                            <p className="text-muted mb-0">Manage individual room instances</p>
                        </div>
                        <Link className="btn btn-primary" href="/admin/rooms/create">
                            <i className="fe fe-plus fe-16 mr-2"></i>
                            Add New Room
                        </Link>
                    </div>

                    {/* Filter Section - Responsive */}
                    <Row className="mb-3">
                        <Col xs="12" sm="12" md="6" lg="4">
                            <label htmlFor="categoryFilter" className="form-label font-weight-bold">
                                Filter by Category
                            </label>
                            <div className="d-flex">
                                <select
                                    id="categoryFilter"
                                    className="form-control"
                                    value={selectedCategory}
                                    onChange={(e) => setSelectedCategory(e.target.value)}
                                >
                                    <option value="">All Categories</option>
                                    {uniqueCategories.map((category) => (
                                        <option key={category.id} value={category.id}>
                                            {category.name}
                                        </option>
                                    ))}
                                </select>
                                {selectedCategory && (
                                    <button
                                        className="btn btn-outline-secondary btn-sm ml-2"
                                        onClick={() => setSelectedCategory('')}
                                        type="button"
                                        style={{ whiteSpace: 'nowrap' }}
                                    >
                                        <i className="fe fe-x fe-12 mr-1"></i>
                                        Clear
                                    </button>
                                )}
                            </div>
                        </Col>
                        <Col xs="12" sm="12" md="6" lg="8" className="d-flex align-items-end">
                            <div className="text-muted small">
                                Showing {filteredRooms.length} of {rooms.length} rooms
                            </div>
                        </Col>
                    </Row>

                    <Row>
                        <Col lg="12">
                            <StyledTable 
                                data={transformedRooms} 
                                columns={columns} 
                                itemsPerPage={10} 
                                title={selectedCategory ? `Rooms - ${uniqueCategories.find(c => c.id.toString() === selectedCategory)?.name || 'Filtered'}` : "All Rooms"}
                                onEdit={handleEdit}
                                onDelete={handleDelete}
                                noDataText={selectedCategory ? "No rooms found in this category" : "No rooms found"}
                            />
                        </Col>
                    </Row>
                </Col>
            </Row>
            
            <DeleteConfirmationModal 
                isOpen={deleteModal.show} 
                onClose={() => setDeleteModal({ show: false, room: null })}
                onConfirmDelete={() => {
                    toast.success("Room Deleted Successfully");
                }}
                itemName={`Room ${deleteModal.room?.room_number || 'this room'}`}
                itemType="room"
                deleteEndpoint={`/admin/api/delete_room/${deleteModal?.room?.id}`}
            />
            
            <EditRoom 
                isOpen={isEditModalOpen} 
                onClose={() => setIsEditModalOpen(false)}
                initialData={initialData}
                accommodations={accommodations || []}
            />
        </>
    );
}

