'use client';

import { useState, useEffect } from 'react';
import { Collection, Story } from '../../types/api';
import { collectionApi, getImageUrl } from '../../lib/api';
import Link from 'next/link';
import Button from '../ui/Button';

interface StoryReorderListProps {
  collection: Collection;
  onUpdate: () => void;
}

export default function StoryReorderList({ collection, onUpdate }: StoryReorderListProps) {
  const [draggedIndex, setDraggedIndex] = useState<number | null>(null);
  const [reordering, setReordering] = useState(false);
  const [localStories, setLocalStories] = useState(collection.collectionStories || []);

  // Update local stories when collection changes
  useEffect(() => {
    setLocalStories(collection.collectionStories || []);
  }, [collection.collectionStories]);

  const stories = localStories;

  const handleDragStart = (e: React.DragEvent, index: number) => {
    setDraggedIndex(index);
    e.dataTransfer.effectAllowed = 'move';
    e.dataTransfer.setData('text/html', '');
  };

  const handleDragEnd = () => {
    setDraggedIndex(null);
  };

  const handleDragOver = (e: React.DragEvent) => {
    e.preventDefault();
    e.dataTransfer.dropEffect = 'move';
  };

  const handleDrop = async (e: React.DragEvent, dropIndex: number) => {
    e.preventDefault();
    
    if (draggedIndex === null || draggedIndex === dropIndex || reordering) {
      return;
    }

    // Optimistic update - update local state immediately
    const newStories = [...stories];
    const [draggedStory] = newStories.splice(draggedIndex, 1);
    newStories.splice(dropIndex, 0, draggedStory);
    setLocalStories(newStories);

    try {
      setReordering(true);

      // Create reorder request with new positions
      const storyOrders = newStories.map((storyItem, index) => ({
        storyId: storyItem.story.id,
        position: index + 1,
      }));

      await collectionApi.reorderStories(collection.id, storyOrders);
      // Don't call onUpdate() to avoid page reload - the local state is already correct
    } catch (error) {
      console.error('Failed to reorder stories:', error);
      // On error, refresh to get the correct order
      onUpdate();
    } finally {
      setReordering(false);
      setDraggedIndex(null);
    }
  };

  const handleRemoveStory = async (storyId: string) => {
    if (confirm('Remove this story from the collection?')) {
      try {
        await collectionApi.removeStoryFromCollection(collection.id, storyId);
        onUpdate();
      } catch (error) {
        console.error('Failed to remove story:', error);
      }
    }
  };

  const moveStoryUp = async (index: number) => {
    if (index === 0 || reordering) return;
    
    // Optimistic update - update local state immediately
    const newStories = [...stories];
    [newStories[index - 1], newStories[index]] = [newStories[index], newStories[index - 1]];
    setLocalStories(newStories);
    
    try {
      setReordering(true);
      
      const storyOrders = newStories.map((storyItem, idx) => ({
        storyId: storyItem.story.id,
        position: idx + 1,
      }));

      await collectionApi.reorderStories(collection.id, storyOrders);
      // Don't call onUpdate() to avoid page reload
    } catch (error) {
      console.error('Failed to reorder stories:', error);
      // On error, refresh to get the correct order
      onUpdate();
    } finally {
      setReordering(false);
    }
  };

  const moveStoryDown = async (index: number) => {
    if (index === stories.length - 1 || reordering) return;
    
    // Optimistic update - update local state immediately
    const newStories = [...stories];
    [newStories[index], newStories[index + 1]] = [newStories[index + 1], newStories[index]];
    setLocalStories(newStories);
    
    try {
      setReordering(true);
      
      const storyOrders = newStories.map((storyItem, idx) => ({
        storyId: storyItem.story.id,
        position: idx + 1,
      }));

      await collectionApi.reorderStories(collection.id, storyOrders);
      // Don't call onUpdate() to avoid page reload
    } catch (error) {
      console.error('Failed to reorder stories:', error);
      // On error, refresh to get the correct order
      onUpdate();
    } finally {
      setReordering(false);
    }
  };

  if (stories.length === 0) {
    return (
      <div className="text-center py-8 theme-text opacity-70">
        <p className="mb-4">No stories in this collection yet.</p>
        <p className="text-sm">Add stories to start building your collection.</p>
      </div>
    );
  }

  return (
    <div className="space-y-3">
      {stories.map((storyItem, index) => {
        const story = storyItem.story;
        const isDragging = draggedIndex === index;
        
        return (
          <div
            key={`${story.id}-${index}`}
            draggable={!reordering}
            onDragStart={(e) => handleDragStart(e, index)}
            onDragEnd={handleDragEnd}
            onDragOver={handleDragOver}
            onDrop={(e) => handleDrop(e, index)}
            className={`
              flex items-center gap-4 p-4 theme-card rounded-lg border transition-all duration-200
              ${isDragging ? 'opacity-50 scale-95' : 'hover:border-gray-400'}
              ${reordering ? 'pointer-events-none' : 'cursor-move'}
            `}
          >
            {/* Drag Handle */}
            <div className="flex flex-col items-center text-gray-400 hover:text-gray-600">
              <div className="text-xs font-mono bg-gray-100 px-2 py-1 rounded mb-1">
                {index + 1}
              </div>
              <div className="flex flex-col gap-1">
                <div className="w-3 h-1 bg-gray-300 rounded"></div>
                <div className="w-3 h-1 bg-gray-300 rounded"></div>
                <div className="w-3 h-1 bg-gray-300 rounded"></div>
              </div>
            </div>

            {/* Story Cover */}
            <div className="w-12 h-16 flex-shrink-0 rounded overflow-hidden bg-gray-100">
              {story.coverPath ? (
                <img
                  src={getImageUrl(story.coverPath)}
                  alt={`${story.title} cover`}
                  className="w-full h-full object-cover"
                />
              ) : (
                <div className="w-full h-full flex items-center justify-center bg-gradient-to-br from-blue-100 to-purple-100">
                  <span className="text-xs font-bold text-gray-600">
                    {story.title.charAt(0)}
                  </span>
                </div>
              )}
            </div>

            {/* Story Details */}
            <div className="flex-1 min-w-0">
              <Link
                href={`/stories/${story.id}`}
                className="block hover:underline"
              >
                <h3 className="font-medium theme-header truncate">
                  {story.title}
                </h3>
              </Link>
              <p className="text-sm theme-text opacity-70 truncate">
                by {story.authorName}
              </p>
              <div className="flex items-center gap-4 mt-1 text-xs theme-text opacity-60">
                <span>{story.wordCount?.toLocaleString()} words</span>
                {story.rating && (
                  <span className="flex items-center">
                    ★ {story.rating}
                  </span>
                )}
              </div>
            </div>

            {/* Action Buttons */}
            <div className="flex flex-col gap-1">
              <button
                onClick={() => moveStoryUp(index)}
                disabled={index === 0 || reordering}
                className="p-1 text-gray-400 hover:text-gray-600 disabled:opacity-30 disabled:cursor-not-allowed"
                title="Move up"
              >
                ↑
              </button>
              <button
                onClick={() => moveStoryDown(index)}
                disabled={index === stories.length - 1 || reordering}
                className="p-1 text-gray-400 hover:text-gray-600 disabled:opacity-30 disabled:cursor-not-allowed"
                title="Move down"
              >
                ↓
              </button>
            </div>

            {/* Remove Button */}
            <button
              onClick={() => handleRemoveStory(story.id)}
              disabled={reordering}
              className="p-2 text-red-500 hover:text-red-700 disabled:opacity-30 disabled:cursor-not-allowed"
              title="Remove from collection"
            >
              ×
            </button>
          </div>
        );
      })}

      {reordering && (
        <div className="text-center py-4 theme-text opacity-70">
          <span className="inline-flex items-center gap-2">
            <div className="w-4 h-4 border-2 border-blue-500 border-t-transparent rounded-full animate-spin"></div>
            Reordering stories...
          </span>
        </div>
      )}
    </div>
  );
}