/**
 * BoostMedia AI Content Generator Admin - Regenerate Image Dialog
 *
 * @package BoostMedia_AI
 * @license GPL-2.0-or-later
 */

import { useState, useEffect } from 'react'
import { X, ImageIcon, RefreshCw } from 'lucide-react'
import { Button } from '../common'
import { endpoints } from '../../api/client'
import { t } from '../../lib/i18n'

interface RegenerateImageDialogProps {
  postId: number
  postTitle: string
  currentImageUrl?: string
  isOpen: boolean
  onClose: () => void
  onSuccess: (newImageUrl: string, thumbnailUrl: string) => void
}

export function RegenerateImageDialog({
  postId,
  postTitle,
  currentImageUrl,
  isOpen,
  onClose,
  onSuccess,
}: RegenerateImageDialogProps) {
  const [notes, setNotes] = useState('')
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState('')
  const [balance, setBalance] = useState<number | null>(null)

  useEffect(() => {
    if (isOpen) {
      setError('')
      setBalance(null)
      endpoints.getCreditsStatus()
        .then((res: any) => {
          const d = res.data ?? res
          const total =
            (d.credits?.free?.remaining || 0) +
            (d.boost_credits?.remaining || 0) +
            (d.credits?.subscription?.remaining || 0)
          setBalance(total)
        })
        .catch(() => setBalance(null))
    }
  }, [isOpen])

  if (!isOpen) return null

  const handleRegenerate = async () => {
    setLoading(true)
    setError('')
    try {
      const response = await endpoints.regenerateImage(postId, notes || undefined)
      const data = response.data
      onSuccess(data.image_url, data.thumbnail_url)
      setNotes('')
      onClose()
    } catch (err: any) {
      const msg = err?.message || err?.error?.message
      if (msg?.includes('INSUFFICIENT_CREDITS') || msg?.includes('Insufficient credits')) {
        setError(t('Insufficient credits for image generation. Visit the Usage page to purchase more.'))
      } else {
        setError(t('Failed to generate image. Please try again.'))
      }
    } finally {
      setLoading(false)
    }
  }

  const handleBackdropClick = (e: React.MouseEvent) => {
    if (e.target === e.currentTarget && !loading) {
      onClose()
    }
  }

  return (
    <div
      className="fixed inset-0 bg-black/50 z-50 flex items-center justify-center p-4"
      onClick={handleBackdropClick}
    >
      <div className="bg-white rounded-bc-lg shadow-xl w-full max-w-md">
        {/* Header */}
        <div className="flex items-center justify-between p-4 border-b border-bc-gray-200">
          <div className="flex items-center gap-2">
            <RefreshCw className="w-5 h-5 text-bc-primary" />
            <h3 className="font-semibold text-bc-gray-800">
              {currentImageUrl ? t('Regenerate Image') : t('Generate Image')}
            </h3>
          </div>
          <button
            onClick={onClose}
            disabled={loading}
            className="p-1 text-bc-gray-400 hover:text-bc-gray-600 transition-colors disabled:opacity-50"
          >
            <X className="w-5 h-5" />
          </button>
        </div>

        {/* Body */}
        <div className="p-4 space-y-4">
          {/* Current image preview */}
          {currentImageUrl && (
            <div className="flex justify-center">
              <img
                src={currentImageUrl}
                alt={postTitle}
                className="max-h-32 rounded-bc border border-bc-gray-200 object-cover"
              />
            </div>
          )}

          {/* Notes textarea */}
          <div>
            <label className="block text-sm font-medium text-bc-gray-700 mb-1">
              {t('Additional instructions (optional):')}
            </label>
            <textarea
              value={notes}
              onChange={(e) => setNotes(e.target.value)}
              placeholder={t('e.g., Make the image brighter, add a water pump in the foreground...')}
              rows={3}
              disabled={loading}
              className="w-full rounded-bc border border-bc-gray-300 px-3 py-2 text-sm text-bc-gray-800 placeholder:text-bc-gray-400 focus:border-bc-primary focus:ring-1 focus:ring-bc-primary disabled:opacity-50 resize-none"
              style={{ textAlign: 'start' }}
            />
          </div>

          {/* Hint */}
          <p className="text-xs text-bc-gray-500 flex items-start gap-1.5">
            <ImageIcon className="w-3.5 h-3.5 mt-0.5 shrink-0" />
            {t('These notes will be combined with the original image description')}
          </p>

          {/* Balance & Cost */}
          <div className="p-3 rounded-bc bg-bc-gray-50 border border-bc-gray-200 text-sm space-y-1">
            {balance !== null && (
              <p className="text-bc-gray-600">
                {t('Current balance')}: <strong>{balance.toFixed(1)} BoostCoins</strong>
              </p>
            )}
            <p className="text-bc-gray-600">
              {t('Image generation cost')}: <strong>~0.5 BoostCoin</strong>
            </p>
          </div>

          {/* Error */}
          {error && (
            <div className="p-3 rounded-bc bg-red-50 border border-red-200 text-sm text-red-700">
              {error}
            </div>
          )}
        </div>

        {/* Footer */}
        <div className="flex items-center justify-end gap-2 p-4 border-t border-bc-gray-200">
          <Button
            variant="ghost"
            size="sm"
            onClick={onClose}
            disabled={loading}
          >
            {t('Cancel')}
          </Button>
          <Button
            variant="primary"
            size="sm"
            onClick={handleRegenerate}
            disabled={loading}
            loading={loading}
            icon={<ImageIcon className="w-4 h-4" />}
          >
            {loading ? t('Generating...') : t('Generate New Image')}
          </Button>
        </div>
      </div>
    </div>
  )
}
