import { useState, useRef } from 'react'
import { useAuthStore } from '../stores/authStore'

interface PhotoUploadProps {
  employeeId?: string
  currentPhoto?: string
  onPhotoUpdate?: (photoUrl: string | null) => void
  disabled?: boolean
}

export default function PhotoUpload({ 
  employeeId, 
  currentPhoto, 
  onPhotoUpdate, 
  disabled = false 
}: PhotoUploadProps) {
  const [uploading, setUploading] = useState(false)
  const [error, setError] = useState('')
  const [dragOver, setDragOver] = useState(false)
  const fileInputRef = useRef<HTMLInputElement>(null)
  const { token } = useAuthStore()

  const handleFileSelect = (file: File) => {
    if (!employeeId) {
      setError('Employee ID is required')
      return
    }

    // Validate file type
    const allowedTypes = ['image/jpeg', 'image/jpg', 'image/png', 'image/gif', 'image/webp']
    if (!allowedTypes.includes(file.type)) {
      setError('Nur Bilddateien sind erlaubt (JPEG, PNG, GIF, WebP)')
      return
    }

    // Validate file size (5MB)
    if (file.size > 5 * 1024 * 1024) {
      setError('Datei zu groß (max. 5MB)')
      return
    }

    uploadPhoto(file)
  }

  const uploadPhoto = async (file: File) => {
    if (!token) {
      setError('Not authenticated')
      return
    }

    setUploading(true)
    setError('')

    try {
      const formData = new FormData()
      formData.append('photo', file)

      const API_BASE_URL = (import.meta as any).env?.VITE_API_URL || 'http://localhost:3004/api'
      const response = await fetch(`${API_BASE_URL}/upload/employee-photo/${employeeId}`, {
        method: 'POST',
        headers: {
          'Authorization': `Bearer ${token}`
        },
        body: formData
      })

      const data = await response.json()

      if (!response.ok) {
        throw new Error(data.error?.message || 'Upload failed')
      }

      // Update photo URL
      const base = (import.meta as any).env?.VITE_API_PUBLIC_URL || (API_BASE_URL.replace(/\/api$/, ''))
      const photoUrl = `${base}${data.data.photoUrl}`
      onPhotoUpdate?.(photoUrl)

    } catch (err: any) {
      setError(err.message || 'Upload failed')
    } finally {
      setUploading(false)
    }
  }

  const deletePhoto = async () => {
    if (!employeeId || !token) return

    setUploading(true)
    setError('')

    try {
      const API_BASE_URL = (import.meta as any).env?.VITE_API_URL || 'http://localhost:3004/api'
      const response = await fetch(`${API_BASE_URL}/upload/employee-photo/${employeeId}`, {
        method: 'DELETE',
        headers: {
          'Authorization': `Bearer ${token}`,
          'Content-Type': 'application/json'
        }
      })

      const data = await response.json()

      if (!response.ok) {
        throw new Error(data.error?.message || 'Delete failed')
      }

      onPhotoUpdate?.(null)

    } catch (err: any) {
      setError(err.message || 'Delete failed')
    } finally {
      setUploading(false)
    }
  }

  const handleDragOver = (e: React.DragEvent) => {
    e.preventDefault()
    setDragOver(true)
  }

  const handleDragLeave = (e: React.DragEvent) => {
    e.preventDefault()
    setDragOver(false)
  }

  const handleDrop = (e: React.DragEvent) => {
    e.preventDefault()
    setDragOver(false)
    
    if (disabled || uploading) return

    const files = e.dataTransfer.files
    if (files.length > 0) {
      handleFileSelect(files[0])
    }
  }

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

  const triggerFileInput = () => {
    if (!disabled && !uploading) {
      fileInputRef.current?.click()
    }
  }

  const API_BASE = (import.meta as any).env?.VITE_API_URL || 'http://localhost:3004/api'
  const PUBLIC_BASE = (import.meta as any).env?.VITE_API_PUBLIC_URL || API_BASE.replace(/\/api$/, '')
  const displayPhoto = currentPhoto && currentPhoto.startsWith('/uploads/') ? `${PUBLIC_BASE}${currentPhoto}` : currentPhoto

  return (
    <div className="space-y-4">
      <div
        className={`relative w-32 h-32 rounded-full border-2 border-dashed transition-colors ${
          dragOver ? 'border-primary-blue bg-bg-accent' : 'border-border-default'
        } ${disabled ? 'opacity-50 cursor-not-allowed' : 'cursor-pointer'}`}
        onDragOver={handleDragOver}
        onDragLeave={handleDragLeave}
        onDrop={handleDrop}
        onClick={triggerFileInput}
      >
        {displayPhoto ? (
          <img
            src={displayPhoto}
            alt="Employee photo"
            className="w-full h-full rounded-full object-cover"
          />
        ) : (
          <div className="w-full h-full rounded-full bg-bg-accent dark:bg-dark-primary flex items-center justify-center">
            <svg className="w-8 h-8 text-text-placeholder" fill="none" viewBox="0 0 24 24" stroke="currentColor">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 6v6m0 0v6m0-6h6m-6 0H6" />
            </svg>
          </div>
        )}

        {uploading && (
          <div className="absolute inset-0 rounded-full bg-black bg-opacity-50 flex items-center justify-center">
            <div className="w-8 h-8 border-2 border-white border-t-transparent rounded-full animate-spin"></div>
          </div>
        )}

        <input
          ref={fileInputRef}
          type="file"
          accept="image/*"
          onChange={handleFileInputChange}
          className="hidden"
          disabled={disabled || uploading}
        />
      </div>

      <div className="flex space-x-2">
        <button
          onClick={triggerFileInput}
          disabled={disabled || uploading}
          className="btn-secondary text-xs"
        >
          {uploading ? 'Uploading...' : 'Photo auswählen'}
        </button>
        
        {currentPhoto && (
          <button
            onClick={deletePhoto}
            disabled={disabled || uploading}
            className="btn-secondary text-xs text-error hover:bg-error-bg"
          >
            Entfernen
          </button>
        )}
      </div>

      {error && (
        <p className="text-error text-xs">{error}</p>
      )}

      <p className="text-xs text-tertiary">
        Drag & Drop oder klicken zum Auswählen
        <br />
        Max. 5MB, JPEG/PNG/GIF/WebP
      </p>
    </div>
  )
}
