import { useState, useEffect } from 'react';
import { useParams } from 'react-router';
import { useTranslation } from 'react-i18next';
import type { RoomFull } from '@house-plan-maker/shared';
import { getRoomFull } from '../api/client';
import { LoadingSpinner } from '../components/ui/LoadingSpinner';
import { ErrorBanner } from '../components/ui/ErrorBanner';
import { EditorProvider } from '../components/editor/context/EditorContext';
import { UndoRedoProvider } from '../components/editor/context/UndoRedoContext';
import { RoomEditorLayout } from '../components/editor/RoomEditorLayout';

export function RoomEditorPage() {
  const { t } = useTranslation();
  const { roomId } = useParams<{ id: string; roomId: string }>();
  const [room, setRoom] = useState<RoomFull | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    if (!roomId) return;

    const fetchRoom = async () => {
      try {
        const fullRoom = await getRoomFull(roomId);
        setRoom(fullRoom);
      } catch (err: unknown) {
        const message = err instanceof Error ? err.message : t('editor.error.load');
        setError(message);
      } finally {
        setLoading(false);
      }
    };

    fetchRoom();
  }, [roomId, t]);

  if (loading) {
    return <LoadingSpinner />;
  }

  if (error || !room) {
    return <ErrorBanner message={error ?? t('editor.roomNotFound')} />;
  }

  return (
    <EditorProvider room={room}>
      <UndoRedoProvider>
        <RoomEditorLayout roomId={room.id} />
      </UndoRedoProvider>
    </EditorProvider>
  );
}
