import { useState } from 'react'
import { nostrService } from '@/lib/nostr'
import { useNostrAuth } from '@/hooks/useNostrAuth'
import { t } from '@/lib/i18n'
import { sponsoringPaymentService } from '@/lib/sponsoringPayment'
import type { AuthorPresentationArticle } from '@/types/nostr'

interface SponsoringFormProps {
  author: AuthorPresentationArticle
  onSuccess?: () => void
  onCancel?: () => void
}

export function SponsoringForm({ author, onSuccess, onCancel }: SponsoringFormProps): 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
    }

    if (!author.mainnetAddress) {
      setError(t('sponsoring.form.error.noAddress'))
      return
    }

    setLoading(true)
    setError(null)

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

      // Create sponsoring payment request
      const result = await sponsoringPaymentService.createSponsoringPayment({
        authorPubkey: author.pubkey,
        authorMainnetAddress: author.mainnetAddress,
        amount: 0.046, // Fixed amount for sponsoring
      })

      if (!result.success) {
        setError(result.error ?? t('sponsoring.form.error.paymentFailed'))
        return
      }

      // Note: Sponsoring is done via Bitcoin mainnet, not Lightning zap
      // The user needs to create a Bitcoin transaction with two outputs:
      // 1. Author address: result.split.authorSats
      // 2. Platform address: result.split.platformSats
      // After the transaction is confirmed, we can create a zap receipt for tracking

      // Store payment info for later verification
      // The user will need to provide the transaction ID after payment
      console.log('Sponsoring payment info:', {
        authorAddress: result.authorAddress,
        platformAddress: result.platformAddress,
        authorAmount: result.split.authorSats,
        platformAmount: result.split.platformSats,
        totalAmount: result.split.totalSats,
      })

      // Show instructions to user
      alert(t('sponsoring.form.instructions', {
        authorAddress: result.authorAddress,
        platformAddress: result.platformAddress,
        authorAmount: (result.split.authorSats / 100_000_000).toFixed(8),
        platformAmount: (result.split.platformSats / 100_000_000).toFixed(8),
      }))

      setText('')
      onSuccess?.()
    } catch (submitError) {
      setError(submitError instanceof Error ? submitError.message : t('sponsoring.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('sponsoring.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>
    )
  }

  if (!author.mainnetAddress) {
    return (
      <div className="border border-neon-cyan/30 rounded-lg p-4 bg-cyber-dark">
        <p className="text-cyber-accent">{t('sponsoring.form.error.noAddress')}</p>
      </div>
    )
  }

  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('sponsoring.form.title')}</h3>
      <p className="text-sm text-cyber-accent/70">
        {t('sponsoring.form.description', { amount: '0.046' })}
      </p>

      <div>
        <label htmlFor="sponsoring-text" className="block text-sm font-medium text-cyber-accent mb-1">
          {t('sponsoring.form.text.label')} <span className="text-cyber-accent/50">({t('common.optional')})</span>
        </label>
        <textarea
          id="sponsoring-text"
          value={text}
          onChange={(e) => {
            setText(e.target.value)
          }}
          placeholder={t('sponsoring.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('sponsoring.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('sponsoring.form.submit')}
        </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>
  )
}
