'use client';

import { useState, useEffect } from 'react';
import { collectionApi, searchApi } from '../../lib/api';
import { Collection, Story } from '../../types/api';
import Button from '../ui/Button';
import { Input } from '../ui/Input';
import LoadingSpinner from '../ui/LoadingSpinner';

interface AddToCollectionModalProps {
  isOpen: boolean;
  onClose: () => void;
  collection: Collection;
  onUpdate: () => void;
}

export default function AddToCollectionModal({
  isOpen,
  onClose,
  collection,
  onUpdate
}: AddToCollectionModalProps) {
  const [searchQuery, setSearchQuery] = useState('');
  const [availableStories, setAvailableStories] = useState<Story[]>([]);
  const [selectedStoryIds, setSelectedStoryIds] = useState<string[]>([]);
  const [loading, setLoading] = useState(false);
  const [adding, setAdding] = useState(false);

  // Get IDs of stories already in the collection
  const existingStoryIds = collection.collectionStories?.map(cs => cs.story.id) || [];

  useEffect(() => {
    if (isOpen) {
      loadStories();
    }
  }, [isOpen, searchQuery]);

  const loadStories = async () => {
    try {
      setLoading(true);
      const result = await searchApi.search({
        query: searchQuery || '*',
        page: 0,
        size: 50,
      });
      
      // Filter out stories already in the collection
      const filteredStories = result.results.filter(
        story => !existingStoryIds.includes(story.id)
      );
      
      setAvailableStories(filteredStories);
    } catch (error) {
      console.error('Failed to load stories:', error);
    } finally {
      setLoading(false);
    }
  };

  const toggleStorySelection = (storyId: string) => {
    setSelectedStoryIds(prev => 
      prev.includes(storyId)
        ? prev.filter(id => id !== storyId)
        : [...prev, storyId]
    );
  };

  const handleAddStories = async () => {
    if (selectedStoryIds.length === 0) return;

    try {
      setAdding(true);
      await collectionApi.addStoriesToCollection(collection.id, selectedStoryIds);
      onUpdate();
      onClose();
      setSelectedStoryIds([]);
    } catch (error) {
      console.error('Failed to add stories to collection:', error);
    } finally {
      setAdding(false);
    }
  };

  const handleClose = () => {
    if (!adding) {
      setSelectedStoryIds([]);
      setSearchQuery('');
      onClose();
    }
  };

  if (!isOpen) return null;

  return (
    <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 p-4">
      <div className="theme-card max-w-2xl w-full max-h-[80vh] overflow-hidden flex flex-col">
        {/* Header */}
        <div className="flex items-center justify-between p-6 border-b theme-border">
          <h2 className="text-xl font-semibold theme-header">
            Add Stories to "{collection.name}"
          </h2>
          <button
            onClick={handleClose}
            disabled={adding}
            className="text-gray-500 hover:text-gray-700 disabled:opacity-50"
          >
            ×
          </button>
        </div>

        {/* Search */}
        <div className="p-6 border-b theme-border">
          <Input
            type="search"
            value={searchQuery}
            onChange={(e) => setSearchQuery(e.target.value)}
            placeholder="Search stories to add..."
            className="w-full"
          />
        </div>

        {/* Stories List */}
        <div className="flex-1 overflow-y-auto p-6">
          {loading ? (
            <div className="flex justify-center py-8">
              <LoadingSpinner size="md" />
            </div>
          ) : availableStories.length === 0 ? (
            <div className="text-center py-8 theme-text opacity-70">
              {searchQuery ? 'No stories found matching your search.' : 'All stories are already in this collection.'}
            </div>
          ) : (
            <div className="space-y-3">
              {availableStories.map((story) => {
                const isSelected = selectedStoryIds.includes(story.id);
                return (
                  <div
                    key={story.id}
                    className={`p-3 rounded-lg border cursor-pointer transition-colors ${
                      isSelected
                        ? 'border-blue-500 bg-blue-50'
                        : 'theme-border hover:border-gray-400'
                    }`}
                    onClick={() => toggleStorySelection(story.id)}
                  >
                    <div className="flex items-center gap-3">
                      <input
                        type="checkbox"
                        checked={isSelected}
                        onChange={() => toggleStorySelection(story.id)}
                        className="rounded border-gray-300 text-blue-600 focus:ring-blue-500"
                      />
                      <div className="flex-1 min-w-0">
                        <h3 className="font-medium theme-text truncate">
                          {story.title}
                        </h3>
                        <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>
                    </div>
                  </div>
                );
              })}
            </div>
          )}
        </div>

        {/* Footer */}
        <div className="flex items-center justify-between p-6 border-t theme-border">
          <div className="text-sm theme-text opacity-70">
            {selectedStoryIds.length} stories selected
          </div>
          <div className="flex gap-3">
            <Button
              variant="ghost"
              onClick={handleClose}
              disabled={adding}
            >
              Cancel
            </Button>
            <Button
              onClick={handleAddStories}
              disabled={selectedStoryIds.length === 0 || adding}
            >
              {adding ? <LoadingSpinner size="sm" /> : `Add ${selectedStoryIds.length} Stories`}
            </Button>
          </div>
        </div>
      </div>
    </div>
  );
}