import Link from 'next/link'
import { useState } from 'react'
import { CreateSeriesModal } from '@/components/CreateSeriesModal'
import { SeriesCard } from '@/components/SeriesCard'
import { Button } from '@/components/ui'
import { useNostrAuth } from '@/hooks/useNostrAuth'
import { t } from '@/lib/i18n'
import type { Series } from '@/types/nostr'

export function SeriesList(params: { series: Series[]; authorPubkey: string; onSeriesCreated: () => void }): React.ReactElement {
  const { pubkey, isUnlocked } = useNostrAuth()
  const [showCreateModal, setShowCreateModal] = useState(false)
  const isAuthor = pubkey === params.authorPubkey && isUnlocked

  return (
    <div className="space-y-6">
      <SeriesListHeader isAuthor={isAuthor} onCreate={() => setShowCreateModal(true)} />
      <SeriesGrid series={params.series} />
      <CreateSeriesModal
        isOpen={showCreateModal}
        onClose={() => setShowCreateModal(false)}
        onSuccess={params.onSeriesCreated}
        authorPubkey={params.authorPubkey}
      />
    </div>
  )
}

function SeriesListHeader(params: { isAuthor: boolean; onCreate: () => void }): React.ReactElement {
  return (
    <div className="flex items-center justify-between">
      <h2 className="text-2xl font-semibold text-neon-cyan">{t('series.title')}</h2>
      {params.isAuthor && (
        <Button
          type="button"
          variant="primary"
          onClick={params.onCreate}
        >
          {t('series.create.button')}
        </Button>
      )}
    </div>
  )
}

function SeriesGrid(params: { series: Series[] }): React.ReactElement {
  if (params.series.length === 0) {
    return (
      <div className="bg-cyber-dark/50 border border-neon-cyan/20 rounded-lg p-6">
        <p className="text-cyber-accent">{t('series.empty')}</p>
      </div>
    )
  }

  return (
    <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
      {params.series.map((s) => (
        <Link key={s.id} href={`/series/${s.id}`}>
          <SeriesCard series={s} onSelect={() => {}} />
        </Link>
      ))}
    </div>
  )
}
