import { useState, useEffect, useMemo } from 'react'
import { useParams } from 'react-router-dom'
import { CheckCircle, XCircle, AlertCircle, Languages, Globe, User, Check, PenLine, Copy, Lock } from 'lucide-react'
import { useLanguage } from '../i18n/LanguageContext'
import { AVAILABLE_LANGUAGES, isTextSelected, groupTextsByLanguage } from '../utils/translations'
import { useToast } from '../components/ToastContainer'
import Modal from '../components/Modal'

export default function PublicTranslationReview() {
  const { token } = useParams()
  const { t } = useLanguage()
  const toast = useToast()
  const [translation, setTranslation] = useState(null)
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState('')
  const [submitting, setSubmitting] = useState(false)
  const [success, setSuccess] = useState('')
  const [reviewerName, setReviewerName] = useState('')
  const [feedback, setFeedback] = useState('')
  const [pendingAction, setPendingAction] = useState(null)
  const [suggestingLang, setSuggestingLang] = useState(null)
  const [suggestionContent, setSuggestionContent] = useState('')
  const [selectingId, setSelectingId] = useState(null)
  const [copiedId, setCopiedId] = useState(null)

  useEffect(() => {
    loadTranslation()
  }, [token])

  const loadTranslation = async () => {
    try {
      const res = await fetch(`/api/public/review-translation/${token}`)
      if (!res.ok) {
        const err = await res.json()
        setError(err.error || t('review.loadFailed'))
        setLoading(false)
        return
      }
      const data = await res.json()
      setTranslation(data)
      if (data.approvers?.length === 1 && data.approvers[0].name) {
        setReviewerName(data.approvers[0].name)
      }
    } catch (err) {
      setError(t('review.loadFailed'))
    } finally {
      setLoading(false)
    }
  }

  const handleAction = async (action) => {
    if ((action === 'approve' || action === 'reject') && !reviewerName.trim()) {
      toast.error(t('review.nameRequired'))
      return
    }
    if ((action === 'reject' || action === 'revision') && !feedback.trim()) {
      toast.error(t('review.feedbackRequiredError'))
      return
    }

    setSubmitting(true)
    try {
      const res = await fetch(`/api/public/review-translation/${token}/${action}`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          approved_by_name: reviewerName || 'Anonymous',
          feedback: feedback || '',
        }),
      })
      if (!res.ok) {
        const err = await res.json()
        throw new Error(err.error || 'Action failed')
      }
      if (action === 'approve') setSuccess(t('review.approveSuccess'))
      else if (action === 'reject') setSuccess(t('review.rejectSuccess'))
      else setSuccess(t('review.revisionSuccess'))
      setPendingAction(null)
    } catch (err) {
      toast.error(err.message)
    } finally {
      setSubmitting(false)
    }
  }

  const handleSelect = async (textId) => {
    setSelectingId(textId)
    try {
      const res = await fetch(`/api/public/review-translation/${token}/select`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ text_id: textId }),
      })
      if (!res.ok) {
        const err = await res.json()
        throw new Error(err.error || 'Selection failed')
      }
      setTranslation(prev => ({
        ...prev,
        texts: prev.texts.map(txt => ({
          ...txt,
          is_selected: txt.language_code === prev.texts.find(t => (t.Id || t.id) === textId)?.language_code
            ? (txt.Id || txt.id) === textId
            : txt.is_selected,
        })),
      }))
      toast.success(t('translations.optionSelected'))
    } catch (err) {
      toast.error(err.message)
    } finally {
      setSelectingId(null)
    }
  }

  const handleSuggest = async (langCode) => {
    if (!suggestionContent.trim()) return
    setSubmitting(true)
    try {
      const langDef = AVAILABLE_LANGUAGES.find(l => l.code === langCode)
      const res = await fetch(`/api/public/review-translation/${token}/suggest`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          language_code: langCode,
          language_label: langDef?.label || langCode,
          content: suggestionContent,
          suggested_by: reviewerName || 'Reviewer',
        }),
      })
      if (!res.ok) {
        const err = await res.json()
        throw new Error(err.error || 'Suggestion failed')
      }
      const newText = await res.json()
      setTranslation(prev => ({
        ...prev,
        texts: [...(prev.texts || []), newText],
      }))
      setSuggestingLang(null)
      setSuggestionContent('')
      toast.success(t('translations.suggestionAdded'))
    } catch (err) {
      toast.error(err.message)
    } finally {
      setSubmitting(false)
    }
  }

  const copyContent = (text, id) => {
    navigator.clipboard.writeText(text)
    setCopiedId(id)
    toast.success(t('translations.copiedToClipboard'))
    setTimeout(() => setCopiedId(null), 2000)
  }

  // Group texts by language (memoized)
  const textsByLanguage = useMemo(
    () => translation?.texts ? groupTextsByLanguage(translation.texts) : {},
    [translation?.texts]
  )

  const isPendingReview = translation?.status === 'pending_review'
  const isApproved = translation?.status === 'approved'
  const isRejected = translation?.status === 'rejected'

  if (loading) {
    return (
      <div className="min-h-screen flex items-center justify-center bg-surface-secondary">
        <div className="w-8 h-8 border-4 border-brand-primary border-t-transparent rounded-full animate-spin" />
      </div>
    )
  }

  if (error) {
    return (
      <div className="min-h-screen flex items-center justify-center bg-surface-secondary">
        <div className="text-center">
          <AlertCircle className="w-12 h-12 text-red-500 mx-auto mb-3" />
          <h2 className="text-lg font-semibold text-text-primary mb-1">{t('review.errorTitle')}</h2>
          <p className="text-text-secondary">{error}</p>
        </div>
      </div>
    )
  }

  if (success) {
    return (
      <div className="min-h-screen flex items-center justify-center bg-surface-secondary">
        <div className="text-center">
          <CheckCircle className="w-12 h-12 text-emerald-500 mx-auto mb-3" />
          <h2 className="text-lg font-semibold text-text-primary mb-1">{success}</h2>
          <p className="text-text-secondary">{t('review.thankYou')}</p>
        </div>
      </div>
    )
  }

  if (!translation) return null

  return (
    <div className="min-h-screen bg-surface-secondary">
      <div className="max-w-4xl mx-auto px-4 py-8">
        {/* Header */}
        <div className="bg-surface rounded-xl border border-border p-6 mb-6">
          <div className="flex items-start gap-4">
            <div className="w-12 h-12 rounded-xl bg-brand-primary/10 flex items-center justify-center shrink-0">
              <Languages className="w-6 h-6 text-brand-primary" />
            </div>
            <div className="flex-1 min-w-0">
              <div className="flex items-center gap-2 mb-1">
                <h2 className="text-2xl font-bold text-text-primary">{translation.title}</h2>
                {isApproved && (
                  <span className="text-xs px-2 py-0.5 rounded-full bg-emerald-100 text-emerald-700 font-medium flex items-center gap-1">
                    <Lock className="w-3 h-3" />
                    {t('review.approved')}
                  </span>
                )}
                {isRejected && (
                  <span className="text-xs px-2 py-0.5 rounded-full bg-red-100 text-red-700 font-medium">
                    {t('review.rejected')}
                  </span>
                )}
              </div>
              <div className="flex items-center gap-2 text-sm text-text-tertiary flex-wrap">
                {translation.brand_name && <span>{translation.brand_name}</span>}
                {translation.creator_name && <span className="font-medium text-text-secondary">{t('review.createdBy')} <strong>{translation.creator_name}</strong></span>}
              </div>
            </div>
          </div>
        </div>

        {/* Source Content */}
        <div className="bg-surface rounded-xl border border-border p-6 mb-6">
          <div className="flex items-center gap-2 mb-3">
            <Globe className="w-5 h-5 text-blue-600" />
            <h3 className="text-lg font-semibold text-text-primary">
              {t('translations.sourceContent')}
            </h3>
            <span className="text-xs px-2 py-0.5 rounded-full bg-blue-50 text-blue-600 font-medium">
              {translation.source_language}
            </span>
          </div>
          <div className="bg-blue-50 border border-blue-200 rounded-lg p-4">
            <p className="text-sm text-blue-900 whitespace-pre-wrap leading-relaxed">{translation.source_content}</p>
          </div>
        </div>

        {/* Translation Options by Language */}
        {Object.keys(textsByLanguage).length > 0 && (
          <div className="bg-surface rounded-xl border border-border p-6 mb-6">
            <h3 className="text-lg font-semibold text-text-primary mb-4">
              {t('translations.translationTexts')}
            </h3>
            <div className="space-y-6">
              {Object.entries(textsByLanguage).map(([langCode, options]) => {
                const langLabel = options[0]?.language_label || langCode
                const hasSelected = options.some(isTextSelected)
                return (
                  <div key={langCode}>
                    <div className="flex items-center justify-between mb-3">
                      <div className="flex items-center gap-2">
                        <span className="text-sm font-semibold text-text-primary">{langLabel}</span>
                        <span className="text-xs text-text-tertiary">({langCode})</span>
                        <span className="text-xs text-text-tertiary">
                          — {options.length} {options.length === 1 ? t('translations.option') : t('translations.options')}
                        </span>
                      </div>
                      {isPendingReview && (
                        <button
                          onClick={() => {
                            setSuggestingLang(langCode)
                            setSuggestionContent('')
                          }}
                          className="flex items-center gap-1 text-xs text-brand-primary hover:text-brand-primary/80 font-medium"
                        >
                          <PenLine className="w-3.5 h-3.5" />
                          {t('translations.suggestAlternative')}
                        </button>
                      )}
                    </div>
                    <div className="space-y-2">
                      {options.map((text) => {
                        const textId = text.Id || text.id
                        const isSelected = isTextSelected(text)
                        // When approved, show only the selected option prominently; others are dimmed
                        const isDimmed = isApproved && hasSelected && !isSelected
                        return (
                          <div
                            key={textId}
                            className={`rounded-lg p-4 border transition-all ${
                              isSelected
                                ? 'bg-emerald-50 border-emerald-300 ring-1 ring-emerald-200'
                                : isDimmed
                                  ? 'bg-surface-secondary border-border opacity-50'
                                  : 'bg-surface-secondary border-border hover:border-brand-primary/30'
                            }`}
                          >
                            <div className="flex items-start gap-3">
                              <div className="flex-1 min-w-0">
                                <div className="flex items-center gap-2 mb-1">
                                  <span className="text-xs font-medium text-text-tertiary">
                                    {t('translations.optionLabel')} {text.option_number || 1}
                                  </span>
                                  {isSelected && (
                                    <span className="text-xs px-1.5 py-0.5 rounded bg-emerald-100 text-emerald-700 font-medium flex items-center gap-1">
                                      <Check className="w-3 h-3" />
                                      {t('translations.selected')}
                                    </span>
                                  )}
                                </div>
                                <p className="text-sm text-text-secondary whitespace-pre-wrap leading-relaxed">{text.content}</p>
                              </div>
                              <div className="flex items-center gap-1 shrink-0">
                                {/* Copy button — always available, especially useful for approved */}
                                {(isApproved || isSelected) && (
                                  <button
                                    onClick={() => copyContent(text.content, textId)}
                                    className="p-1.5 rounded-lg text-text-tertiary hover:text-text-primary hover:bg-surface-tertiary transition-colors"
                                    title={t('translations.copyContent')}
                                  >
                                    {copiedId === textId ? <Check className="w-4 h-4 text-emerald-600" /> : <Copy className="w-4 h-4" />}
                                  </button>
                                )}
                                {/* Select button — only when pending review */}
                                {isPendingReview && (
                                  <button
                                    onClick={() => handleSelect(textId)}
                                    disabled={selectingId === textId || isSelected}
                                    className={`px-3 py-1.5 rounded-lg text-xs font-medium transition-colors ${
                                      isSelected
                                        ? 'bg-emerald-100 text-emerald-700 cursor-default'
                                        : 'bg-brand-primary/10 text-brand-primary hover:bg-brand-primary/20'
                                    }`}
                                  >
                                    {selectingId === textId ? '...' : isSelected ? t('translations.selected') : t('translations.selectThis')}
                                  </button>
                                )}
                              </div>
                            </div>
                          </div>
                        )
                      })}
                    </div>

                    {/* Inline suggestion form for this language */}
                    {suggestingLang === langCode && (
                      <div className="mt-3 bg-amber-50 border border-amber-200 rounded-lg p-4">
                        <p className="text-sm font-medium text-amber-800 mb-2">{t('translations.suggestForLang')} {langLabel}</p>
                        <textarea
                          value={suggestionContent}
                          onChange={e => setSuggestionContent(e.target.value)}
                          placeholder={t('translations.enterSuggestion')}
                          className="w-full px-3 py-2 text-sm border border-amber-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-amber-400/30 min-h-[80px] resize-y bg-white"
                        />
                        <div className="flex items-center gap-2 mt-2">
                          <button
                            onClick={() => handleSuggest(langCode)}
                            disabled={submitting || !suggestionContent.trim()}
                            className="px-3 py-1.5 bg-amber-600 text-white text-xs font-medium rounded-lg hover:bg-amber-700 disabled:opacity-50 transition-colors"
                          >
                            {submitting ? '...' : t('translations.submitSuggestion')}
                          </button>
                          <button
                            onClick={() => setSuggestingLang(null)}
                            className="px-3 py-1.5 text-xs text-text-secondary hover:text-text-primary transition-colors"
                          >
                            {t('common.cancel')}
                          </button>
                        </div>
                      </div>
                    )}
                  </div>
                )
              })}
            </div>
          </div>
        )}

        {/* Review Actions — only pending_review */}
        {isPendingReview && (
          <div className="bg-surface rounded-xl border border-border p-6">
            <h3 className="text-lg font-semibold text-text-primary mb-4">{t('review.yourReview')}</h3>

            {/* Reviewer identity */}
            <div className="mb-4">
              {translation.approvers?.length === 1 ? (
                <div className="flex items-center gap-2 mb-3">
                  <User className="w-4 h-4 text-text-tertiary" />
                  <span className="text-sm text-text-primary">{translation.approvers[0].name}</span>
                </div>
              ) : translation.approvers?.length > 1 ? (
                <div className="mb-3">
                  <label className="block text-sm font-medium text-text-primary mb-1">{t('review.selectYourName')}</label>
                  <select
                    value={reviewerName}
                    onChange={e => setReviewerName(e.target.value)}
                    className="w-full px-3 py-2 text-sm border border-border rounded-lg focus:outline-none focus:ring-2 focus:ring-brand-primary/20"
                  >
                    <option value="">{t('review.selectApprover')}</option>
                    {translation.approvers.map(a => (
                      <option key={a.id} value={a.name}>{a.name}</option>
                    ))}
                  </select>
                </div>
              ) : (
                <div className="mb-3">
                  <label className="block text-sm font-medium text-text-primary mb-1">{t('review.yourName')}</label>
                  <input
                    type="text"
                    value={reviewerName}
                    onChange={e => setReviewerName(e.target.value)}
                    className="w-full px-3 py-2 text-sm border border-border rounded-lg focus:outline-none focus:ring-2 focus:ring-brand-primary/20"
                    placeholder={t('review.enterYourName')}
                  />
                </div>
              )}
            </div>

            {/* Feedback */}
            <div className="mb-4">
              <label className="block text-sm font-medium text-text-primary mb-1">{t('review.feedback')}</label>
              <textarea
                value={feedback}
                onChange={e => setFeedback(e.target.value)}
                className="w-full px-3 py-2 text-sm border border-border rounded-lg focus:outline-none focus:ring-2 focus:ring-brand-primary/20 min-h-[100px] resize-y"
                placeholder={t('review.feedbackPlaceholder')}
              />
            </div>

            {/* Action buttons */}
            <div className="flex items-center gap-3">
              <button
                onClick={() => handleAction('approve')}
                disabled={submitting || !reviewerName.trim()}
                className="flex-1 flex items-center justify-center gap-2 py-3 bg-emerald-600 text-white rounded-lg font-medium hover:bg-emerald-700 disabled:opacity-50 transition-colors"
              >
                <CheckCircle className="w-5 h-5" />
                {t('review.approve')}
              </button>
              <button
                onClick={() => handleAction('revision')}
                disabled={submitting || !feedback.trim()}
                className="flex-1 flex items-center justify-center gap-2 py-3 bg-amber-500 text-white rounded-lg font-medium hover:bg-amber-600 disabled:opacity-50 transition-colors"
              >
                <AlertCircle className="w-5 h-5" />
                {t('review.requestRevision')}
              </button>
              <button
                onClick={() => setPendingAction('reject')}
                disabled={submitting}
                className="flex-1 flex items-center justify-center gap-2 py-3 bg-red-600 text-white rounded-lg font-medium hover:bg-red-700 disabled:opacity-50 transition-colors"
              >
                <XCircle className="w-5 h-5" />
                {t('review.reject')}
              </button>
            </div>
          </div>
        )}

        {/* Approved state — read-only with copy buttons */}
        {isApproved && (
          <div className="bg-surface rounded-xl border border-border p-6">
            <div className="flex items-center gap-3 mb-3">
              <CheckCircle className="w-6 h-6 text-emerald-500" />
              <div>
                <p className="text-text-primary font-semibold">{t('review.approved')}</p>
                {translation.approved_by_name && (
                  <p className="text-sm text-text-secondary">
                    {t('review.reviewedBy')} <strong>{translation.approved_by_name}</strong>
                  </p>
                )}
              </div>
            </div>
            {translation.feedback && (
              <div className="bg-surface-secondary rounded-lg p-3 mt-3">
                <p className="text-xs font-medium text-text-tertiary mb-1">{t('review.feedback')}</p>
                <p className="text-sm text-text-secondary whitespace-pre-wrap">{translation.feedback}</p>
              </div>
            )}
          </div>
        )}

        {/* Rejected state */}
        {isRejected && (
          <div className="bg-surface rounded-xl border border-border p-6">
            <div className="flex items-center gap-3 mb-3">
              <XCircle className="w-6 h-6 text-red-500" />
              <div>
                <p className="text-text-primary font-semibold">{t('review.rejected')}</p>
                {translation.approved_by_name && (
                  <p className="text-sm text-text-secondary">
                    {t('review.reviewedBy')} <strong>{translation.approved_by_name}</strong>
                  </p>
                )}
              </div>
            </div>
            {translation.feedback && (
              <div className="bg-red-50 border border-red-200 rounded-lg p-3 mt-3">
                <p className="text-xs font-medium text-red-700 mb-1">{t('review.feedback')}</p>
                <p className="text-sm text-red-800 whitespace-pre-wrap">{translation.feedback}</p>
              </div>
            )}
          </div>
        )}

        {/* Other statuses (revision_requested, draft) */}
        {!isPendingReview && !isApproved && !isRejected && (
          <div className="bg-surface rounded-xl border border-border p-6">
            <div className="text-center py-4">
              <AlertCircle className="w-10 h-10 text-amber-500 mx-auto mb-2" />
              <p className="text-text-primary font-medium">
                {t('review.statusLabel')}: <span className="font-semibold capitalize">{translation.status.replace('_', ' ')}</span>
              </p>
              {translation.approved_by_name && (
                <p className="text-sm text-text-secondary mt-1">
                  {t('review.reviewedBy')} <strong>{translation.approved_by_name}</strong>
                </p>
              )}
            </div>
          </div>
        )}
      </div>

      {/* Reject confirmation modal */}
      <Modal
        isOpen={pendingAction === 'reject'}
        onClose={() => setPendingAction(null)}
        title={t('review.confirmReject')}
        isConfirm
        danger
        onConfirm={() => handleAction('reject')}
        confirmText={t('review.reject')}
        confirmDisabled={!feedback.trim() || !reviewerName.trim()}
      >
        <p className="text-sm text-text-secondary mb-3">{t('review.rejectConfirmDesc')}</p>
        {!feedback.trim() && (
          <p className="text-sm text-amber-600">{t('review.feedbackRequiredForReject')}</p>
        )}
      </Modal>
    </div>
  )
}
