import { useState } from 'react'
import Link from 'next/link'
import { Button } from './ui'
import { SeriesSection } from './SeriesSection'
import { CreateSeriesModal } from './CreateSeriesModal'
import { useNostrAuth } from '@/hooks/useNostrAuth'
import { t } from '@/lib/i18n'

interface ProfileSeriesBlockProps {
  currentPubkey: string
  onSelectSeries: (seriesId: string | undefined) => void
  selectedSeriesId?: string | undefined
}

export function ProfileSeriesBlock({ currentPubkey, onSelectSeries, selectedSeriesId }: ProfileSeriesBlockProps): React.ReactElement {
  const { pubkey, isUnlocked } = useNostrAuth()
  const [showCreateModal, setShowCreateModal] = useState(false)
  const [refreshKey, setRefreshKey] = useState(0)
  const isAuthor = pubkey !== null && pubkey === currentPubkey && isUnlocked

  const handleSeriesCreated = (): void => {
    setRefreshKey((prev) => prev + 1)
  }

  return (
    <div className="mb-6">
      <ProfileSeriesHeader isAuthor={isAuthor} onCreate={() => setShowCreateModal(true)} />
      <SeriesSection
        authorPubkey={currentPubkey}
        onSelect={onSelectSeries}
        refreshKey={refreshKey}
        {...(selectedSeriesId ? { selectedId: selectedSeriesId } : {})}
      />
      {selectedSeriesId && (
        <div className="mt-2 text-sm text-blue-600">
          <Link href={`/series/${selectedSeriesId}`} className="underline">
            Ouvrir la page de la série sélectionnée
          </Link>
        </div>
      )}
      <CreateSeriesModal
        isOpen={showCreateModal}
        onClose={() => {
          setShowCreateModal(false)
        }}
        onSuccess={handleSeriesCreated}
        authorPubkey={currentPubkey}
      />
    </div>
  )
}

function ProfileSeriesHeader({ isAuthor, onCreate }: { isAuthor: boolean; onCreate: () => void }): React.ReactElement {
  return (
    <div className="flex items-center justify-between mb-2">
      <h3 className="text-lg font-semibold">Séries</h3>
      {isAuthor && (
        <Button
          type="button"
          variant="primary"
          onClick={onCreate}
        >
          {t('series.create.button')}
        </Button>
      )}
    </div>
  )
}
