/**
 * FeedbackModal - Send feedback to BoostBot support center
 * 
 * Features:
 * - Bug reports, feature requests, questions
 * - Optional screenshot upload (drag & drop)
 * - Saves to feedback database table with image storage
 */

import { useState, useCallback } from 'react'
import { 
  MessageSquare, 
  X, 
  Upload, 
  Image as ImageIcon, 
  CheckCircle, 
  Bug,
  Lightbulb,
  HelpCircle,
  MoreHorizontal,
  AlertCircle
} from 'lucide-react'
import { Button } from './Button'
import { apiClient } from '@/api/client'
import { t } from '@/lib/i18n'

interface FeedbackModalProps {
  isOpen: boolean
  onClose: () => void
}

type FeedbackType = 'bug' | 'feature' | 'question' | 'other'

function getFeedbackTypes(): { value: FeedbackType; label: string; icon: typeof Bug }[] {
  return [
    { value: 'bug', label: t('Bug Report'), icon: Bug },
    { value: 'feature', label: t('Feature Request'), icon: Lightbulb },
    { value: 'question', label: t('Question'), icon: HelpCircle },
    { value: 'other', label: t('Other'), icon: MoreHorizontal },
  ]
}

export function FeedbackModal({ isOpen, onClose }: FeedbackModalProps) {
  const [type, setType] = useState<FeedbackType>('question')
  const [customType, setCustomType] = useState('')
  const [message, setMessage] = useState('')
  const [screenshot, setScreenshot] = useState<File | null>(null)
  const [screenshotPreview, setScreenshotPreview] = useState<string | null>(null)
  const [isSubmitting, setIsSubmitting] = useState(false)
  const [success, setSuccess] = useState(false)
  const [error, setError] = useState<string | null>(null)
  const [isDragging, setIsDragging] = useState(false)
  
  // Handle screenshot selection
  const handleScreenshotSelect = useCallback((file: File) => {
    // Validate file type
    if (!file.type.startsWith('image/')) {
      setError(t('Please upload an image file only'))
      return
    }
    
    // Validate file size (max 5MB)
    if (file.size > 5 * 1024 * 1024) {
      setError(t('Maximum file size is 5MB'))
      return
    }
    
    setScreenshot(file)
    setError(null)
    
    // Create preview
    const reader = new FileReader()
    reader.onloadend = () => {
      setScreenshotPreview(reader.result as string)
    }
    reader.readAsDataURL(file)
  }, [])
  
  // Handle drag events
  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 file = e.dataTransfer.files[0]
    if (file) {
      handleScreenshotSelect(file)
    }
  }, [handleScreenshotSelect])
  
  // Handle file input change
  const handleFileChange = useCallback((e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0]
    if (file) {
      handleScreenshotSelect(file)
    }
  }, [handleScreenshotSelect])
  
  // Remove screenshot
  const removeScreenshot = useCallback(() => {
    setScreenshot(null)
    setScreenshotPreview(null)
  }, [])
  
  // Submit feedback
  const handleSubmit = async () => {
    // Validate message
    if (message.trim().length < 10) {
      setError(t('Message must contain at least 10 characters'))
      return
    }
    
    setIsSubmitting(true)
    setError(null)
    
    try {
      // Build FormData to support image upload
      const formData = new FormData()
      // For 'other' type, send the custom type text; otherwise send the standard type
      const feedbackType = type === 'other' && customType.trim() ? `other:${customType.trim()}` : type
      formData.append('type', feedbackType)
      formData.append('message', message)
      formData.append('browser_info', navigator.userAgent)
      
      if (screenshot) {
        formData.append('screenshot', screenshot)
      }
      
      // Send via upload (multipart/form-data) to support images
      await apiClient.upload('feedback', formData)
      
      setSuccess(true)
      
      // Close after 2 seconds
      setTimeout(() => {
        handleClose()
      }, 2000)
      
    } catch (err) {
      console.error('Failed to send feedback:', err)
      setError(t('An error occurred while sending feedback. Please try again later.'))
    } finally {
      setIsSubmitting(false)
    }
  }
  
  // Reset and close
  const handleClose = useCallback(() => {
    setType('question')
    setCustomType('')
    setMessage('')
    setScreenshot(null)
    setScreenshotPreview(null)
    setSuccess(false)
    setError(null)
    setIsSubmitting(false)
    onClose()
  }, [onClose])
  
  if (!isOpen) return null
  
  return (
    <div 
      className="fixed inset-0 z-50 flex items-center justify-center bg-black/50"
      onClick={handleClose}
    >
      <div 
        className="bg-white rounded-2xl shadow-2xl max-w-md w-full mx-4 overflow-hidden"
        onClick={(e) => e.stopPropagation()}
      >
        {/* Header */}
        <div className="flex items-center justify-between px-6 py-4 border-b border-gray-100 bg-gradient-to-r from-primary-500 to-primary-600">
          <h2 className="text-lg font-semibold text-white flex items-center gap-2">
            <MessageSquare className="w-5 h-5" />
            {t('Send Us Feedback')}
          </h2>
          <button
            onClick={handleClose}
            className="text-white/80 hover:text-white transition-colors"
          >
            <X className="w-5 h-5" />
          </button>
        </div>
        
        {/* Content */}
        <div className="p-6">
          {success ? (
            // Success state
            <div className="text-center py-8">
              <div className="w-16 h-16 bg-green-100 rounded-full flex items-center justify-center mx-auto mb-4">
                <CheckCircle className="w-10 h-10 text-green-500" />
              </div>
              <h3 className="text-xl font-semibold text-gray-900 mb-2">
                {t('Thank you for your feedback!')}
              </h3>
              <p className="text-gray-500">
                {t('We will get back to you as soon as possible')}
              </p>
            </div>
          ) : (
            <>
              {/* Error message */}
              {error && (
                <div className="mb-4 p-3 bg-red-50 border border-red-200 rounded-lg flex items-start gap-2">
                  <AlertCircle className="w-5 h-5 text-red-500 flex-shrink-0 mt-0.5" />
                  <p className="text-sm text-red-600">{error}</p>
                </div>
              )}
              
              {/* Feedback Type */}
              <div className="mb-4">
                <label className="block text-sm font-medium text-gray-700 mb-2">
                  {t('Type of Inquiry')}
                </label>
                <div className="grid grid-cols-2 gap-2">
                  {getFeedbackTypes().map(({ value, label, icon: Icon }) => (
                    <button
                      key={value}
                      type="button"
                      onClick={() => setType(value)}
                      className={`
                        flex items-center gap-2 px-4 py-3 rounded-lg border-2 transition-all
                        ${type === value 
                          ? 'border-primary-500 bg-primary-50 text-primary-700' 
                          : 'border-gray-200 text-gray-600 hover:border-gray-300'
                        }
                      `}
                    >
                      <Icon className="w-4 h-4" />
                      <span className="text-sm font-medium">{label}</span>
                    </button>
                  ))}
                </div>
                
                {/* Custom type input - shown when 'Other' is selected */}
                {type === 'other' && (
                  <div className="mt-3">
                    <input
                      type="text"
                      value={customType}
                      onChange={(e) => setCustomType(e.target.value)}
                      placeholder={t('Describe the type of inquiry...')}
                      maxLength={50}
                      className="w-full px-4 py-2.5 border border-gray-200 rounded-lg text-sm
                        focus:outline-none focus:ring-2 focus:ring-primary-500 focus:border-transparent
                        placeholder:text-gray-400"
                    />
                  </div>
                )}
              </div>
              
              {/* Message */}
              <div className="mb-4">
                <label className="block text-sm font-medium text-gray-700 mb-2">
                  {t('Your Message')}
                </label>
                <textarea
                  value={message}
                  onChange={(e) => setMessage(e.target.value)}
                  placeholder={t('Tell us how we can help...')}
                  className="w-full px-4 py-3 border border-gray-200 rounded-lg resize-none h-32 
                    focus:outline-none focus:ring-2 focus:ring-primary-500 focus:border-transparent
                    placeholder:text-gray-400"
                />
                <p className="text-xs text-gray-400 mt-1">
                  {message.length}/10 {t('characters minimum')}
                </p>
              </div>
              
              {/* Screenshot Upload */}
              <div className="mb-6">
                <label className="block text-sm font-medium text-gray-700 mb-2">
                  {t('Screenshot (optional)')}
                </label>
                
                {screenshotPreview ? (
                  // Preview
                  <div className="relative rounded-lg border-2 border-green-300 bg-green-50 p-2">
                    <img 
                      src={screenshotPreview} 
                      alt="Screenshot preview" 
                      className="max-h-32 mx-auto rounded"
                    />
                    <button
                      type="button"
                      onClick={removeScreenshot}
                      className="absolute top-2 left-2 w-6 h-6 bg-red-500 text-white rounded-full 
                        flex items-center justify-center hover:bg-red-600 transition-colors"
                    >
                      <X className="w-4 h-4" />
                    </button>
                    <p className="text-center text-sm text-green-600 mt-2 flex items-center justify-center gap-1">
                      <ImageIcon className="w-4 h-4" />
                      {screenshot?.name}
                    </p>
                  </div>
                ) : (
                  // Drop zone
                  <div
                    className={`
                      border-2 border-dashed rounded-lg p-6 text-center cursor-pointer
                      transition-all
                      ${isDragging 
                        ? 'border-primary-500 bg-primary-50' 
                        : 'border-gray-300 hover:border-primary-400 hover:bg-gray-50'
                      }
                    `}
                    onDragOver={handleDragOver}
                    onDragLeave={handleDragLeave}
                    onDrop={handleDrop}
                    onClick={() => document.getElementById('screenshot-input')?.click()}
                  >
                    <input
                      id="screenshot-input"
                      type="file"
                      accept="image/*"
                      className="hidden"
                      onChange={handleFileChange}
                    />
                    <Upload className={`w-8 h-8 mx-auto mb-2 ${isDragging ? 'text-primary-500' : 'text-gray-400'}`} />
                    <p className="text-sm text-gray-600">
                      {isDragging ? t('Drop image here') : t('Drag image here or click to select')}
                    </p>
                    <p className="text-xs text-gray-400 mt-1">
                      {t('Up to 5MB')} &bull; JPG, PNG, GIF, WebP
                    </p>
                  </div>
                )}
              </div>
              
              {/* Submit Button */}
              <Button
                onClick={handleSubmit}
                disabled={isSubmitting || message.trim().length < 10}
                loading={isSubmitting}
                className="w-full"
                size="lg"
              >
                {isSubmitting ? t('Sending...') : t('Send Feedback')}
              </Button>
              
              {/* Info */}
              <p className="text-xs text-gray-400 text-center mt-3">
                {t('The feedback will be sent to our support center')}
              </p>
              <p className="text-xs text-gray-400 text-center mt-1">
                {t('Successful feedback may earn BoostCoins for the site (at our discretion — awarded to the first site to report a given issue).')}
              </p>
            </>
          )}
        </div>
      </div>
    </div>
  )
}
