import React, { useState, useEffect } from "react";
import { useTranslation } from "react-i18next";
import KPIBar from "./components/KPIBar";
import RoomGrid from "./components/RoomGrid";
import RoomDetailModal from "./components/RoomDetailModal";
import { getRoomsWithStatus, getDashboardKPIs, updateRoomStatus } from "../../services/roomService";

export default function RoomDashboard() {
  const { t } = useTranslation();
  const [rooms, setRooms] = useState([]);
  const [kpis, setKpis] = useState({});
  const [selectedRoom, setSelectedRoom] = useState(null);
  const [loading, setLoading] = useState(true);

  const fetchData = async () => {
    try {
      const [roomsRes, kpisRes] = await Promise.all([
        getRoomsWithStatus(),
        getDashboardKPIs(),
      ]);
      setRooms(roomsRes.data.rooms);
      setKpis(kpisRes.data);
    } catch (error) {
      console.error(error);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => { fetchData(); }, []);

  const handleStatusChange = async (roomId, newStatus) => {
    await updateRoomStatus(roomId, newStatus);
    fetchData();
    setSelectedRoom(null);
  };

  if (loading) return <div className="empty-state"><p>{t('common.loading')}</p></div>;

  return (
    <div>
      <div className="page-header">
        <h2>{t('rooms.title')}</h2>
      </div>
      <KPIBar kpis={kpis} />
      <div style={{ marginTop: 'var(--space-xl)' }}>
        <RoomGrid rooms={rooms} onRoomClick={setSelectedRoom} />
      </div>
      {selectedRoom && (
        <RoomDetailModal
          room={selectedRoom}
          onClose={() => setSelectedRoom(null)}
          onStatusChange={handleStatusChange}
        />
      )}
    </div>
  );
}
