'use client'

import { useState, useTransition } from 'react'
import { useRouter } from 'next/navigation'
import { Button, Card, Label } from '@/components/ui'
import { addTopicAction, deleteTopicAction, toggleTopicAction } from '@/app/actions'

export function AddTopic({ constructs }: { constructs: { code: string; label: string }[] }) {
  const [pending, start] = useTransition()
  const [error, setError] = useState<string | null>(null)
  const router = useRouter()

  return (
    <Card>
      <form
        action={(fd) =>
          start(async () => {
            const r = await addTopicAction(fd)
            if (r?.error) setError(r.error)
            else {
              setError(null)
              router.refresh()
            }
          })
        }
        className="space-y-3"
      >
        <Label>Add a topic</Label>
        <div className="grid gap-2 sm:grid-cols-[1fr_2fr]">
          <select
            name="constructCode"
            required
            className="rounded-lg border border-[var(--color-line)] bg-white px-3 py-2 text-sm"
          >
            {constructs.map((c) => (
              <option key={c.code} value={c.code}>
                {c.label}
              </option>
            ))}
          </select>
          <input
            name="label"
            required
            placeholder="Lesson Book Level 1: Salvation"
            className="rounded-lg border border-[var(--color-line)] bg-white px-3 py-2 text-sm"
          />
        </div>
        <textarea
          name="notes"
          rows={2}
          placeholder="Optional — what you want them to come away with"
          className="w-full rounded-lg border border-[var(--color-line)] bg-white px-3 py-2 text-sm"
        />
        {error && <p className="text-xs text-[#9b3232]">{error}</p>}
        <Button type="submit" disabled={pending}>
          {pending ? 'Adding…' : 'Add'}
        </Button>
      </form>
    </Card>
  )
}

interface TopicView {
  id: string
  label: string
  notes: string | null
  active: boolean
  constructLabel: string
  lastCovered: string | null
}

export function TopicList({ topics }: { topics: TopicView[] }) {
  const [pending, start] = useTransition()
  const router = useRouter()

  return (
    <div className="space-y-2">
      {topics.map((t) => (
        <Card key={t.id} className={t.active ? '' : 'opacity-55'}>
          <div className="flex flex-wrap items-start justify-between gap-2">
            <div className="min-w-0">
              <p className="text-sm font-medium">{t.label}</p>
              <p className="text-xs text-[var(--color-muted)]">
                {t.constructLabel}
                {t.lastCovered ? ` · last covered ${t.lastCovered}` : ' · not yet covered'}
                {!t.active && ' · paused'}
              </p>
              {t.notes && (
                <p className="mt-1 text-xs leading-relaxed text-[var(--color-muted)]">{t.notes}</p>
              )}
            </div>
            <div className="flex shrink-0 gap-3 text-xs">
              <button
                disabled={pending}
                onClick={() =>
                  start(async () => {
                    await toggleTopicAction(t.id)
                    router.refresh()
                  })
                }
                className="text-[var(--color-muted)] hover:text-[var(--color-ink)]"
              >
                {t.active ? 'Pause' : 'Resume'}
              </button>
              <button
                disabled={pending}
                onClick={() =>
                  start(async () => {
                    await deleteTopicAction(t.id)
                    router.refresh()
                  })
                }
                className="text-[#9b3232] hover:underline"
              >
                Remove
              </button>
            </div>
          </div>
        </Card>
      ))}
    </div>
  )
}
