import { useState } from 'react'
import { Button, Card } from '@/components/ui'
import { SponsoringForm } from '@/components/SponsoringForm'
import { t } from '@/lib/i18n'
import type { AuthorPresentationArticle } from '@/types/nostr'

type SponsoringSummaryProps = {
  totalSponsoring: number
  author: AuthorPresentationArticle | null
  onSponsor: () => void
}

export function SponsoringSummary({ totalSponsoring, author, onSponsor }: SponsoringSummaryProps): React.ReactElement {
  const totalBTC = totalSponsoring / 100_000_000
  const [showForm, setShowForm] = useState(false)

  return (
    <Card variant="default" className="bg-cyber-dark/50 mb-8">
      <SponsoringSummaryHeader showSponsorButton={author !== null} onSponsorClick={() => setShowForm(true)} />
      <SponsoringTotals totalBTC={totalBTC} totalSats={totalSponsoring} />
      <SponsoringFormPanel show={showForm} author={author} onClose={() => setShowForm(false)} onSponsor={onSponsor} />
    </Card>
  )
}

function SponsoringSummaryHeader(params: { showSponsorButton: boolean; onSponsorClick: () => void }): React.ReactElement {
  return (
    <div className="flex items-center justify-between mb-4">
      <h2 className="text-xl font-semibold text-neon-cyan">{t('author.sponsoring')}</h2>
      {params.showSponsorButton && (
        <Button
          variant="success"
          onClick={params.onSponsorClick}
        >
          {t('sponsoring.form.submit')}
        </Button>
      )}
    </div>
  )
}

function SponsoringTotals(params: { totalBTC: number; totalSats: number }): React.ReactElement {
  return (
    <div className="space-y-2">
      <p className="text-cyber-accent">{t('author.sponsoring.total', { amount: params.totalBTC.toFixed(6) })}</p>
      <p className="text-cyber-accent">{t('author.sponsoring.sats', { amount: params.totalSats.toLocaleString() })}</p>
    </div>
  )
}

function SponsoringFormPanel(params: {
  show: boolean
  author: AuthorPresentationArticle | null
  onClose: () => void
  onSponsor: () => void
}): React.ReactElement | null {
  if (!params.show || !params.author) {
    return null
  }
  return (
    <div className="mt-4">
      <SponsoringForm
        author={params.author}
        onSuccess={() => {
          params.onClose()
          params.onSponsor()
        }}
        onCancel={params.onClose}
      />
    </div>
  )
}
