import { useState } from 'react'
import Link from 'next/link'
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 === 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"
          onClick={onCreate}
          className="px-4 py-2 bg-neon-cyan/20 hover:bg-neon-cyan/30 text-neon-cyan rounded-lg font-medium transition-all border border-neon-cyan/50 hover:shadow-glow-cyan"
        >
          {t('series.create.button')}
        </button>
      )}
    </div>
  )
}
