'use client'
import React, { useState, useEffect } from 'react'
import { pb } from '@/lib/pocketbase'
import { CurriculumWeekRow } from '@/components/admin/CurriculumWeekRow'
import { Button } from '@/components/ui/Button'
import { StatusBadge } from '@/components/ui/StatusBadge'
import { postCurriculumConfirm, patchCurriculumWeekOrder } from '@/lib/services'
import type { CurriculumVersion, CurriculumWeek } from '@/types'

export default function CurriculumPage() {
  const [versions, setVersions] = useState<CurriculumVersion[]>([])
  const [weeks, setWeeks] = useState<CurriculumWeek[]>([])
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)
  const [confirming, setConfirming] = useState(false)

  // Drag state
  const [dragIndex, setDragIndex] = useState<number | null>(null)
  const [dragOverIndex, setDragOverIndex] = useState<number | null>(null)

  async function load() {
    setLoading(true)
    try {
      const [vList, wList] = await Promise.all([
        pb.collection('curriculum_versions').getFullList<CurriculumVersion>({
          sort: '-version',
        }),
        pb.collection('curriculum_weeks').getFullList<CurriculumWeek>({
          sort: 'week_number',
          expand: 'theme',
        }),
      ])
      setVersions(vList)
      setWeeks(wList)
      setError(null)
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Failed to load')
    } finally {
      setLoading(false)
    }
  }

  useEffect(() => {
    void load()
  }, [])

  const activeVersion = versions.find((v) => v.status === 'active')
  const draftVersion = versions.find((v) => v.status === 'draft')

  function handleDragStart(e: React.DragEvent<HTMLDivElement>, idx: number) {
    setDragIndex(idx)
    e.dataTransfer.effectAllowed = 'move'
  }

  function handleDragOver(e: React.DragEvent<HTMLDivElement>, idx: number) {
    e.preventDefault()
    setDragOverIndex(idx)
  }

  function handleDrop(e: React.DragEvent<HTMLDivElement>, dropIdx: number) {
    e.preventDefault()
    if (dragIndex === null || dragIndex === dropIdx) {
      setDragIndex(null)
      setDragOverIndex(null)
      return
    }

    const newWeeks = [...weeks]
    const [moved] = newWeeks.splice(dragIndex, 1)
    newWeeks.splice(dropIdx, 0, moved)
    setWeeks(newWeeks)
    setDragIndex(null)
    setDragOverIndex(null)

    // Persist order
    if (moved) {
      void patchCurriculumWeekOrder(moved.id, dropIdx + 1).catch(() => {
        // revert on error
        void load()
      })
    }
  }

  function handleDragEnd() {
    setDragIndex(null)
    setDragOverIndex(null)
  }

  async function handleConfirm(versionId: string) {
    setConfirming(true)
    try {
      await postCurriculumConfirm(versionId)
      void load()
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Failed to confirm')
    } finally {
      setConfirming(false)
    }
  }

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--s-6)' }}>
      <div>
        <h1
          style={{
            margin: '0 0 var(--s-2)',
            fontSize: 'var(--t-h3)',
            fontWeight: 700,
            color: 'var(--fg)',
          }}
        >
          Curriculum
        </h1>
        <p style={{ margin: 0, fontSize: 'var(--t-body)', color: 'var(--fg-muted)' }}>
          26-week learning schedule. Drag to reorder weeks.
        </p>
      </div>

      {/* Version info */}
      {versions.length > 0 && (
        <div
          style={{
            display: 'flex',
            gap: 'var(--s-3)',
            flexWrap: 'wrap',
            alignItems: 'center',
            padding: 'var(--s-4)',
            background: 'var(--bg-warm)',
            borderRadius: 'var(--r-md)',
          }}
        >
          <div style={{ flex: 1 }}>
            {activeVersion && (
              <span style={{ fontSize: 'var(--t-body)', color: 'var(--fg)' }}>
                Active: <strong>v{activeVersion.version}</strong>{' '}
                <StatusBadge status="active" />
              </span>
            )}
            {draftVersion && (
              <span style={{ fontSize: 'var(--t-body)', color: 'var(--fg)', marginLeft: 'var(--s-4)' }}>
                Draft: <strong>v{draftVersion.version}</strong>{' '}
                <StatusBadge status="draft" />
                {' '}
                <em style={{ fontSize: 'var(--t-small)', color: 'var(--fg-muted)' }}>
                  {draftVersion.generation_notes}
                </em>
              </span>
            )}
          </div>
          {draftVersion && (
            <Button
              variant="primary"
              size="sm"
              loading={confirming}
              onClick={() => void handleConfirm(draftVersion.id)}
            >
              Activate draft v{draftVersion.version}
            </Button>
          )}
        </div>
      )}

      {error && (
        <div
          style={{
            background: '#f8d7da',
            color: '#c0392b',
            borderRadius: 'var(--r-sm)',
            padding: 'var(--s-3) var(--s-4)',
            fontSize: 'var(--t-small)',
          }}
        >
          {error}
        </div>
      )}

      {loading ? (
        <div style={{ color: 'var(--fg-muted)', fontSize: 'var(--t-body)' }}>Loading…</div>
      ) : weeks.length === 0 ? (
        <div style={{ color: 'var(--fg-muted)', fontSize: 'var(--t-body)', textAlign: 'center', padding: 'var(--s-6)' }}>
          No curriculum weeks yet. Generate a curriculum from the knowledge base first.
        </div>
      ) : (
        <div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--s-2)' }}>
          {weeks.map((week, idx) => (
            <CurriculumWeekRow
              key={week.id}
              week={week}
              isDragging={dragIndex === idx}
              onDragStart={(e) => handleDragStart(e, idx)}
              onDragOver={(e) => handleDragOver(e, idx)}
              onDrop={(e) => handleDrop(e, idx)}
              onDragEnd={handleDragEnd}
              onUpdate={() => void load()}
            />
          ))}
        </div>
      )}
    </div>
  )
}
