import { useState, useEffect } from 'react';
import { useFileService } from '../hooks/useFileService';
import type { FileServiceConfig, FileMetadata, ExportOptions, FilePreview } from '../types';
import { generateFilePreview } from '../utils/filePreview';

interface FileExporterProps {
  fileId: string;
  config?: FileServiceConfig;
  onExportSuccess?: (blob: Blob, fileName: string) => void;
  onExportError?: (error: string) => void;
  className?: string;
  allowSelectiveExport?: boolean;
}

export function FileExporter({
  fileId,
  config,
  onExportSuccess,
  onExportError,
  className = '',
  allowSelectiveExport = true,
}: FileExporterProps) {
  const { getFileMetadata, getFile, loading, error } = useFileService(config);
  const [fileMetadata, setFileMetadata] = useState<FileMetadata | null>(null);
  const [preview, setPreview] = useState<FilePreview | null>(null);
  const [exportOptions, setExportOptions] = useState<ExportOptions>({
    format: 'original',
  });

  useEffect(() => {
    const loadFile = async () => {
      if (!fileId) return;
      
      const metadata = await getFileMetadata(fileId);
      if (metadata) {
        setFileMetadata(metadata);
        
        // Generate preview for selective export
        try {
          const fileBlob = await getFile(fileId);
          if (fileBlob) {
            const file = new File([fileBlob], metadata.fileName, {
              type: `application/${metadata.fileExtension.slice(1)}`,
            });
            const previewData = await generateFilePreview(file);
            setPreview(previewData);
          }
        } catch (err) {
          console.warn('Could not generate preview:', err);
        }
      }
    };

    loadFile();
  }, [fileId, getFileMetadata, getFile]);

  const handleExport = async () => {
    if (!fileMetadata) {
      onExportError?.('File metadata not available');
      return;
    }

    try {
      const fileBlob = await getFile(fileId);
      if (!fileBlob) {
        onExportError?.('Failed to download file');
        return;
      }

      // Convert blob based on export options
      let exportBlob: Blob = fileBlob;
      let exportFileName = fileMetadata.fileName;

      if (exportOptions.format !== 'original') {
        // In a real implementation, you would use libraries like:
        // - PDF.js for PDF conversion
        // - xlsx for Excel conversion
        // - mammoth.js for Word conversion
        // For now, we'll just return the original file
        console.warn('Format conversion not yet implemented, exporting original file');
      }

      // Apply selective export if needed
      if (allowSelectiveExport && exportOptions.selectPages && exportOptions.selectPages.length > 0) {
        // In a real implementation, you would extract specific pages
        console.warn('Selective page export not yet implemented, exporting all pages');
      }

      if (allowSelectiveExport && exportOptions.selectSheets && exportOptions.selectSheets.length > 0) {
        // In a real implementation, you would extract specific sheets
        console.warn('Selective sheet export not yet implemented, exporting all sheets');
      }

      if (exportOptions.fileName) {
        exportFileName = exportOptions.fileName;
      }

      onExportSuccess?.(exportBlob, exportFileName);
    } catch (err) {
      const errorMessage = err instanceof Error ? err.message : 'Export failed';
      onExportError?.(errorMessage);
    }
  };

  const downloadFile = (blob: Blob, fileName: string) => {
    const url = URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = url;
    link.download = fileName;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    URL.revokeObjectURL(url);
  };

  const handleExportAndDownload = async () => {
    await handleExport();
    if (fileMetadata) {
      const fileBlob = await getFile(fileId);
      if (fileBlob) {
        downloadFile(fileBlob, exportOptions.fileName || fileMetadata.fileName);
      }
    }
  };

  if (loading && !fileMetadata) {
    return <div className={`file-exporter loading ${className}`}>Loading file...</div>;
  }

  if (error) {
    return <div className={`file-exporter error ${className}`}>Error: {error}</div>;
  }

  if (!fileMetadata) {
    return <div className={`file-exporter empty ${className}`}>No file to export</div>;
  }

  const fileExtension = fileMetadata.fileExtension.toLowerCase();
  const isPdf = fileExtension === '.pdf';
  const isExcel = fileExtension === '.xlsx' || fileExtension === '.xls';
  const isWord = fileExtension === '.docx' || fileExtension === '.doc';

  return (
    <div className={`file-exporter ${className}`}>
      <div className="export-header">
        <h4>Export: {fileMetadata.fileName}</h4>
      </div>

      <div className="export-options">
        <div className="format-selection">
          <label>
            <strong>Export Format:</strong>
            <select
              value={exportOptions.format}
              onChange={(e) =>
                setExportOptions({
                  ...exportOptions,
                  format: e.target.value as ExportOptions['format'],
                })
              }
            >
              <option value="original">Original Format</option>
              {isPdf && <option value="pdf">PDF</option>}
              {isExcel && (
                <>
                  <option value="excel">Excel (.xlsx)</option>
                  <option value="csv">CSV</option>
                </>
              )}
              {isWord && <option value="pdf">PDF</option>}
              <option value="json">JSON</option>
              <option value="txt">Text (.txt)</option>
            </select>
          </label>
        </div>

        {allowSelectiveExport && (
          <>
            {(isPdf || isWord) && preview?.pages && preview.pages > 1 && (
              <div className="page-selection">
                <label>
                  <input
                    type="checkbox"
                    checked={exportOptions.selectPages !== undefined}
                    onChange={(e) => {
                      if (e.target.checked) {
                        setExportOptions({
                          ...exportOptions,
                          selectPages: [1],
                        });
                      } else {
                        const { selectPages, ...rest } = exportOptions;
                        setExportOptions(rest);
                      }
                    }}
                  />
                  Select specific pages
                </label>
                {exportOptions.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={exportOptions.selectPages?.includes(pageNum)}
                          onChange={(e) => {
                            const currentPages = exportOptions.selectPages || [];
                            if (e.target.checked) {
                              setExportOptions({
                                ...exportOptions,
                                selectPages: [...currentPages, pageNum].sort((a, b) => a - b),
                              });
                            } else {
                              setExportOptions({
                                ...exportOptions,
                                selectPages: currentPages.filter((p) => p !== pageNum),
                              });
                            }
                          }}
                        />
                        Page {pageNum}
                      </label>
                    ))}
                  </div>
                )}
              </div>
            )}

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

        <div className="file-name-customization">
          <label>
            <strong>Custom File Name (optional):</strong>
            <input
              type="text"
              value={exportOptions.fileName || ''}
              onChange={(e) =>
                setExportOptions({
                  ...exportOptions,
                  fileName: e.target.value || undefined,
                })
              }
              placeholder={fileMetadata.fileName}
            />
          </label>
        </div>
      </div>

      <div className="export-actions">
        <button
          onClick={handleExportAndDownload}
          disabled={loading}
          className="export-button"
        >
          {loading ? 'Exporting...' : 'Export & Download'}
        </button>
        <button
          onClick={handleExport}
          disabled={loading}
          className="export-button-secondary"
        >
          {loading ? 'Exporting...' : 'Export (Callback Only)'}
        </button>
      </div>

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

