/**
 * FeedbackModal — send feedback to the BoostMedia centralized backend.
 *
 * Adapted from BoostBot's FeedbackModal, restyled to BMAI's bc-* tailwind tokens
 * and routed through `api.upload('feedback', formData)` (which proxies to
 * `POST /wp-json/bmai/v1/feedback`, which proxies to `/api/v1/feedback` on the backend).
 *
 * @package BoostMedia_AI
 * @license GPL-2.0-or-later
 */

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 { api } 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)

  const handleScreenshotSelect = useCallback((file: File) => {
    if (!file.type.startsWith('image/')) {
      setError(t('Please upload an image file only'))
      return
    }
    if (file.size > 5 * 1024 * 1024) {
      setError(t('Maximum file size is 5MB'))
      return
    }
    setScreenshot(file)
    setError(null)
    const reader = new FileReader()
    reader.onloadend = () => setScreenshotPreview(reader.result as string)
    reader.readAsDataURL(file)
  }, [])

  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])

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

  const removeScreenshot = useCallback(() => {
    setScreenshot(null); setScreenshotPreview(null)
  }, [])

  const handleSubmit = async () => {
    if (message.trim().length < 10) {
      setError(t('Message must contain at least 10 characters'))
      return
    }
    setIsSubmitting(true); setError(null)
    try {
      const formData = new FormData()
      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)

      await api.upload('feedback', formData)
      setSuccess(true)
      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)
    }
  }

  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-bc-md shadow-bc-lg 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-bc-gray-100 bg-gradient-to-r from-bc-primary to-bc-primary-dark">
          <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 bg-transparent border-0 cursor-pointer"
          >
            <X className="w-5 h-5" />
          </button>
        </div>

        {/* Content */}
        <div className="p-6">
          {success ? (
            <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-bc-gray-800 mb-2">
                {t('Thank you for your feedback!')}
              </h3>
              <p className="text-bc-gray-500">
                {t('We will get back to you as soon as possible')}
              </p>
            </div>
          ) : (
            <>
              {error && (
                <div className="mb-4 p-3 bg-red-50 border border-red-200 rounded-bc 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-bc-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-bc border-2 transition-all bg-white cursor-pointer
                        ${type === value
                          ? 'border-bc-primary bg-bc-primary-light text-bc-primary'
                          : 'border-bc-gray-200 text-bc-gray-600 hover:border-bc-gray-300'}
                      `}
                    >
                      <Icon className="w-4 h-4" />
                      <span className="text-sm font-medium">{label}</span>
                    </button>
                  ))}
                </div>
                {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-bc-gray-200 rounded-bc text-sm
                        focus:outline-none focus:ring-2 focus:ring-bc-primary focus:border-transparent
                        placeholder:text-bc-gray-400"
                    />
                  </div>
                )}
              </div>

              {/* Message */}
              <div className="mb-4">
                <label className="block text-sm font-medium text-bc-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-bc-gray-200 rounded-bc resize-none h-32
                    focus:outline-none focus:ring-2 focus:ring-bc-primary focus:border-transparent
                    placeholder:text-bc-gray-400"
                />
                <p className="text-xs text-bc-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-bc-gray-700 mb-2">
                  {t('Screenshot (optional)')}
                </label>

                {screenshotPreview ? (
                  <div className="relative rounded-bc 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 border-0 cursor-pointer"
                    >
                      <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>
                ) : (
                  <div
                    className={`
                      border-2 border-dashed rounded-bc p-6 text-center cursor-pointer
                      transition-all
                      ${isDragging
                        ? 'border-bc-primary bg-bc-primary-light'
                        : 'border-bc-gray-300 hover:border-bc-primary/40 hover:bg-bc-gray-50'}
                    `}
                    onDragOver={handleDragOver}
                    onDragLeave={handleDragLeave}
                    onDrop={handleDrop}
                    onClick={() => document.getElementById('bmai-screenshot-input')?.click()}
                  >
                    <input
                      id="bmai-screenshot-input"
                      type="file"
                      accept="image/*"
                      className="hidden"
                      onChange={handleFileChange}
                    />
                    <Upload className={`w-8 h-8 mx-auto mb-2 ${isDragging ? 'text-bc-primary' : 'text-bc-gray-400'}`} />
                    <p className="text-sm text-bc-gray-600">
                      {isDragging ? t('Drop image here') : t('Drag image here or click to select')}
                    </p>
                    <p className="text-xs text-bc-gray-400 mt-1">
                      {t('Up to 5MB')} &bull; JPG, PNG, GIF, WebP
                    </p>
                  </div>
                )}
              </div>

              <Button
                onClick={handleSubmit}
                disabled={isSubmitting || message.trim().length < 10}
                loading={isSubmitting}
                size="lg"
                className="w-full"
              >
                {isSubmitting ? t('Sending...') : t('Send Feedback')}
              </Button>

              <p className="text-xs text-bc-gray-400 text-center mt-3">
                {t('The feedback will be sent to our support center')}
              </p>
            </>
          )}
        </div>
      </div>
    </div>
  )
}
