"use client"

import { useState, useRef, useCallback, useEffect } from 'react'
import { Button } from '@/components/ui/button'
import { Camera, Upload, X, User } from 'lucide-react'
import { authFetch } from '@/lib/fetchAuth'

interface ProfilePhotoUploadProps {
  userId: number
  currentPhoto?: string | null
  onPhotoUpdate: (photoData: string) => void
}

export default function ProfilePhotoUpload({ 
  userId, 
  currentPhoto, 
  onPhotoUpdate 
}: ProfilePhotoUploadProps) {
  const [isDragging, setIsDragging] = useState(false)
  const [isUploading, setIsUploading] = useState(false)
  const [error, setError] = useState<string | null>(null)
  const [previewPhoto, setPreviewPhoto] = useState<string | null>(currentPhoto || null)

  // Update preview photo when currentPhoto prop changes
  useEffect(() => {
    setPreviewPhoto(currentPhoto || null)
  }, [currentPhoto])
  const fileInputRef = useRef<HTMLInputElement>(null)

  const handleFileSelect = useCallback(async (file: File) => {
    if (!file) return

    // Validate file type
    const allowedTypes = ['image/jpeg', 'image/jpg', 'image/png', 'image/gif']
    if (!allowedTypes.includes(file.type)) {
      setError('Invalid file type. Only JPEG, PNG, and GIF are allowed.')
      return
    }

    // Validate file size (max 5MB)
    const maxSize = 5 * 1024 * 1024 // 5MB
    if (file.size > maxSize) {
      setError('File size too large. Maximum size is 5MB.')
      return
    }

    setError(null)
    setIsUploading(true)

    try {
      // Convert file to base64
      const reader = new FileReader()
      reader.onload = async (e) => {
        const base64Data = e.target?.result as string
        const photoData = base64Data.split(',')[1] // Remove data:image/...;base64, prefix

        // Upload to server
        const response = await authFetch('/api/user/upload-photo', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
          body: JSON.stringify({
            photoData,
            photoType: file.type,
            fileSize: file.size,
          }),
        })

        if (response.ok) {
          setPreviewPhoto(base64Data)
          onPhotoUpdate(base64Data)
          setError(null)
        } else {
          const errorData = await response.json()
          setError(errorData.error || 'Failed to upload photo')
        }
      }
      reader.readAsDataURL(file)
    } catch (error) {
      setError('Failed to process image')
    } finally {
      setIsUploading(false)
    }
  }, [userId, onPhotoUpdate])

  const handleDragOver = useCallback((e: React.DragEvent) => {
    e.preventDefault()
    setIsDragging(true)
  }, [])

  const handleDragLeave = useCallback((e: React.DragEvent) => {
    e.preventDefault()
    setIsDragging(false)
  }, [])

  const handleDrop = useCallback((e: React.DragEvent) => {
    e.preventDefault()
    setIsDragging(false)
    
    const files = e.dataTransfer.files
    if (files.length > 0) {
      handleFileSelect(files[0])
    }
  }, [handleFileSelect])

  const handleFileInputChange = useCallback((e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0]
    if (file) {
      handleFileSelect(file)
    }
  }, [handleFileSelect])

  const removePhoto = useCallback(async () => {
    try {
      // You can implement photo removal logic here if needed
      setPreviewPhoto(null)
      onPhotoUpdate('')
    } catch (error) {
      setError('Failed to remove photo')
    }
  }, [onPhotoUpdate])

  return (
    <div className="space-y-4">
      {/* Current Photo Display */}
      <div className="text-center">
        <div className="relative inline-block">
          <div className="w-32 h-32 rounded-full overflow-hidden border-4 border-gray-700 bg-gradient-to-br from-gray-800 to-gray-900">
            {previewPhoto ? (
              <img
                src={previewPhoto}
                alt="Profile"
                className="w-full h-full object-cover"
              />
            ) : (
              <div className="w-full h-full flex items-center justify-center">
                <User className="w-16 h-16 text-gray-400" />
              </div>
            )}
          </div>
          
          {/* Remove Photo Button */}
          {previewPhoto && (
            <button
              onClick={removePhoto}
              className="absolute -top-2 -right-2 w-8 h-8 bg-red-500 hover:bg-red-600 text-white rounded-full flex items-center justify-center transition-colors duration-200"
            >
              <X className="w-4 h-4" />
            </button>
          )}
        </div>
      </div>

      {/* Upload Area */}
      <div
        className={`border-2 border-dashed rounded-xl p-6 text-center transition-all duration-200 ${
          isDragging
            ? 'border-green-500 bg-green-500/10'
            : 'border-gray-600 hover:border-gray-500 bg-gray-800/30'
        }`}
        onDragOver={handleDragOver}
        onDragLeave={handleDragLeave}
        onDrop={handleDrop}
      >
        <div className="space-y-4">
          <div className="flex flex-col items-center space-y-2">
            <div className="w-16 h-16 bg-gradient-to-br from-green-500/20 to-blue-500/20 rounded-full flex items-center justify-center">
              {isUploading ? (
                <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-green-500"></div>
              ) : (
                <Upload className="w-8 h-8 text-green-400" />
              )}
            </div>
            <div>
              <p className="text-white font-medium">
                {isUploading ? 'Uploading...' : 'Upload Profile Photo'}
              </p>
              <p className="text-gray-400 text-sm">
                Drag & drop or click to select
              </p>
            </div>
          </div>

          <div className="flex flex-col sm:flex-row gap-3 justify-center">
            <Button
              onClick={() => fileInputRef.current?.click()}
              disabled={isUploading}
              className="bg-gradient-to-r from-green-600 to-green-700 hover:from-green-700 hover:to-green-800 text-white font-medium py-2 px-4 rounded-lg transition-all duration-200 transform hover:scale-105"
            >
              <Camera className="w-4 h-4 mr-2" />
              Choose File
            </Button>
            
            <Button
              variant="outline"
              disabled={isUploading}
              className="border-gray-600 text-gray-300 hover:border-green-500 hover:text-green-400"
            >
              <Upload className="w-4 h-4 mr-2" />
              Browse Files
            </Button>
          </div>

          <p className="text-gray-500 text-xs">
            Supports: JPEG, PNG, GIF • Max: 5MB
          </p>
        </div>
      </div>

      {/* Hidden File Input */}
      <input
        ref={fileInputRef}
        type="file"
        accept="image/*"
        onChange={handleFileInputChange}
        className="hidden"
      />

      {/* Error Display */}
      {error && (
        <div className="bg-red-500/20 border border-red-500/30 rounded-lg p-3">
          <p className="text-red-400 text-sm text-center">{error}</p>
        </div>
      )}
    </div>
  )
}
