'use client';

import { useState, useEffect } from 'react';
import { useParams, useRouter } from 'next/navigation';
import { collectionApi } from '../../../../../lib/api';
import { StoryWithCollectionContext } from '../../../../../types/api';
import AppLayout from '../../../../../components/layout/AppLayout';
import CollectionReadingView from '../../../../../components/collections/CollectionReadingView';
import LoadingSpinner from '../../../../../components/ui/LoadingSpinner';

export default function CollectionReadingPage() {
  const params = useParams();
  const router = useRouter();
  const collectionId = params.id as string;
  const storyId = params.storyId as string;

  const [data, setData] = useState<StoryWithCollectionContext | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    const loadStoryWithContext = async () => {
      if (!collectionId || !storyId) return;

      try {
        setLoading(true);
        setError(null);
        const result = await collectionApi.getStoryWithCollectionContext(collectionId, storyId);
        setData(result);
      } catch (err: any) {
        console.error('Failed to load story with collection context:', err);
        setError(err.response?.data?.message || 'Failed to load story');
      } finally {
        setLoading(false);
      }
    };

    loadStoryWithContext();
  }, [collectionId, storyId]);

  const handleNavigate = (newStoryId: string) => {
    router.push(`/collections/${collectionId}/read/${newStoryId}`);
  };

  if (loading) {
    return (
      <AppLayout>
        <div className="flex items-center justify-center py-20">
          <LoadingSpinner size="lg" />
        </div>
      </AppLayout>
    );
  }

  if (error || !data) {
    return (
      <AppLayout>
        <div className="text-center py-20">
          <div className="text-red-600 text-lg mb-4">
            {error || 'Story not found'}
          </div>
          <button
            onClick={() => router.push(`/collections/${collectionId}`)}
            className="theme-accent hover:underline"
          >
            Back to Collection
          </button>
        </div>
      </AppLayout>
    );
  }

  return (
    <AppLayout>
      <CollectionReadingView
        data={data}
        onNavigate={handleNavigate}
        onBackToCollection={() => router.push(`/collections/${collectionId}`)}
      />
    </AppLayout>
  );
}