import { useState, useCallback } from 'react'
import { useNostrConnect } from '@/hooks/useNostrConnect'
import { useAuthorPresentation } from '@/hooks/useAuthorPresentation'
import { ArticleField } from './ArticleField'
import { ArticleFormButtons } from './ArticleFormButtons'
import { ConnectButton } from './ConnectButton'
import { t } from '@/lib/i18n'

interface AuthorPresentationDraft {
  presentation: string
  contentDescription: string
  mainnetAddress: string
}

const ADDRESS_PATTERN = /^(1|3|bc1)[a-zA-Z0-9]{25,62}$/

function NotConnected() {
  return (
    <div className="border border-neon-cyan/20 rounded-lg p-6 bg-cyber-dark/50">
      <div className="flex flex-col items-center gap-4">
        <p className="text-center text-cyber-accent">
          {t('presentation.notConnected')}
        </p>
        <ConnectButton />
      </div>
    </div>
  )
}

function SuccessNotice() {
  return (
    <div className="border border-neon-green/50 rounded-lg p-6 bg-neon-green/10">
      <h3 className="text-lg font-semibold text-neon-green mb-2">{t('presentation.success')}</h3>
      <p className="text-cyber-accent">
        {t('presentation.successMessage')}
      </p>
    </div>
  )
}

function ValidationError({ message }: { message: string | null }) {
  if (!message) {
    return null
  }
  return (
    <div className="bg-red-500/10 border border-red-500/50 rounded-lg p-3">
      <p className="text-sm text-red-400">{message}</p>
    </div>
  )
}

function PresentationField({
  draft,
  onChange,
}: {
  draft: AuthorPresentationDraft
  onChange: (next: AuthorPresentationDraft) => void
}) {
  return (
    <ArticleField
      id="presentation"
      label="Présentation personnelle"
      value={draft.presentation}
      onChange={(value) => onChange({ ...draft, presentation: value as string })}
      required
      type="textarea"
      rows={6}
      placeholder="Présentez-vous : qui êtes-vous, votre parcours, vos intérêts..."
      helpText="Cette présentation sera visible par tous les lecteurs"
    />
  )
}

function ContentDescriptionField({
  draft,
  onChange,
}: {
  draft: AuthorPresentationDraft
  onChange: (next: AuthorPresentationDraft) => void
}) {
  return (
    <ArticleField
      id="contentDescription"
      label="Description de votre contenu"
      value={draft.contentDescription}
      onChange={(value) => onChange({ ...draft, contentDescription: value as string })}
      required
      type="textarea"
      rows={6}
      placeholder="Décrivez le type de contenu que vous publiez : science-fiction, recherche scientifique, thèmes abordés..."
      helpText="Aidez les lecteurs à comprendre le type d'articles que vous publiez"
    />
  )
}

function MainnetAddressField({
  draft,
  onChange,
}: {
  draft: AuthorPresentationDraft
  onChange: (next: AuthorPresentationDraft) => void
}) {
  return (
    <ArticleField
      id="mainnetAddress"
      label="Adresse Bitcoin mainnet (pour le sponsoring)"
      value={draft.mainnetAddress}
      onChange={(value) => onChange({ ...draft, mainnetAddress: value as string })}
      required
      type="text"
      placeholder="1A1zP1eP5QGefi2DMPTfTL5SLmv7DivfNa"
      helpText="Adresse Bitcoin mainnet où vous recevrez les paiements de sponsoring (0.046 BTC par sponsoring)"
    />
  )
}

const PresentationFields = ({
  draft,
  onChange,
}: {
  draft: AuthorPresentationDraft
  onChange: (next: AuthorPresentationDraft) => void
}) => (
  <div className="space-y-4">
    <PresentationField draft={draft} onChange={onChange} />
    <ContentDescriptionField draft={draft} onChange={onChange} />
    <MainnetAddressField draft={draft} onChange={onChange} />
  </div>
)

function PresentationForm({
  draft,
  setDraft,
  validationError,
  error,
  loading,
  handleSubmit,
  userName,
}: {
  draft: AuthorPresentationDraft
  setDraft: (next: AuthorPresentationDraft) => void
  validationError: string | null
  error: string | null
  loading: boolean
  handleSubmit: (e: React.FormEvent) => Promise<void>
  userName: string
}) {
  return (
    <form
      onSubmit={(e) => {
        void handleSubmit(e)
      }}
      className="border border-neon-cyan/20 rounded-lg p-6 bg-cyber-dark space-y-4"
    >
      <div className="mb-6">
        <h2 className="text-2xl font-bold mb-2 text-neon-cyan font-mono">
          {t('presentation.title')} - {userName}
        </h2>
        <p className="text-cyber-accent text-sm">
          {t('presentation.description')}
        </p>
      </div>

      <PresentationFields draft={draft} onChange={setDraft} />
      <ValidationError message={validationError ?? error} />
      <ArticleFormButtons loading={loading} />
    </form>
  )
}

function useAuthorPresentationState(pubkey: string | null) {
  const { loading, error, success, publishPresentation } = useAuthorPresentation(pubkey)
  const [draft, setDraft] = useState<AuthorPresentationDraft>({
    presentation: '',
    contentDescription: '',
    mainnetAddress: '',
  })
  const [validationError, setValidationError] = useState<string | null>(null)

  const handleSubmit = useCallback(
    async (e: React.FormEvent) => {
      e.preventDefault()
      const address = draft.mainnetAddress.trim()
      if (!ADDRESS_PATTERN.test(address)) {
        setValidationError('Adresse Bitcoin invalide (doit commencer par 1, 3 ou bc1)')
        return
      }
      setValidationError(null)
      await publishPresentation(draft)
    },
    [draft, publishPresentation]
  )

  return { loading, error, success, draft, setDraft, validationError, handleSubmit }
}

function AuthorPresentationFormView({
  pubkey,
  connected,
  profile,
}: {
  pubkey: string | null
  connected: boolean
  profile: { name?: string; pubkey: string } | null
}) {
  const state = useAuthorPresentationState(pubkey)

  if (!connected || !pubkey) {
    return <NotConnected />
  }
  if (state.success) {
    return <SuccessNotice />
  }

  // Get user name or fallback to shortened pubkey
  const userName = profile?.name ?? (pubkey ? `${pubkey.substring(0, 16)}...` : 'Utilisateur')

  return (
    <PresentationForm
      draft={state.draft}
      setDraft={state.setDraft}
      validationError={state.validationError}
      error={state.error}
      loading={state.loading}
      handleSubmit={state.handleSubmit}
      userName={userName}
    />
  )
}

export function AuthorPresentationEditor() {
  const { connected, pubkey, profile } = useNostrConnect()
  return <AuthorPresentationFormView pubkey={pubkey ?? null} connected={connected} profile={profile} />
}
