"use client"

import { useState, useRef, useEffect } from "react"
import { Button } from "@/components/ui/button"
import { Card } from "@/components/ui/card"
import { Upload, X, File, FileText, Image as ImageIcon, Loader2 } from "lucide-react"
import { toast } from "@/hooks/use-toast"

interface UploadedDocument {
  type: string
  name: string
  url: string
  size?: number
  uploadedAt?: Date
}

interface DocumentUploaderProps {
  documents: UploadedDocument[]
  onDocumentsChange: (documents: UploadedDocument[]) => void
  maxFiles?: number
  maxSizeInMB?: number
  acceptedTypes?: string[]
  allowedDocumentTypes?: string[]
  defaultDocumentType?: string // Default type for uploaded documents
  userId?: string // Optional userId for registration flow
}

export function DocumentUploader({
  documents,
  onDocumentsChange,
  maxFiles = 5,
  maxSizeInMB = 10,
  acceptedTypes = [
    'image/jpeg',
    'image/jpg',
    'image/png',
    'image/webp',
    'application/pdf',
    'application/msword',
    'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
  ],
  allowedDocumentTypes = ['business_license', 'ownership_proof', 'insurance', 'other'],
  defaultDocumentType = 'other',
  userId
}: DocumentUploaderProps) {
  const [uploading, setUploading] = useState(false)
  const [uploadingCount, setUploadingCount] = useState(0)
  const [dragActive, setDragActive] = useState(false)
  const fileInputRef = useRef<HTMLInputElement>(null)

  // Debug: Log documents changes
  useEffect(() => {
    console.log('[DocumentUploader] Documents prop changed:', documents.length, 'documents')
    documents.forEach((doc, index) => {
      console.log(`[DocumentUploader] Document ${index + 1}:`, doc.name, doc.url)
    })
  }, [documents])

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

  const validateFile = (file: File): string | null => {
    // Check file size
    const maxSizeBytes = maxSizeInMB * 1024 * 1024
    if (file.size > maxSizeBytes) {
      return `File size exceeds ${maxSizeInMB}MB limit`
    }

    // Check file type
    if (!acceptedTypes.includes(file.type)) {
      return `File type ${file.type} is not allowed`
    }

    // Check max files
    if (documents.length >= maxFiles) {
      return `Maximum ${maxFiles} files allowed`
    }

    return null
  }

  const uploadFile = async (file: File, documentType: string): Promise<UploadedDocument | null> => {
    try {
      // Actually upload file to server
      const formData = new FormData()
      formData.append('file', file)
      formData.append('type', documentType)
      
      // Include userId if provided (for registration flow)
      if (userId && userId.trim()) {
        formData.append('userId', userId.trim())
        console.log('[DocumentUploader] Including userId in upload:', userId)
      } else {
        console.warn('[DocumentUploader] No userId provided - userId value:', userId)
      }

      const token = typeof window !== 'undefined' ? localStorage.getItem('geezer_guide_token') : null
      console.log('[DocumentUploader] Token available:', !!token)
      
      const response = await fetch('/api/uploads', {
        method: 'POST',
        body: formData,
        headers: {
          ...(token ? { Authorization: `Bearer ${token}` } : {})
        }
      })

      if (!response.ok) {
        const errorData = await response.json().catch(() => ({ message: 'Upload failed' }))
        console.error('[DocumentUploader] Upload failed:', response.status, errorData)
        throw new Error(errorData.message || 'Upload failed')
      }

      const data = await response.json()
      
      if (!data.success || !data.data?.url) {
        throw new Error(data.message || 'Upload failed')
      }

      return {
        type: documentType,
        name: file.name,
        url: data.data.url,
        size: file.size,
        uploadedAt: new Date()
      }
    } catch (error) {
      console.error('Upload error:', error)
      return null
    }
  }

  const handleFiles = async (files: FileList | null, documentType: string = defaultDocumentType) => {
    if (!files || files.length === 0) return

    setUploading(true)

    const fileArray = Array.from(files)
    const validFiles: File[] = []

    // Validate all files first
    for (const file of fileArray) {
      const error = validateFile(file)
      if (error) {
        toast({
          title: "Upload Error",
          description: `${file.name}: ${error}`,
          variant: "destructive"
        })
        continue
      }
      validFiles.push(file)
    }

    if (validFiles.length === 0) {
      setUploading(false)
      return
    }

    setUploadingCount(validFiles.length)

    // Upload files sequentially for better progress tracking
    const uploadedDocs: UploadedDocument[] = []
    for (let i = 0; i < validFiles.length; i++) {
      const file = validFiles[i]
      const doc = await uploadFile(file, documentType)
      if (doc) {
        uploadedDocs.push(doc)
      }
      setUploadingCount(validFiles.length - i - 1)
    }

    // Update documents array after all uploads complete
    if (uploadedDocs.length > 0) {
      const updatedDocuments = [...documents, ...uploadedDocs]
      console.log('[DocumentUploader] Uploaded documents:', uploadedDocs)
      console.log('[DocumentUploader] Total documents after upload:', updatedDocuments.length)
      onDocumentsChange(updatedDocuments)
      toast({
        title: "Upload Successful",
        description: `${uploadedDocs.length} file(s) uploaded successfully`
      })
      // Reset file input to allow uploading the same file again if needed
      if (fileInputRef.current) {
        fileInputRef.current.value = ''
      }
    } else {
      toast({
        title: "Upload Failed",
        description: "Failed to upload files. Please try again.",
        variant: "destructive"
      })
    }

    setUploading(false)
    setUploadingCount(0)
    setDragActive(false)
  }

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

    if (e.dataTransfer.files && e.dataTransfer.files.length > 0) {
      handleFiles(e.dataTransfer.files)
    }
  }

  const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    e.preventDefault()
    if (e.target.files && e.target.files.length > 0) {
      handleFiles(e.target.files)
    }
  }

  const removeDocument = (index: number) => {
    const newDocuments = documents.filter((_, i) => i !== index)
    onDocumentsChange(newDocuments)
    toast({
      title: "Document Removed",
      description: "Document removed successfully"
    })
  }

  const getFileIcon = (fileName: string) => {
    const extension = fileName.split('.').pop()?.toLowerCase()
    if (['jpg', 'jpeg', 'png', 'webp', 'gif'].includes(extension || '')) {
      return ImageIcon
    } else if (['pdf'].includes(extension || '')) {
      return FileText
    } else {
      return File
    }
  }

  const formatFileSize = (bytes?: number) => {
    if (!bytes) return ''
    if (bytes < 1024) return bytes + ' B'
    if (bytes < 1024 * 1024) return (bytes / 1024).toFixed(1) + ' KB'
    return (bytes / (1024 * 1024)).toFixed(1) + ' MB'
  }

  return (
    <div className="space-y-4">
      {/* Upload Area */}
      <Card
        className={`border-2 border-dashed transition-all ${
          dragActive 
            ? 'border-blue-500 bg-blue-50' 
            : 'border-gray-300 bg-gray-50 hover:border-gray-400'
        }`}
        onDragEnter={handleDrag}
        onDragLeave={handleDrag}
        onDragOver={handleDrag}
        onDrop={handleDrop}
      >
        <div className="p-8 text-center">
          <input
            ref={fileInputRef}
            type="file"
            multiple
            accept={acceptedTypes.join(',')}
            onChange={handleChange}
            className="hidden"
          />
          
          <Upload className={`mx-auto h-12 w-12 ${dragActive ? 'text-blue-500' : 'text-gray-400'}`} />
          
          <h3 className="mt-4 text-lg font-semibold text-gray-900">
            Drop files here or click to upload
          </h3>
          
          <p className="mt-2 text-sm text-gray-600">
            Upload up to {maxFiles} files (max {maxSizeInMB}MB each)
          </p>
          
          <p className="mt-1 text-xs text-gray-500">
            Supported: PDF, DOC, DOCX, JPG, PNG, WEBP
          </p>
          
          <Button
            type="button"
            onClick={() => fileInputRef.current?.click()}
            disabled={uploading || documents.length >= maxFiles}
            className="mt-4 bg-[#3F5CEA] hover:bg-[#3F5CEA]/90"
          >
            {uploading ? (
              <>
                <Loader2 className="h-4 w-4 mr-2 animate-spin" />
                {uploadingCount > 0 ? `Uploading ${uploadingCount} file(s)...` : 'Uploading...'}
              </>
            ) : (
              <>
                <Upload className="h-4 w-4 mr-2" />
                Select Files
              </>
            )}
          </Button>
        </div>
      </Card>

      {/* Uploaded Documents List - Show below upload button */}
      {documents && documents.length > 0 && (
        <div className="space-y-3 mt-4">
          <div className="flex items-center justify-between">
            <h4 className="text-sm font-semibold text-gray-900 flex items-center gap-2">
              <FileText className="h-4 w-4 text-blue-600" />
              Uploaded Documents ({documents.length}/{maxFiles})
            </h4>
            {documents.length > 0 && (
              <span className="text-xs text-green-600 font-medium flex items-center gap-1">
                <span className="w-2 h-2 bg-green-500 rounded-full"></span>
                {documents.length} file{documents.length > 1 ? 's' : ''} uploaded
              </span>
            )}
          </div>
          
          <div className="space-y-2">
            {documents.map((doc, index) => {
              const FileIcon = getFileIcon(doc.name)
              // Use a more stable key combining url and index
              const docKey = doc.url || `${doc.name}-${index}`
              return (
                <Card key={docKey} className="p-4 bg-white border-2 border-green-200 hover:border-green-300 hover:bg-green-50 transition-all">
                  <div className="flex items-center justify-between gap-3">
                    <div className="flex items-center gap-3 flex-1 min-w-0">
                      <div className="flex-shrink-0">
                        <FileIcon className="h-10 w-10 text-blue-600" />
                      </div>
                      <div className="flex-1 min-w-0">
                        <p className="text-sm font-medium text-gray-900 truncate" title={doc.name}>
                          {doc.name}
                        </p>
                        <div className="flex items-center gap-2 mt-1 flex-wrap">
                          <span className="text-xs text-gray-500 capitalize">{doc.type.replace('_', ' ')}</span>
                          {doc.size && (
                            <>
                              <span className="text-xs text-gray-400">•</span>
                              <span className="text-xs text-gray-500">{formatFileSize(doc.size)}</span>
                            </>
                          )}
                          {doc.uploadedAt && (
                            <>
                              <span className="text-xs text-gray-400">•</span>
                              <span className="text-xs text-gray-500">
                                Uploaded {new Date(doc.uploadedAt).toLocaleDateString()}
                              </span>
                            </>
                          )}
                        </div>
                      </div>
                    </div>
                    <Button
                      type="button"
                      variant="ghost"
                      size="sm"
                      onClick={() => removeDocument(index)}
                      className="text-red-600 hover:text-red-700 hover:bg-red-50 flex-shrink-0"
                      title="Remove document"
                    >
                      <X className="h-4 w-4" />
                    </Button>
                  </div>
                </Card>
              )
            })}
          </div>
        </div>
      )}
    </div>
  )
}

