'use client';

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

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

  const [collection, setCollection] = useState<Collection | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  const loadCollection = async () => {
    try {
      setLoading(true);
      setError(null);
      const data = await collectionApi.getCollection(collectionId);
      setCollection(data);
    } catch (err: any) {
      console.error('Failed to load collection:', err);
      setError(err.response?.data?.message || 'Failed to load collection');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    if (collectionId) {
      loadCollection();
    }
  }, [collectionId]);

  const handleCollectionUpdate = () => {
    loadCollection();
  };

  const handleCollectionDelete = () => {
    router.push('/collections');
  };

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

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

  return (
    <AppLayout>
      <CollectionDetailView
        collection={collection}
        onUpdate={handleCollectionUpdate}
        onDelete={handleCollectionDelete}
      />
    </AppLayout>
  );
}