import { useState } from 'react'
import { nostrService } from '@/lib/nostr'
import { useNostrAuth } from '@/hooks/useNostrAuth'
import { t } from '@/lib/i18n'
import { buildReviewTipZapRequestTags } from '@/lib/zapRequestBuilder'
import { calculateReviewSplit } from '@/lib/platformCommissions'
import type { Review } from '@/types/nostr'
import type { Article } from '@/types/nostr'

interface ReviewTipFormProps {
  review: Review
  article: Article
  onSuccess?: () => void
  onCancel?: () => void
}

export function ReviewTipForm({ review, article, onSuccess, onCancel }: ReviewTipFormProps): React.ReactElement {
  const { pubkey, connect } = useNostrAuth()
  const [text, setText] = useState('')
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState<string | null>(null)

  const handleSubmit = async (e: React.FormEvent): Promise<void> => {
    e.preventDefault()
    if (!pubkey) {
      await connect()
      return
    }

    setLoading(true)
    setError(null)

    try {
      const privateKey = nostrService.getPrivateKey()
      if (!privateKey) {
        setError(t('reviewTip.form.error.noPrivateKey'))
        return
      }

      const split = calculateReviewSplit()

      // Build zap request tags
      const category = article.category === 'author-presentation' ? undefined : (article.category === 'science-fiction' || article.category === 'scientific-research' ? article.category : undefined)
      const zapRequestTags = buildReviewTipZapRequestTags({
        articleId: article.id,
        reviewId: review.id,
        authorPubkey: article.pubkey,
        reviewerPubkey: review.reviewerPubkey,
        ...(category ? { category } : {}),
        ...(article.seriesId ? { seriesId: article.seriesId } : {}),
        ...(text.trim() ? { text: text.trim() } : {}),
      })

      // Create zap request event (kind 9734) and publish it
      // This zap request will be used by Alby to create the zap payment
      await nostrService.createZapRequest(review.reviewerPubkey, review.id, split.total, zapRequestTags)

      // Note: The actual zap payment is handled by Alby/WebLN when the user confirms
      // The zap request event (kind 9734) contains all the necessary information
      // Alby will use this to create the zap receipt (kind 9735) after payment
      // The user needs to complete the zap payment via Alby after this zap request is published

      setText('')
      onSuccess?.()
    } catch (submitError) {
      setError(submitError instanceof Error ? submitError.message : t('reviewTip.form.error.paymentFailed'))
    } finally {
      setLoading(false)
    }
  }

  if (!pubkey) {
    return (
      <div className="border border-neon-cyan/30 rounded-lg p-4 bg-cyber-dark">
        <p className="text-cyber-accent mb-4">{t('reviewTip.form.connectRequired')}</p>
        <button
          onClick={() => {
            void connect()
          }}
          className="px-4 py-2 bg-neon-green/20 hover:bg-neon-green/30 text-neon-green rounded-lg font-medium transition-all border border-neon-green/50"
        >
          {t('connect.connect')}
        </button>
      </div>
    )
  }

  const split = calculateReviewSplit()

  return (
    <form onSubmit={(e) => {
      void handleSubmit(e)
    }} className="border border-neon-cyan/30 rounded-lg p-4 bg-cyber-dark space-y-4">
      <h3 className="text-lg font-semibold text-neon-cyan">{t('reviewTip.form.title')}</h3>
      <p className="text-sm text-cyber-accent/70">
        {t('reviewTip.form.description', { amount: split.total, reviewer: split.reviewer, platform: split.platform })}
      </p>

      <div>
        <label htmlFor="review-tip-text" className="block text-sm font-medium text-cyber-accent mb-1">
          {t('reviewTip.form.text.label')} <span className="text-cyber-accent/50">({t('common.optional')})</span>
        </label>
        <textarea
          id="review-tip-text"
          value={text}
          onChange={(e) => {
            setText(e.target.value)
          }}
          placeholder={t('reviewTip.form.text.placeholder')}
          rows={3}
          className="w-full px-3 py-2 bg-cyber-darker border border-neon-cyan/30 rounded text-cyber-accent focus:border-neon-cyan focus:outline-none"
        />
        <p className="text-xs text-cyber-accent/70 mt-1">{t('reviewTip.form.text.help')}</p>
      </div>

      {error && (
        <div className="p-3 bg-red-900/20 border border-red-500/50 rounded text-red-400 text-sm">
          {error}
        </div>
      )}

      <div className="flex gap-2">
        <button
          type="submit"
          disabled={loading}
          className="px-4 py-2 bg-neon-green/20 hover:bg-neon-green/30 text-neon-green rounded-lg font-medium transition-all border border-neon-green/50 hover:shadow-glow-green disabled:opacity-50"
        >
          {loading ? t('common.loading') : t('reviewTip.form.submit', { amount: split.total })}
        </button>
        {onCancel && (
          <button
            type="button"
            onClick={onCancel}
            className="px-4 py-2 bg-cyber-darker hover:bg-cyber-dark text-cyber-accent rounded-lg font-medium transition-all border border-neon-cyan/30"
          >
            {t('common.cancel')}
          </button>
        )}
      </div>
    </form>
  )
}
