'use client'

import { useState, useCallback } from 'react'
import { useDropzone } from 'react-dropzone'
import { toast } from 'react-hot-toast'
import { Upload, FileSpreadsheet, CheckCircle, XCircle, AlertTriangle, Download, X } from 'lucide-react'
import { contactsAPI } from '@/lib/api/contacts'
import * as XLSX from 'xlsx'

interface ImportError {
  row: number
  field: string
  message: string
  data?: any
}

interface ImportResult {
  success: number
  failed: number
  duplicates: number
  errors: ImportError[]
}

interface ContactImportProps {
  onClose: () => void
  onSuccess: () => void
}

export default function ContactImport({ onClose, onSuccess }: ContactImportProps) {
  const [step, setStep] = useState(1)
  const [file, setFile] = useState<File | null>(null)
  const [preview, setPreview] = useState<any[]>([])
  const [importing, setImporting] = useState(false)
  const [result, setResult] = useState<ImportResult | null>(null)

  // Step 1: File Upload
  const onDrop = useCallback((acceptedFiles: File[]) => {
    const uploadedFile = acceptedFiles[0]
    if (!uploadedFile) return

    const fileExtension = uploadedFile.name.split('.').pop()?.toLowerCase()
    if (!['xlsx', 'xls', 'csv'].includes(fileExtension || '')) {
      toast.error('يرجى تحميل ملف Excel أو CSV - Please upload an Excel or CSV file')
      return
    }

    setFile(uploadedFile)
    
    // Read and preview file
    const reader = new FileReader()
    reader.onload = (e) => {
      try {
        const data = e.target?.result
        const workbook = XLSX.read(data, { type: 'binary' })
        const sheetName = workbook.SheetNames[0]
        const worksheet = workbook.Sheets[sheetName]
        const jsonData = XLSX.utils.sheet_to_json(worksheet)
        
        setPreview(jsonData.slice(0, 5)) // Preview first 5 rows
        setStep(2)
      } catch (error) {
        toast.error('خطأ في قراءة الملف - Error reading file')
      }
    }
    reader.readAsBinaryString(uploadedFile)
  }, [])

  const { getRootProps, getInputProps, isDragActive } = useDropzone({
    onDrop,
    accept: {
      'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet': ['.xlsx'],
      'application/vnd.ms-excel': ['.xls'],
      'text/csv': ['.csv']
    },
    maxFiles: 1
  })

  // Step 2: Preview and Confirm
  const handleImport = async () => {
    if (!file) return

    setImporting(true)
    setStep(3)

    try {
      const importResult = await contactsAPI.import(file)
      setResult(importResult)
      setStep(4)

      if (importResult.success > 0) {
        toast.success(`تم استيراد ${importResult.success} جهة اتصال بنجاح - Imported ${importResult.success} contacts successfully`)
        onSuccess()
      }
    } catch (error: any) {
      toast.error(error.response?.data?.message || 'فشل الاستيراد - Import failed')
      setStep(2)
    } finally {
      setImporting(false)
    }
  }

  // Download error report
  const downloadErrorReport = () => {
    if (!result || result.errors.length === 0) return

    const errorData = result.errors.map(err => ({
      'Row': err.row,
      'Field': err.field,
      'Error': err.message,
      'Data': JSON.stringify(err.data || {})
    }))

    const worksheet = XLSX.utils.json_to_sheet(errorData)
    const workbook = XLSX.utils.book_new()
    XLSX.utils.book_append_sheet(workbook, worksheet, 'Errors')
    XLSX.writeFile(workbook, `import-errors-${Date.now()}.xlsx`)
  }

  // Download template
  const downloadTemplate = () => {
    const template = [
      {
        type: 'INDIVIDUAL',
        name: 'John Doe',
        nameAr: 'جون دو',
        email: 'john@example.com',
        phone: '+966501234567',
        mobile: '+966501234567',
        website: 'https://example.com',
        companyName: 'Acme Corp',
        companyNameAr: 'شركة أكمي',
        taxNumber: '123456789',
        commercialRegister: 'CR123456',
        address: '123 Main St',
        city: 'Riyadh',
        country: 'Saudi Arabia',
        postalCode: '12345',
        source: 'WEBSITE',
        tags: 'vip,partner'
      }
    ]

    const worksheet = XLSX.utils.json_to_sheet(template)
    const workbook = XLSX.utils.book_new()
    XLSX.utils.book_append_sheet(workbook, worksheet, 'Template')
    XLSX.writeFile(workbook, 'contacts-import-template.xlsx')
  }

  return (
    <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 p-4">
      <div className="bg-white rounded-lg shadow-xl w-full max-w-4xl max-h-[90vh] overflow-hidden flex flex-col">
        {/* Header */}
        <div className="flex items-center justify-between p-6 border-b">
          <div>
            <h2 className="text-2xl font-bold text-gray-900">
              استيراد جهات الاتصال - Import Contacts
            </h2>
            <p className="text-sm text-gray-600 mt-1">
              Step {step} of 4
            </p>
          </div>
          <button onClick={onClose} className="text-gray-400 hover:text-gray-600">
            <X size={24} />
          </button>
        </div>

        {/* Content */}
        <div className="flex-1 overflow-y-auto p-6">
          {/* Step 1: Upload File */}
          {step === 1 && (
            <div className="space-y-6">
              <div className="text-center mb-6">
                <button
                  onClick={downloadTemplate}
                  className="inline-flex items-center gap-2 text-blue-600 hover:text-blue-700 font-medium"
                >
                  <Download size={18} />
                  تحميل قالب Excel - Download Excel Template
                </button>
              </div>

              <div
                {...getRootProps()}
                className={`border-2 border-dashed rounded-lg p-12 text-center cursor-pointer transition-colors ${
                  isDragActive
                    ? 'border-blue-500 bg-blue-50'
                    : 'border-gray-300 hover:border-gray-400'
                }`}
              >
                <input {...getInputProps()} />
                <Upload className="mx-auto h-12 w-12 text-gray-400 mb-4" />
                {isDragActive ? (
                  <p className="text-lg text-blue-600">
                    أفلت الملف هنا - Drop the file here
                  </p>
                ) : (
                  <>
                    <p className="text-lg text-gray-700 mb-2">
                      اسحب وأفلت ملف Excel أو CSV هنا - Drag & drop an Excel or CSV file here
                    </p>
                    <p className="text-sm text-gray-500">
                      أو انقر لتحديد ملف - or click to select a file
                    </p>
                  </>
                )}
              </div>

              <div className="bg-blue-50 border border-blue-200 rounded-lg p-4">
                <h3 className="font-semibold text-blue-900 mb-2">
                  متطلبات الملف - File Requirements:
                </h3>
                <ul className="text-sm text-blue-800 space-y-1 list-disc list-inside">
                  <li>يجب أن يحتوي الملف على الأعمدة التالية: type, name, source</li>
                  <li>الأنواع المسموح بها: INDIVIDUAL, COMPANY, HOLDING, GOVERNMENT</li>
                  <li>سيتم تخطي جهات الاتصال المكررة (البريد الإلكتروني، الهاتف، الرقم الضريبي)</li>
                  <li>الحد الأقصى: 10,000 صف</li>
                </ul>
              </div>
            </div>
          )}

          {/* Step 2: Preview */}
          {step === 2 && (
            <div className="space-y-6">
              <div className="flex items-center gap-3 mb-4">
                <FileSpreadsheet className="text-green-600" size={24} />
                <div>
                  <p className="font-semibold text-gray-900">{file?.name}</p>
                  <p className="text-sm text-gray-600">
                    {preview.length} صفوف للمعاينة - rows to preview
                  </p>
                </div>
              </div>

              <div className="border rounded-lg overflow-x-auto">
                <table className="min-w-full divide-y divide-gray-200">
                  <thead className="bg-gray-50">
                    <tr>
                      <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">
                        Type
                      </th>
                      <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">
                        Name
                      </th>
                      <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">
                        Email
                      </th>
                      <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">
                        Phone
                      </th>
                      <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">
                        Source
                      </th>
                    </tr>
                  </thead>
                  <tbody className="bg-white divide-y divide-gray-200">
                    {preview.map((row, idx) => (
                      <tr key={idx} className="hover:bg-gray-50">
                        <td className="px-4 py-3 text-sm text-gray-900">{row.type}</td>
                        <td className="px-4 py-3 text-sm text-gray-900">{row.name}</td>
                        <td className="px-4 py-3 text-sm text-gray-600">{row.email || '-'}</td>
                        <td className="px-4 py-3 text-sm text-gray-600">{row.phone || '-'}</td>
                        <td className="px-4 py-3 text-sm text-gray-600">{row.source}</td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>

              <div className="bg-yellow-50 border border-yellow-200 rounded-lg p-4">
                <div className="flex gap-2">
                  <AlertTriangle className="text-yellow-600 flex-shrink-0" size={20} />
                  <div className="text-sm text-yellow-800">
                    <p className="font-semibold mb-1">تنبيه - Warning:</p>
                    <p>
                      سيتم فحص جميع جهات الاتصال بحثاً عن التكرارات. سيتم تخطي جهات الاتصال المكررة وتسجيلها في تقرير الأخطاء.
                    </p>
                  </div>
                </div>
              </div>
            </div>
          )}

          {/* Step 3: Importing */}
          {step === 3 && (
            <div className="text-center py-12">
              <div className="animate-spin rounded-full h-16 w-16 border-b-2 border-blue-600 mx-auto mb-4"></div>
              <p className="text-lg font-semibold text-gray-900 mb-2">
                جاري الاستيراد - Importing...
              </p>
              <p className="text-sm text-gray-600">
                يرجى الانتظار، قد تستغرق هذه العملية بضع دقائق - Please wait, this may take a few minutes
              </p>
            </div>
          )}

          {/* Step 4: Results */}
          {step === 4 && result && (
            <div className="space-y-6">
              <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
                <div className="bg-green-50 border border-green-200 rounded-lg p-4">
                  <div className="flex items-center gap-3">
                    <CheckCircle className="text-green-600" size={24} />
                    <div>
                      <p className="text-2xl font-bold text-green-900">{result.success}</p>
                      <p className="text-sm text-green-700">نجح - Successful</p>
                    </div>
                  </div>
                </div>

                <div className="bg-yellow-50 border border-yellow-200 rounded-lg p-4">
                  <div className="flex items-center gap-3">
                    <AlertTriangle className="text-yellow-600" size={24} />
                    <div>
                      <p className="text-2xl font-bold text-yellow-900">{result.duplicates}</p>
                      <p className="text-sm text-yellow-700">مكرر - Duplicates</p>
                    </div>
                  </div>
                </div>

                <div className="bg-red-50 border border-red-200 rounded-lg p-4">
                  <div className="flex items-center gap-3">
                    <XCircle className="text-red-600" size={24} />
                    <div>
                      <p className="text-2xl font-bold text-red-900">{result.failed}</p>
                      <p className="text-sm text-red-700">فشل - Failed</p>
                    </div>
                  </div>
                </div>
              </div>

              {result.errors.length > 0 && (
                <div className="border rounded-lg overflow-hidden">
                  <div className="bg-gray-50 px-4 py-3 border-b flex items-center justify-between">
                    <h3 className="font-semibold text-gray-900">
                      الأخطاء ({result.errors.length}) - Errors ({result.errors.length})
                    </h3>
                    <button
                      onClick={downloadErrorReport}
                      className="inline-flex items-center gap-2 text-sm text-blue-600 hover:text-blue-700 font-medium"
                    >
                      <Download size={16} />
                      تحميل تقرير الأخطاء - Download Error Report
                    </button>
                  </div>
                  <div className="max-h-64 overflow-y-auto">
                    <table className="min-w-full divide-y divide-gray-200">
                      <thead className="bg-gray-50 sticky top-0">
                        <tr>
                          <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">
                            Row
                          </th>
                          <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">
                            Field
                          </th>
                          <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">
                            Error
                          </th>
                        </tr>
                      </thead>
                      <tbody className="bg-white divide-y divide-gray-200">
                        {result.errors.slice(0, 50).map((error, idx) => (
                          <tr key={idx} className="hover:bg-gray-50">
                            <td className="px-4 py-3 text-sm text-gray-900">{error.row}</td>
                            <td className="px-4 py-3 text-sm text-gray-600">{error.field}</td>
                            <td className="px-4 py-3 text-sm text-red-600">{error.message}</td>
                          </tr>
                        ))}
                      </tbody>
                    </table>
                  </div>
                </div>
              )}
            </div>
          )}
        </div>

        {/* Footer */}
        <div className="border-t p-6 flex justify-between">
          {step === 1 && (
            <button
              onClick={onClose}
              className="px-4 py-2 text-gray-700 hover:text-gray-900"
            >
              إلغاء - Cancel
            </button>
          )}

          {step === 2 && (
            <>
              <button
                onClick={() => {
                  setStep(1)
                  setFile(null)
                  setPreview([])
                }}
                className="px-4 py-2 text-gray-700 hover:text-gray-900"
              >
                رجوع - Back
              </button>
              <button
                onClick={handleImport}
                disabled={importing}
                className="px-6 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 disabled:bg-gray-400 disabled:cursor-not-allowed"
              >
                ابدأ الاستيراد - Start Import
              </button>
            </>
          )}

          {step === 4 && (
            <button
              onClick={onClose}
              className="ml-auto px-6 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700"
            >
              إغلاق - Close
            </button>
          )}
        </div>
      </div>
    </div>
  )
}
