'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 CollectionForm from '../../../../components/collections/CollectionForm';
import LoadingSpinner from '../../../../components/ui/LoadingSpinner';

export default function EditCollectionPage() {
  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 [saving, setSaving] = useState(false);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    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);
      }
    };

    if (collectionId) {
      loadCollection();
    }
  }, [collectionId]);

  const handleSubmit = async (formData: {
    name: string;
    description?: string;
    tags?: string[];
    storyIds?: string[];
    coverImage?: File;
  }) => {
    if (!collection) return;

    try {
      setSaving(true);
      setError(null);

      // Update basic info
      await collectionApi.updateCollection(collection.id, {
        name: formData.name,
        description: formData.description,
        tagNames: formData.tags,
      });

      // Upload cover image if provided
      if (formData.coverImage) {
        await collectionApi.uploadCover(collection.id, formData.coverImage);
      }

      // Redirect back to collection detail
      router.push(`/collections/${collection.id}`);
    } catch (err: any) {
      console.error('Failed to update collection:', err);
      setError(err.response?.data?.message || 'Failed to update collection');
    } finally {
      setSaving(false);
    }
  };

  const handleCancel = () => {
    router.push(`/collections/${collectionId}`);
  };

  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>
    );
  }

  const initialData = {
    name: collection.name,
    description: collection.description,
    tags: collection.tags?.map(tag => tag.name) || [],
    storyIds: collection.collectionStories?.map(cs => cs.story.id) || [],
    stories: collection.collectionStories?.map(cs => cs.story) || [],
    coverImagePath: collection.coverImagePath,
  };

  return (
    <AppLayout>
      <div className="max-w-2xl mx-auto">
        <div className="mb-6">
          <h1 className="text-3xl font-bold theme-header">Edit Collection</h1>
          <p className="theme-text mt-2">
            Update your collection details and organization.
          </p>
        </div>

        {error && (
          <div className="mb-6 p-4 bg-red-100 border border-red-300 text-red-700 rounded-lg">
            {error}
          </div>
        )}

        <CollectionForm
          initialData={initialData}
          onSubmit={handleSubmit}
          onCancel={handleCancel}
          loading={saving}
          submitLabel="Update Collection"
        />
      </div>
    </AppLayout>
  );
}