'use client';

import { useState } from 'react';
import { useRouter } from 'next/navigation';
import { DocumentArrowUpIcon } from '@heroicons/react/24/outline';
import Button from '@/components/ui/Button';
import { Input } from '@/components/ui/Input';
import ImportLayout from '@/components/layout/ImportLayout';

interface EPUBImportResponse {
  success: boolean;
  message: string;
  storyId?: string;
  storyTitle?: string;
  totalChapters?: number;
  wordCount?: number;
  readingPosition?: any;
  warnings?: string[];
  errors?: string[];
}

export default function EPUBImportPage() {
  const router = useRouter();
  const [selectedFile, setSelectedFile] = useState<File | null>(null);
  const [isLoading, setIsLoading] = useState(false);
  const [isValidating, setIsValidating] = useState(false);
  const [validationResult, setValidationResult] = useState<any>(null);
  const [importResult, setImportResult] = useState<EPUBImportResponse | null>(null);
  const [error, setError] = useState<string | null>(null);
  
  // Import options
  const [authorName, setAuthorName] = useState<string>('');
  const [seriesName, setSeriesName] = useState<string>('');
  const [seriesVolume, setSeriesVolume] = useState<string>('');
  const [tags, setTags] = useState<string>('');
  const [preserveReadingPosition, setPreserveReadingPosition] = useState(true);
  const [overwriteExisting, setOverwriteExisting] = useState(false);
  const [createMissingAuthor, setCreateMissingAuthor] = useState(true);
  const [createMissingSeries, setCreateMissingSeries] = useState(true);

  const handleFileChange = async (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (file) {
      setSelectedFile(file);
      setValidationResult(null);
      setImportResult(null);
      setError(null);
      
      if (file.name.toLowerCase().endsWith('.epub')) {
        await validateFile(file);
      } else {
        setError('Please select a valid EPUB file (.epub extension)');
      }
    }
  };

  const validateFile = async (file: File) => {
    setIsValidating(true);
    try {
      const token = localStorage.getItem('auth-token');
      const formData = new FormData();
      formData.append('file', file);

      const response = await fetch('/api/stories/epub/validate', {
        method: 'POST',
        headers: {
          'Authorization': token ? `Bearer ${token}` : '',
        },
        body: formData,
      });

      if (response.ok) {
        const result = await response.json();
        setValidationResult(result);
        if (!result.valid) {
          setError('EPUB file validation failed: ' + result.errors.join(', '));
        }
      } else if (response.status === 401 || response.status === 403) {
        setError('Authentication required. Please log in.');
      } else {
        setError('Failed to validate EPUB file');
      }
    } catch (err) {
      setError('Error validating EPUB file: ' + (err as Error).message);
    } finally {
      setIsValidating(false);
    }
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    
    if (!selectedFile) {
      setError('Please select an EPUB file');
      return;
    }

    if (validationResult && !validationResult.valid) {
      setError('Cannot import invalid EPUB file');
      return;
    }

    setIsLoading(true);
    setError(null);

    try {
      const token = localStorage.getItem('auth-token');
      const formData = new FormData();
      formData.append('file', selectedFile);
      
      if (authorName) formData.append('authorName', authorName);
      if (seriesName) formData.append('seriesName', seriesName);
      if (seriesVolume) formData.append('seriesVolume', seriesVolume);
      if (tags) {
        const tagList = tags.split(',').map(t => t.trim()).filter(t => t.length > 0);
        tagList.forEach(tag => formData.append('tags', tag));
      }
      
      formData.append('preserveReadingPosition', preserveReadingPosition.toString());
      formData.append('overwriteExisting', overwriteExisting.toString());
      formData.append('createMissingAuthor', createMissingAuthor.toString());
      formData.append('createMissingSeries', createMissingSeries.toString());

      const response = await fetch('/api/stories/epub/import', {
        method: 'POST',
        headers: {
          'Authorization': token ? `Bearer ${token}` : '',
        },
        body: formData,
      });

      const result = await response.json();

      if (response.ok && result.success) {
        setImportResult(result);
      } else if (response.status === 401 || response.status === 403) {
        setError('Authentication required. Please log in.');
      } else {
        setError(result.message || 'Failed to import EPUB');
      }
    } catch (err) {
      setError('Error importing EPUB: ' + (err as Error).message);
    } finally {
      setIsLoading(false);
    }
  };

  const resetForm = () => {
    setSelectedFile(null);
    setValidationResult(null);
    setImportResult(null);
    setError(null);
    setAuthorName('');
    setSeriesName('');
    setSeriesVolume('');
    setTags('');
  };

  if (importResult?.success) {
    return (
      <ImportLayout
        title="EPUB Import Successful"
        description="Your EPUB has been successfully imported into StoryCove"
      >
        <div className="space-y-6">
          <div className="bg-green-50 dark:bg-green-900/20 border border-green-200 dark:border-green-800 rounded-lg p-6">
            <h2 className="text-xl font-semibold text-green-600 dark:text-green-400 mb-2">Import Completed</h2>
            <p className="theme-text">
              Your EPUB has been successfully imported into StoryCove.
            </p>
          </div>
          
          <div className="theme-card theme-shadow rounded-lg p-6">
            <div className="space-y-4">
              <div>
                <span className="font-semibold theme-header">Story Title:</span>
                <p className="theme-text">{importResult.storyTitle}</p>
              </div>
              
              {importResult.wordCount && (
                <div>
                  <span className="font-semibold theme-header">Word Count:</span>
                  <p className="theme-text">{importResult.wordCount.toLocaleString()} words</p>
                </div>
              )}
              
              {importResult.totalChapters && (
                <div>
                  <span className="font-semibold theme-header">Chapters:</span>
                  <p className="theme-text">{importResult.totalChapters}</p>
                </div>
              )}

              {importResult.warnings && importResult.warnings.length > 0 && (
                <div className="bg-yellow-50 dark:bg-yellow-900/20 border border-yellow-200 dark:border-yellow-800 rounded-lg p-4">
                  <strong className="text-yellow-800 dark:text-yellow-200">Warnings:</strong>
                  <ul className="list-disc list-inside mt-2 text-yellow-700 dark:text-yellow-300">
                    {importResult.warnings.map((warning, index) => (
                      <li key={index}>{warning}</li>
                    ))}
                  </ul>
                </div>
              )}

              <div className="flex gap-4 mt-6">
                <Button
                  onClick={() => router.push(`/stories/${importResult.storyId}`)}
                >
                  View Story
                </Button>
                <Button
                  onClick={resetForm}
                  variant="secondary"
                >
                  Import Another EPUB
                </Button>
              </div>
            </div>
          </div>
        </div>
      </ImportLayout>
    );
  }

  return (
    <ImportLayout
      title="Import EPUB"
      description="Upload an EPUB file to import it as a story into your library"
    >
      {error && (
        <div className="bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-lg p-4 mb-6">
          <p className="text-red-800 dark:text-red-200">{error}</p>
        </div>
      )}

      <form onSubmit={handleSubmit} className="space-y-6">
        {/* File Upload */}
        <div className="theme-card theme-shadow rounded-lg p-6">
          <div className="mb-4">
            <h3 className="text-lg font-semibold theme-header mb-2">Select EPUB File</h3>
            <p className="theme-text">
              Choose an EPUB file from your device to import.
            </p>
          </div>
          <div className="space-y-4">
            <div>
              <label htmlFor="epub-file" className="block text-sm font-medium theme-header mb-1">EPUB File</label>
              <Input
                id="epub-file"
                type="file"
                accept=".epub,application/epub+zip"
                onChange={handleFileChange}
                disabled={isLoading || isValidating}
              />
            </div>

            {selectedFile && (
              <div className="flex items-center gap-2">
                <DocumentArrowUpIcon className="h-5 w-5 theme-text" />
                <span className="text-sm theme-text">
                  {selectedFile.name} ({(selectedFile.size / 1024 / 1024).toFixed(2)} MB)
                </span>
              </div>
            )}

            {isValidating && (
              <div className="text-sm theme-accent">
                Validating EPUB file...
              </div>
            )}

            {validationResult && (
              <div className="text-sm">
                {validationResult.valid ? (
                  <span className="inline-flex items-center px-2 py-1 rounded text-xs font-medium bg-green-100 dark:bg-green-900/20 text-green-800 dark:text-green-200">
                    Valid EPUB
                  </span>
                ) : (
                  <span className="inline-flex items-center px-2 py-1 rounded text-xs font-medium bg-red-100 dark:bg-red-900/20 text-red-800 dark:text-red-200">
                    Invalid EPUB
                  </span>
                )}
              </div>
            )}
          </div>
        </div>

        {/* Import Options */}
        <div className="theme-card theme-shadow rounded-lg p-6">
          <div className="mb-4">
            <h3 className="text-lg font-semibold theme-header mb-2">Import Options</h3>
            <p className="theme-text">
              Configure how the EPUB should be imported.
            </p>
          </div>
          <div className="space-y-4">
            <div>
              <label htmlFor="author-name" className="block text-sm font-medium theme-header mb-1">Author Name (Override)</label>
              <Input
                id="author-name"
                value={authorName}
                onChange={(e) => setAuthorName(e.target.value)}
                placeholder="Leave empty to use EPUB metadata"
              />
            </div>

            <div>
              <label htmlFor="series-name" className="block text-sm font-medium theme-header mb-1">Series Name</label>
              <Input
                id="series-name"
                value={seriesName}
                onChange={(e) => setSeriesName(e.target.value)}
                placeholder="Optional: Add to a series"
              />
            </div>

            {seriesName && (
              <div>
                <label htmlFor="series-volume" className="block text-sm font-medium theme-header mb-1">Series Volume</label>
                <Input
                  id="series-volume"
                  type="number"
                  value={seriesVolume}
                  onChange={(e) => setSeriesVolume(e.target.value)}
                  placeholder="Volume number in series"
                />
              </div>
            )}

            <div>
              <label htmlFor="tags" className="block text-sm font-medium theme-header mb-1">Tags</label>
              <Input
                id="tags"
                value={tags}
                onChange={(e) => setTags(e.target.value)}
                placeholder="Comma-separated tags (e.g., fantasy, adventure, romance)"
              />
            </div>

            <div className="space-y-3">
              <div className="flex items-center">
                <input
                  type="checkbox"
                  id="preserve-reading-position"
                  checked={preserveReadingPosition}
                  onChange={(e) => setPreserveReadingPosition(e.target.checked)}
                  className="mr-2"
                />
                <label htmlFor="preserve-reading-position" className="text-sm theme-text">
                  Preserve reading position from EPUB metadata
                </label>
              </div>

              <div className="flex items-center">
                <input
                  type="checkbox"
                  id="create-missing-author"
                  checked={createMissingAuthor}
                  onChange={(e) => setCreateMissingAuthor(e.target.checked)}
                  className="mr-2"
                />
                <label htmlFor="create-missing-author" className="text-sm theme-text">
                  Create author if not found
                </label>
              </div>

              <div className="flex items-center">
                <input
                  type="checkbox"
                  id="create-missing-series"
                  checked={createMissingSeries}
                  onChange={(e) => setCreateMissingSeries(e.target.checked)}
                  className="mr-2"
                />
                <label htmlFor="create-missing-series" className="text-sm theme-text">
                  Create series if not found
                </label>
              </div>

              <div className="flex items-center">
                <input
                  type="checkbox"
                  id="overwrite-existing"
                  checked={overwriteExisting}
                  onChange={(e) => setOverwriteExisting(e.target.checked)}
                  className="mr-2"
                />
                <label htmlFor="overwrite-existing" className="text-sm theme-text">
                  Overwrite existing story with same title and author
                </label>
              </div>
            </div>
          </div>
        </div>

        {/* Submit Button */}
        <div className="flex justify-end">
          <Button
            type="submit"
            disabled={!selectedFile || isLoading || isValidating || (validationResult && !validationResult.valid)}
            loading={isLoading}
          >
            {isLoading ? 'Importing...' : 'Import EPUB'}
          </Button>
        </div>
      </form>
    </ImportLayout>
  );
}