import React, { useState, useRef } from 'react';
import { X, Upload, Download, FileSpreadsheet, AlertCircle, CheckCircle, Info } from 'lucide-react';
import { excelUploadApi, ExcelUploadResponse } from '../../services/api';

interface ExcelUploadDialogProps {
  isOpen: boolean;
  onClose: () => void;
  onSuccess: () => void;
}

const ExcelUploadDialog: React.FC<ExcelUploadDialogProps> = ({
  isOpen,
  onClose,
  onSuccess,
}) => {
  const [file, setFile] = useState<File | null>(null);
  const [isUploading, setIsUploading] = useState(false);
  const [uploadResult, setUploadResult] = useState<ExcelUploadResponse | null>(null);
  const [error, setError] = useState<string | null>(null);
  const fileInputRef = useRef<HTMLInputElement>(null);

  const handleFileSelect = (event: React.ChangeEvent<HTMLInputElement>) => {
    const selectedFile = event.target.files?.[0];
    if (selectedFile) {
      // Validate file type
      const allowedTypes = [
        'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', // .xlsx
        'application/vnd.ms-excel', // .xls
      ];
      
      if (!allowedTypes.includes(selectedFile.type)) {
        setError('Please select a valid Excel file (.xlsx or .xls)');
        return;
      }

      // Validate file size (10MB limit)
      const maxSize = 10 * 1024 * 1024; // 10MB
      if (selectedFile.size > maxSize) {
        setError('File size must be less than 10MB');
        return;
      }

      setFile(selectedFile);
      setError(null);
      setUploadResult(null);
    }
  };

  const handleUpload = async () => {
    if (!file) {
      setError('Please select a file to upload');
      return;
    }

    setIsUploading(true);
    setError(null);
    setUploadResult(null);

    try {
      const response = await excelUploadApi.uploadExcel(file);
      
      // Check if the response contains data (even if it has errors)
      if (response.data) {
        setUploadResult(response.data);
        
        // If ANY users were inserted (even with some errors), call onSuccess to reload the directory
        if (response.data.insertedUsers > 0) {
          // Call onSuccess immediately to refresh the contact list
          onSuccess();
          
          // Auto-close dialog after 3 seconds if there are no errors
          if (response.data.errors.length === 0) {
            setTimeout(() => {
              handleClose();
            }, 3000);
          }
        }
      } else if (response.status === 'error') {
        // API returned an error without detailed data
        setError(response.message || 'Upload failed');
      } else {
        setError('Upload failed - unexpected response format');
      }
    } catch (err) {
      console.error('Upload error:', err);
      setError(err instanceof Error ? err.message : 'Upload failed');
    } finally {
      setIsUploading(false);
    }
  };

  const handleDownloadTemplate = async () => {
    try {
      await excelUploadApi.downloadTemplate();
    } catch (err) {
      console.error('Template download error:', err);
      setError(err instanceof Error ? err.message : 'Failed to download template');
    }
  };

  const handleClose = () => {
    setFile(null);
    setUploadResult(null);
    setError(null);
    setIsUploading(false);
    if (fileInputRef.current) {
      fileInputRef.current.value = '';
    }
    onClose();
  };

  const formatFileSize = (bytes: number) => {
    if (bytes === 0) return '0 Bytes';
    const k = 1024;
    const sizes = ['Bytes', 'KB', 'MB', 'GB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
  };

  if (!isOpen) return null;

  return (
    <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
      <div className="bg-white rounded-xl shadow-xl max-w-2xl w-full mx-4 max-h-[90vh] overflow-y-auto">
        {/* Header */}
        <div className="flex items-center justify-between p-6 border-b border-gray-200">
          <div className="flex items-center space-x-3">
            <div className="p-2 bg-blue-100 rounded-lg">
              <FileSpreadsheet className="h-6 w-6 text-blue-600" />
            </div>
            <div>
              <h2 className="text-xl font-semibold text-gray-900">Upload Excel File</h2>
              <p className="text-sm text-gray-500">Upload contact data in bulk using Excel format</p>
            </div>
          </div>
          <button
            onClick={handleClose}
            className="p-2 hover:bg-gray-100 rounded-lg transition-colors"
          >
            <X className="h-5 w-5 text-gray-500" />
          </button>
        </div>

        {/* Content */}
        <div className="p-6 space-y-6">
          {/* File Selection */}
          {!uploadResult && (
            <div className="space-y-4">
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-2">
                  Select Excel File
                </label>
                <div className="border-2 border-dashed border-gray-300 rounded-lg p-6 text-center hover:border-gray-400 transition-colors">
                  <input
                    ref={fileInputRef}
                    type="file"
                    accept=".xlsx,.xls"
                    onChange={handleFileSelect}
                    className="hidden"
                  />
                  <div className="space-y-3">
                    <Upload className="h-12 w-12 text-gray-400 mx-auto" />
                    <div>
                      <button
                        onClick={() => fileInputRef.current?.click()}
                        className="text-blue-600 hover:text-blue-700 font-medium"
                      >
                        Click to select file
                      </button>
                      <p className="text-sm text-gray-500 mt-1">
                        or drag and drop your Excel file here
                      </p>
                    </div>
                    <p className="text-xs text-gray-400">
                      Supports .xlsx and .xls files up to 10MB
                    </p>
                  </div>
                </div>
              </div>

              {/* Selected File Info */}
              {file && (
                <div className="bg-gray-50 rounded-lg p-4">
                  <div className="flex items-center space-x-3">
                    <FileSpreadsheet className="h-8 w-8 text-green-600" />
                    <div className="flex-1">
                      <p className="font-medium text-gray-900">{file.name}</p>
                      <p className="text-sm text-gray-500">{formatFileSize(file.size)}</p>
                    </div>
                    <button
                      onClick={() => {
                        setFile(null);
                        if (fileInputRef.current) {
                          fileInputRef.current.value = '';
                        }
                      }}
                      className="text-red-600 hover:text-red-700"
                    >
                      <X className="h-4 w-4" />
                    </button>
                  </div>
                </div>
              )}

              {/* Error Message */}
              {error && (
                <div className="bg-gradient-to-r from-red-50 to-red-100 border-2 border-red-400 rounded-lg p-4 shadow-sm">
                  <div className="flex items-center space-x-3">
                    <div className="p-2 bg-red-500 rounded-full flex-shrink-0">
                      <AlertCircle className="h-5 w-5 text-white" />
                    </div>
                    <div className="flex-1">
                      <p className="font-semibold text-red-800 mb-1">Upload Error</p>
                      <p className="text-sm text-red-700">{error}</p>
                    </div>
                  </div>
                </div>
              )}

              {/* Template Download */}
              <div className="bg-blue-50 border border-blue-200 rounded-lg p-4">
                <div className="flex items-start space-x-3">
                  <Info className="h-5 w-5 text-blue-600 mt-0.5" />
                  <div className="flex-1">
                    <p className="text-sm text-blue-800 font-medium mb-2">
                      Need a template?
                    </p>
                    <p className="text-sm text-blue-700 mb-3">
                      Download our Excel template with sample data and proper column headers.
                    </p>
                    <button
                      onClick={handleDownloadTemplate}
                      className="inline-flex items-center space-x-2 text-blue-600 hover:text-blue-700 font-medium"
                    >
                      <Download className="h-4 w-4" />
                      <span>Download Template</span>
                    </button>
                  </div>
                </div>
              </div>
            </div>
          )}

          {/* Upload Results */}
          {uploadResult && (
            <div className="space-y-4">
              {/* Success Summary - Only show if there are inserted users */}
              {uploadResult.insertedUsers > 0 && uploadResult.errors.length === 0 && (
                <div className="bg-gradient-to-r from-green-50 to-emerald-50 border-2 border-green-300 rounded-lg p-5 shadow-sm">
                  <div className="flex items-center space-x-3 mb-4">
                    <div className="p-2 bg-green-500 rounded-full">
                      <CheckCircle className="h-6 w-6 text-white" />
                    </div>
                    <h3 className="text-lg font-semibold text-green-800">✓ Upload Successful!</h3>
                  </div>
                  <div className="grid grid-cols-2 gap-4">
                    <div className="bg-white rounded-lg p-3 border border-green-200">
                      <span className="text-sm text-gray-600 block mb-1">Total Rows</span>
                      <span className="text-2xl font-bold text-green-600">{uploadResult.totalRows}</span>
                    </div>
                    <div className="bg-white rounded-lg p-3 border border-green-200">
                      <span className="text-sm text-gray-600 block mb-1">Processed</span>
                      <span className="text-2xl font-bold text-green-600">{uploadResult.processedUsers}</span>
                    </div>
                    <div className="bg-white rounded-lg p-3 border border-green-200">
                      <span className="text-sm text-gray-600 block mb-1">Successfully Inserted</span>
                      <span className="text-2xl font-bold text-green-600">{uploadResult.insertedUsers}</span>
                    </div>
                    <div className="bg-white rounded-lg p-3 border border-green-200">
                      <span className="text-sm text-gray-600 block mb-1">Skipped</span>
                      <span className="text-2xl font-bold text-gray-500">{uploadResult.skippedUsers}</span>
                    </div>
                  </div>
                </div>
              )}

              {/* Partial Success or Errors */}
              {(() => {
                const totalErrors = uploadResult.errors.length + 
                  (uploadResult.details?.filter((d: any) => d.status === 'error').length || 0);
                const hasErrors = totalErrors > 0;
                
                return hasErrors && (
                  <div className="bg-gradient-to-r from-red-50 to-orange-50 border-2 border-red-300 rounded-lg p-5 shadow-sm">
                    <div className="flex items-center space-x-3 mb-4">
                      <div className="p-2 bg-red-500 rounded-full">
                        <AlertCircle className="h-6 w-6 text-white" />
                      </div>
                      <h3 className="text-lg font-semibold text-red-800">
                        {uploadResult.insertedUsers > 0 ? '⚠ Partial Upload - Some Errors Found' : '✗ Upload Failed'}
                      </h3>
                    </div>
                    <div className="grid grid-cols-2 gap-4 mb-4">
                      <div className="bg-white rounded-lg p-3 border border-red-200">
                        <span className="text-sm text-gray-600 block mb-1">Total Rows</span>
                        <span className="text-2xl font-bold text-gray-700">{uploadResult.totalRows}</span>
                      </div>
                      <div className="bg-white rounded-lg p-3 border border-red-200">
                        <span className="text-sm text-gray-600 block mb-1">Processed</span>
                        <span className="text-2xl font-bold text-gray-700">{uploadResult.processedUsers}</span>
                      </div>
                      <div className="bg-white rounded-lg p-3 border border-green-200">
                        <span className="text-sm text-gray-600 block mb-1">Successfully Inserted</span>
                        <span className="text-2xl font-bold text-green-600">{uploadResult.insertedUsers}</span>
                      </div>
                      <div className="bg-white rounded-lg p-3 border border-red-200">
                        <span className="text-sm text-gray-600 block mb-1">Failed</span>
                        <span className="text-2xl font-bold text-red-600">{totalErrors}</span>
                      </div>
                    </div>
                  </div>
                );
              })()}

              {/* Validation Errors (from Excel parsing) */}
              {uploadResult.errors.length > 0 && (
                <div className="bg-red-50 border-2 border-red-300 rounded-lg p-4">
                  <div className="flex items-center space-x-2 mb-3">
                    <AlertCircle className="h-5 w-5 text-red-600" />
                    <h4 className="font-semibold text-red-800">Validation Errors ({uploadResult.errors.length})</h4>
                  </div>
                  <div className="space-y-2 max-h-40 overflow-y-auto bg-white rounded p-3 border border-red-200">
                    {uploadResult.errors.map((error, index) => (
                      <div key={index} className="text-sm text-red-700 py-1 border-b border-red-100 last:border-0">
                        <span className="font-semibold">Row {error.row}:</span> {error.error}
                      </div>
                    ))}
                  </div>
                </div>
              )}

              {/* Insertion Errors (from database operations) */}
              {uploadResult.details && uploadResult.details.filter((d: any) => d.status === 'error').length > 0 && (
                <div className="bg-red-50 border-2 border-red-300 rounded-lg p-4">
                  <div className="flex items-center space-x-2 mb-3">
                    <AlertCircle className="h-5 w-5 text-red-600" />
                    <h4 className="font-semibold text-red-800">
                      Database Errors ({uploadResult.details.filter((d: any) => d.status === 'error').length})
                    </h4>
                  </div>
                  <div className="space-y-2 max-h-40 overflow-y-auto bg-white rounded p-3 border border-red-200">
                    {uploadResult.details
                      .filter((detail: any) => detail.status === 'error')
                      .map((detail: any, index: number) => (
                        <div key={index} className="text-sm text-red-700 py-2 border-b border-red-100 last:border-0">
                          <div className="font-semibold mb-1">Row {detail.row}:</div>
                          <div className="text-red-600 ml-2">{detail.message}</div>
                        </div>
                      ))}
                  </div>
                </div>
              )}

              {/* Warnings */}
              {uploadResult.warnings.length > 0 && (
                <div className="bg-yellow-50 border-2 border-yellow-300 rounded-lg p-4">
                  <div className="flex items-center space-x-2 mb-3">
                    <Info className="h-5 w-5 text-yellow-600" />
                    <h4 className="font-semibold text-yellow-800">Warnings ({uploadResult.warnings.length})</h4>
                  </div>
                  <div className="space-y-2 max-h-40 overflow-y-auto bg-white rounded p-3 border border-yellow-200">
                    {uploadResult.warnings.map((warning, index) => (
                      <div key={index} className="text-sm text-yellow-700 py-1 border-b border-yellow-100 last:border-0">
                        <span className="font-semibold">Row {warning.row}:</span> {warning.warning}
                      </div>
                    ))}
                  </div>
                </div>
              )}
            </div>
          )}

          {/* Action Buttons */}
          <div className="flex justify-end space-x-3 pt-4 border-t border-gray-200">
            <button
              onClick={handleClose}
              className="px-4 py-2 text-gray-700 bg-gray-100 hover:bg-gray-200 rounded-lg transition-colors"
            >
              {uploadResult ? 'Close' : 'Cancel'}
            </button>
            {!uploadResult && (
              <button
                onClick={handleUpload}
                disabled={!file || isUploading}
                className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 disabled:opacity-50 disabled:cursor-not-allowed transition-colors flex items-center space-x-2"
              >
                {isUploading ? (
                  <>
                    <div className="animate-spin rounded-full h-4 w-4 border-b-2 border-white"></div>
                    <span>Uploading...</span>
                  </>
                ) : (
                  <>
                    <Upload className="h-4 w-4" />
                    <span>Upload</span>
                  </>
                )}
              </button>
            )}
          </div>
        </div>
      </div>
    </div>
  );
};

export default ExcelUploadDialog;
