'use client';

import React, { useEffect, useState } from 'react';
import LoadingSpinner from './LoadingSpinner';

interface LibrarySwitchLoaderProps {
  isVisible: boolean;
  targetLibraryName?: string;
  onComplete: () => void;
  onError: (error: string) => void;
}

export default function LibrarySwitchLoader({ 
  isVisible, 
  targetLibraryName, 
  onComplete, 
  onError 
}: LibrarySwitchLoaderProps) {
  const [dots, setDots] = useState('');
  const [timeElapsed, setTimeElapsed] = useState(0);

  useEffect(() => {
    if (!isVisible) return;

    // Animate dots
    const dotsInterval = setInterval(() => {
      setDots(prev => prev.length >= 3 ? '' : prev + '.');
    }, 500);

    // Track time elapsed
    const timeInterval = setInterval(() => {
      setTimeElapsed(prev => prev + 1);
    }, 1000);

    // Poll for completion
    const pollInterval = setInterval(async () => {
      try {
        const response = await fetch('/api/libraries/switch/status');
        if (response.ok) {
          const data = await response.json();
          if (data.ready) {
            clearInterval(pollInterval);
            clearInterval(dotsInterval);
            clearInterval(timeInterval);
            onComplete();
          }
        }
      } catch (error) {
        console.error('Error polling switch status:', error);
      }
    }, 1000);

    // Timeout after 30 seconds
    const timeout = setTimeout(() => {
      clearInterval(pollInterval);
      clearInterval(dotsInterval);
      clearInterval(timeInterval);
      onError('Library switch timed out. Please try again.');
    }, 30000);

    return () => {
      clearInterval(dotsInterval);
      clearInterval(timeInterval);
      clearInterval(pollInterval);
      clearTimeout(timeout);
    };
  }, [isVisible, onComplete, onError]);

  if (!isVisible) return null;

  return (
    <div className="fixed inset-0 bg-black/80 backdrop-blur-sm z-50 flex items-center justify-center">
      <div className="bg-white dark:bg-gray-800 rounded-lg p-8 max-w-sm w-full mx-4 text-center shadow-2xl">
        <div className="mb-6">
          <LoadingSpinner size="lg" />
        </div>
        
        <h2 className="text-xl font-semibold mb-2 text-gray-900 dark:text-white">
          Switching Libraries
        </h2>
        
        <p className="text-gray-600 dark:text-gray-300 mb-4">
          {targetLibraryName ? 
            `Loading "${targetLibraryName}"${dots}` : 
            `Preparing your library${dots}`
          }
        </p>
        
        <div className="text-sm text-gray-500 dark:text-gray-400">
          <p>This may take a few seconds...</p>
          {timeElapsed > 5 && (
            <p className="mt-2 text-orange-600 dark:text-orange-400">
              Still working ({timeElapsed}s)
            </p>
          )}
        </div>

        <div className="mt-6 p-3 bg-blue-50 dark:bg-blue-900/20 rounded-lg">
          <p className="text-xs text-blue-700 dark:text-blue-300">
            💡 Libraries are completely separate datasets with their own stories, authors, and settings.
          </p>
        </div>
      </div>
    </div>
  );
}