import { useState } from 'react'
import type { OAuthSession } from '@atproto/oauth-client-browser'
import { createPublication, type Publication } from '~/lib/api-client'

export default function CreatePublication({
  session,
  onCreated,
  onCancel,
}: {
  session: OAuthSession
  onCreated: (pub: Publication) => void
  onCancel?: () => void
}) {
  const [name, setName] = useState('')
  const [description, setDescription] = useState('')
  const [showInDiscover, setShowInDiscover] = useState(false)
  const [pending, setPending] = useState(false)
  const [error, setError] = useState<string | null>(null)

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault()
    setPending(true)
    setError(null)
    try {
      const pub = await createPublication(session, {
        name: name.trim(),
        description: description.trim() || undefined,
        showInDiscover,
      })
      onCreated(pub)
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Failed to create publication')
      setPending(false)
    }
  }

  const inputClass =
    'w-full rounded-lg border border-stone-300 dark:border-stone-600 bg-white dark:bg-stone-800 px-4 py-3 text-sm text-stone-900 dark:text-white placeholder-stone-400 focus:outline-none focus:ring-2 focus:ring-stone-900 dark:focus:ring-stone-100 disabled:opacity-50'

  return (
    <div className="space-y-4 max-w-sm">
      <div>
        <p className="font-display text-xl font-semibold text-stone-900 dark:text-white">
          Create your publication
        </p>
        <p className="text-sm text-stone-500 dark:text-stone-400 mt-1">
          Set up your blog on the AT Protocol
        </p>
      </div>

      <form onSubmit={handleSubmit} className="space-y-3">
        <input
          type="text"
          value={name}
          onChange={(e) => setName(e.target.value)}
          placeholder="Publication name"
          disabled={pending}
          className={inputClass}
        />
        <input
          type="text"
          value={description}
          onChange={(e) => setDescription(e.target.value)}
          placeholder="Description (optional)"
          disabled={pending}
          className={inputClass}
        />

        <label className="flex items-center gap-2 text-sm text-stone-700 dark:text-stone-300 cursor-pointer">
          <input
            type="checkbox"
            checked={showInDiscover}
            onChange={(e) => setShowInDiscover(e.target.checked)}
            disabled={pending}
            className="rounded border-stone-300 dark:border-stone-600"
          />
          Discover on other platforms
        </label>

        {error && <p className="text-sm text-red-500">{error}</p>}

        <div className="flex gap-2">
          <button
            type="submit"
            disabled={pending || !name.trim()}
            className="flex-1 rounded-lg bg-stone-900 dark:bg-stone-100 hover:bg-stone-700 dark:hover:bg-stone-200 disabled:opacity-50 disabled:cursor-not-allowed px-4 py-3 text-sm font-semibold text-white dark:text-stone-900 transition-colors"
          >
            {pending ? 'Creating…' : 'Create publication'}
          </button>
          {onCancel && (
            <button
              type="button"
              onClick={onCancel}
              disabled={pending}
              className="rounded-lg border border-stone-200 dark:border-stone-700 px-4 py-3 text-sm font-medium text-stone-600 dark:text-stone-400 hover:bg-stone-50 dark:hover:bg-stone-800 transition-colors"
            >
              Cancel
            </button>
          )}
        </div>
      </form>
    </div>
  )
}
