import { useRef, useState, useEffect } from 'react';
import { useFileService } from '../hooks/useFileService';
import { validateFile, formatFileSize } from '../utils/fileValidation';
import { generateFilePreview } from '../utils/filePreview';
import type { FileServiceConfig, FilePreview, ImportOptions, ValidationResult } from '../types';

interface FileImporterProps {
  config?: FileServiceConfig;
  onImportSuccess?: (fileId: string, options?: ImportOptions) => void;
  onImportError?: (error: string) => void;
  className?: string;
  accept?: string;
  showPreview?: boolean;
  allowSelectiveImport?: boolean;
}

export function FileImporter({
  config,
  onImportSuccess,
  onImportError,
  className = '',
  accept,
  showPreview = true,
  allowSelectiveImport = true,
}: FileImporterProps) {
  const fileInputRef = useRef<HTMLInputElement>(null);
  const [selectedFile, setSelectedFile] = useState<File | null>(null);
  const [preview, setPreview] = useState<FilePreview | null>(null);
  const [validation, setValidation] = useState<ValidationResult | null>(null);
  const [importOptions, setImportOptions] = useState<ImportOptions>({});
  const [dragActive, setDragActive] = useState(false);
  const [previewLoading, setPreviewLoading] = useState(false);
  const [filePreviewUrl, setFilePreviewUrl] = useState<string | null>(null);
  const { uploadFile, loading, error } = useFileService(config);

  useEffect(() => {
    if (selectedFile) {
      // Create object URL for file preview
      const url = URL.createObjectURL(selectedFile);
      setFilePreviewUrl(url);

      return () => {
        URL.revokeObjectURL(url);
      };
    } else {
      setFilePreviewUrl(null);
    }
  }, [selectedFile]);

  useEffect(() => {
    if (selectedFile && showPreview) {
      setPreviewLoading(true);
      generateFilePreview(selectedFile)
        .then((previewData) => {
          setPreview(previewData);
          setPreviewLoading(false);
        })
        .catch((err) => {
          console.error('Preview generation failed:', err);
          setPreviewLoading(false);
        });
    }
  }, [selectedFile, showPreview]);

  useEffect(() => {
    if (selectedFile) {
      // Create object URL for file preview
      const url = URL.createObjectURL(selectedFile);
      setFilePreviewUrl(url);

      return () => {
        URL.revokeObjectURL(url);
      };
    } else {
      setFilePreviewUrl(null);
    }
  }, [selectedFile]);

  const handleFileSelect = (file: File) => {
    const validationResult = validateFile(file, config);
    setValidation(validationResult);
    setSelectedFile(file);
    
    if (!validationResult.valid) {
      onImportError?.(validationResult.errors.join(', '));
      return;
    }
  };

  const handleImport = async () => {
    if (!selectedFile || !validation?.valid) {
      onImportError?.('Please select a valid file');
      return;
    }

    try {
      const result = await uploadFile(selectedFile);
      
      if (result.success && result.file) {
        onImportSuccess?.(result.file.id, importOptions);
        // Reset state
        setSelectedFile(null);
        setPreview(null);
        setImportOptions({});
        if (fileInputRef.current) {
          fileInputRef.current.value = '';
        }
      } else {
        onImportError?.(result.error || 'Import failed');
      }
    } catch (err) {
      const errorMessage = err instanceof Error ? err.message : 'Import failed';
      onImportError?.(errorMessage);
    }
  };

  const handleDrop = (e: React.DragEvent<HTMLDivElement>) => {
    e.preventDefault();
    e.stopPropagation();
    setDragActive(false);

    if (e.dataTransfer.files && e.dataTransfer.files.length > 0) {
      handleFileSelect(e.dataTransfer.files[0]);
    }
  };

  const handleDrag = (e: React.DragEvent<HTMLDivElement>) => {
    e.preventDefault();
    e.stopPropagation();
    if (e.type === 'dragenter' || e.type === 'dragover') {
      setDragActive(true);
    } else if (e.type === 'dragleave') {
      setDragActive(false);
    }
  };

  const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    if (e.target.files && e.target.files.length > 0) {
      handleFileSelect(e.target.files[0]);
    }
  };

  const renderPreview = () => {
    if (!preview || !selectedFile) return null;

    return (
      <div className="file-preview">
        <h4>File Preview: {selectedFile.name}</h4>
        <div className="preview-info">
          <div className="preview-metadata">
            <p><strong>Name:</strong> {selectedFile.name}</p>
            <p><strong>Size:</strong> {formatFileSize(selectedFile.size)}</p>
            <p><strong>Type:</strong> {preview.type}</p>
            
            {preview.pages && (
              <p><strong>Total Pages:</strong> {preview.pages}</p>
            )}
            
            {preview.sheets && preview.sheets.length > 0 && (
              <div>
                <p><strong>Sheets:</strong></p>
                <ul>
                  {preview.sheets.map((sheet) => (
                    <li key={sheet}>{sheet}</li>
                  ))}
                </ul>
              </div>
            )}
          </div>
          
          <div className="preview-content">
            {preview.type === 'pdf' && filePreviewUrl && (
              <div className="pdf-preview">
                <iframe
                  src={filePreviewUrl || undefined}
                  title="PDF Preview"
                  style={{
                    width: '100%',
                    height: '600px',
                    border: '1px solid #ddd',
                    borderRadius: '4px',
                  }}
                />
              </div>
            )}
            
            {preview.type === 'image' && preview.thumbnail && (
              <div className="image-preview">
                <img
                  src={preview.thumbnail}
                  alt="File Preview"
                  style={{
                    maxWidth: '100%',
                    maxHeight: '400px',
                    border: '1px solid #ddd',
                    borderRadius: '4px',
                  }}
                />
              </div>
            )}
            
            {preview.type === 'text' && filePreviewUrl && (
              <div className="text-preview">
                <iframe
                  src={filePreviewUrl || undefined}
                  title="Text Preview"
                  style={{
                    width: '100%',
                    height: '400px',
                    border: '1px solid #ddd',
                    borderRadius: '4px',
                  }}
                />
              </div>
            )}
            
            {(preview.type === 'excel' || preview.type === 'csv') && (
              <div className="spreadsheet-preview">
                <p style={{ padding: '20px', backgroundColor: '#f5f5f5', borderRadius: '4px' }}>
                  <strong>Spreadsheet Preview</strong>
                </p>
                {preview.sheets && preview.sheets.length > 0 && (
                  <div style={{ padding: '10px' }}>
                    <p>Available sheets: {preview.sheets.join(', ')}</p>
                  </div>
                )}
                {preview.metadata && (
                  <div style={{ padding: '10px' }}>
                    {preview.metadata.rows && (
                      <p>Rows: {preview.metadata.rows}</p>
                    )}
                    {preview.metadata.columns && (
                      <p>Columns: {preview.metadata.columns}</p>
                    )}
                    {preview.metadata.headers && (
                      <p>Headers: {preview.metadata.headers.join(', ')}</p>
                    )}
                  </div>
                )}
              </div>
            )}
            
            {preview.type === 'word' && filePreviewUrl && (
              <div className="word-preview">
                <iframe
                  src={`https://view.officeapps.live.com/op/embed.aspx?src=${encodeURIComponent(filePreviewUrl)}`}
                  title="Word Preview"
                  style={{
                    width: '100%',
                    height: '600px',
                    border: '1px solid #ddd',
                    borderRadius: '4px',
                  }}
                />
              </div>
            )}
            
            {preview.type === 'other' && (
              <div className="generic-preview">
                <p style={{ padding: '20px', backgroundColor: '#f5f5f5', borderRadius: '4px' }}>
                  File preview not available for this file type. Download to view.
                </p>
              </div>
            )}
          </div>
        </div>
      </div>
    );
  };

  const renderSelectiveImport = () => {
    if (!allowSelectiveImport || !preview || !selectedFile) return null;

    return (
      <div className="selective-import">
        <h4>Import Options</h4>
        
        {(preview.type === 'pdf' || preview.type === 'word') && preview.pages && preview.pages > 1 && (
          <div className="page-selection">
            <label>
              <input
                type="checkbox"
                checked={importOptions.selectPages !== undefined}
                onChange={(e) => {
                  if (e.target.checked) {
                    setImportOptions({ ...importOptions, selectPages: [1] });
                  } else {
                    const { selectPages, ...rest } = importOptions;
                    setImportOptions(rest);
                  }
                }}
              />
              Select specific pages
            </label>
            {importOptions.selectPages !== undefined && (
              <div className="pages-list">
                {Array.from({ length: preview.pages }, (_, i) => i + 1).map((pageNum) => (
                  <label key={pageNum} className="page-checkbox">
                    <input
                      type="checkbox"
                      checked={importOptions.selectPages?.includes(pageNum)}
                      onChange={(e) => {
                        const currentPages = importOptions.selectPages || [];
                        if (e.target.checked) {
                          setImportOptions({
                            ...importOptions,
                            selectPages: [...currentPages, pageNum].sort((a, b) => a - b),
                          });
                        } else {
                          setImportOptions({
                            ...importOptions,
                            selectPages: currentPages.filter((p) => p !== pageNum),
                          });
                        }
                      }}
                    />
                    Page {pageNum}
                  </label>
                ))}
              </div>
            )}
          </div>
        )}

        {preview.type === 'excel' && preview.sheets && preview.sheets.length > 1 && (
          <div className="sheet-selection">
            <label>
              <input
                type="checkbox"
                checked={importOptions.selectSheets !== undefined}
                onChange={(e) => {
                  if (e.target.checked) {
                    setImportOptions({ ...importOptions, selectSheets: [preview.sheets![0]] });
                  } else {
                    const { selectSheets, ...rest } = importOptions;
                    setImportOptions(rest);
                  }
                }}
              />
              Select specific sheets
            </label>
            {importOptions.selectSheets !== undefined && (
              <div className="sheets-list">
                {preview.sheets.map((sheet) => (
                  <label key={sheet} className="sheet-checkbox">
                    <input
                      type="checkbox"
                      checked={importOptions.selectSheets?.includes(sheet)}
                      onChange={(e) => {
                        const currentSheets = importOptions.selectSheets || [];
                        if (e.target.checked) {
                          setImportOptions({
                            ...importOptions,
                            selectSheets: [...currentSheets, sheet],
                          });
                        } else {
                          setImportOptions({
                            ...importOptions,
                            selectSheets: currentSheets.filter((s) => s !== sheet),
                          });
                        }
                      }}
                    />
                    {sheet}
                  </label>
                ))}
              </div>
            )}
          </div>
        )}
      </div>
    );
  };

  return (
    <div className={`file-importer ${className}`}>
      <div
        className={`import-area ${dragActive ? 'drag-active' : ''} ${loading ? 'loading' : ''}`}
        onDragEnter={handleDrag}
        onDragLeave={handleDrag}
        onDragOver={handleDrag}
        onDrop={handleDrop}
        onClick={() => fileInputRef.current?.click()}
      >
        <input
          ref={fileInputRef}
          type="file"
          onChange={handleChange}
          accept={accept}
          style={{ display: 'none' }}
        />
        <div className="import-content">
          {loading ? (
            <p>Importing...</p>
          ) : selectedFile ? (
            <div>
              <p>Selected: {selectedFile.name}</p>
              <button
                onClick={(e) => {
                  e.stopPropagation();
                  handleImport();
                }}
                disabled={!validation?.valid || loading}
                className="import-button"
              >
                Import File
              </button>
            </div>
          ) : (
            <>
              <p>Click to select file or drag and drop</p>
              <p className="import-hint">Select a file to import</p>
            </>
          )}
        </div>
      </div>

      {validation && (
        <div className={`validation ${validation.valid ? 'valid' : 'invalid'}`}>
          {validation.errors.length > 0 && (
            <div className="errors">
              {validation.errors.map((error, idx) => (
                <p key={idx} className="error">❌ {error}</p>
              ))}
            </div>
          )}
          {validation.warnings.length > 0 && (
            <div className="warnings">
              {validation.warnings.map((warning, idx) => (
                <p key={idx} className="warning">⚠️ {warning}</p>
              ))}
            </div>
          )}
        </div>
      )}

      {previewLoading && <div className="preview-loading">Generating preview...</div>}

      {showPreview && renderPreview()}

      {renderSelectiveImport()}

      {error && <div className="error-message">{error}</div>}
    </div>
  );
}

