'use client';

import { useState } from 'react';
import { Story } from '../../types/api';
import StoryCard from './StoryCard';
import StorySelectionToolbar from './StorySelectionToolbar';

interface StoryMultiSelectProps {
  stories: Story[];
  viewMode: 'grid' | 'list';
  onUpdate?: () => void;
  allowMultiSelect?: boolean;
}

export default function StoryMultiSelect({
  stories,
  viewMode,
  onUpdate,
  allowMultiSelect = true
}: StoryMultiSelectProps) {
  const [selectedStoryIds, setSelectedStoryIds] = useState<string[]>([]);
  const [isSelectionMode, setIsSelectionMode] = useState(false);

  const handleStorySelect = (storyId: string) => {
    setSelectedStoryIds(prev => {
      if (prev.includes(storyId)) {
        const newSelection = prev.filter(id => id !== storyId);
        if (newSelection.length === 0) {
          setIsSelectionMode(false);
        }
        return newSelection;
      } else {
        if (!isSelectionMode) {
          setIsSelectionMode(true);
        }
        return [...prev, storyId];
      }
    });
  };

  const handleSelectAll = () => {
    if (selectedStoryIds.length === stories.length) {
      setSelectedStoryIds([]);
      setIsSelectionMode(false);
    } else {
      setSelectedStoryIds(stories.map(story => story.id));
      setIsSelectionMode(true);
    }
  };

  const handleClearSelection = () => {
    setSelectedStoryIds([]);
    setIsSelectionMode(false);
  };

  const handleBatchOperation = (operation: string) => {
    // This will trigger the appropriate action based on the operation
    console.log(`Batch operation: ${operation} on stories:`, selectedStoryIds);
    // After operation, clear selection
    setSelectedStoryIds([]);
    setIsSelectionMode(false);
    onUpdate?.();
  };

  if (stories.length === 0) {
    return (
      <div className="text-center py-20">
        <div className="theme-text text-lg mb-4">
          No stories found
        </div>
      </div>
    );
  }

  return (
    <div className="space-y-4">
      {/* Selection Toolbar */}
      {allowMultiSelect && (
        <StorySelectionToolbar
          selectedCount={selectedStoryIds.length}
          totalCount={stories.length}
          isSelectionMode={isSelectionMode}
          onSelectAll={handleSelectAll}
          onClearSelection={handleClearSelection}
          onBatchOperation={handleBatchOperation}
          selectedStoryIds={selectedStoryIds}
        />
      )}

      {/* Stories Grid/List */}
      <div className={
        viewMode === 'grid'
          ? 'grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6'
          : 'space-y-4'
      }>
        {stories.map((story) => (
          <div key={story.id} className="relative">
            {/* Selection Checkbox */}
            {allowMultiSelect && (isSelectionMode || selectedStoryIds.includes(story.id)) && (
              <div className="absolute top-2 left-2 z-10">
                <input
                  type="checkbox"
                  checked={selectedStoryIds.includes(story.id)}
                  onChange={(e) => {
                    e.stopPropagation(); // Prevent checkbox clicks from interfering
                    handleStorySelect(story.id);
                  }}
                  className="w-5 h-5 rounded border-gray-300 text-blue-600 focus:ring-blue-500 bg-white shadow-lg"
                />
              </div>
            )}

            {/* Story Card */}
            <div
              className={`transition-all duration-200 ${
                selectedStoryIds.includes(story.id) ? 'ring-2 ring-blue-500 ring-opacity-50' : ''
              }`}
            >
              <StoryCard
                story={story}
                viewMode={viewMode}
                onUpdate={onUpdate}
                showSelection={isSelectionMode}
                isSelected={selectedStoryIds.includes(story.id)}
                onSelect={() => handleStorySelect(story.id)}
              />
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}