'use client'
import React, { useState } from 'react'
import type { CurriculumWeek } from '@/types'
import { pb } from '@/lib/pocketbase'
import { Button } from '@/components/ui/Button'

interface CurriculumWeekRowProps {
  week: CurriculumWeek
  isDragging: boolean
  onDragStart: (e: React.DragEvent<HTMLDivElement>) => void
  onDragOver: (e: React.DragEvent<HTMLDivElement>) => void
  onDrop: (e: React.DragEvent<HTMLDivElement>) => void
  onDragEnd: () => void
  onUpdate: () => void
}

export function CurriculumWeekRow({
  week,
  isDragging,
  onDragStart,
  onDragOver,
  onDrop,
  onDragEnd,
  onUpdate,
}: CurriculumWeekRowProps) {
  const [editingNotes, setEditingNotes] = useState(false)
  const [notes, setNotes] = useState(week.admin_notes)
  const [saving, setSaving] = useState(false)

  async function saveNotes() {
    setSaving(true)
    try {
      await pb.collection('curriculum_weeks').update(week.id, { admin_notes: notes })
      setEditingNotes(false)
      onUpdate()
    } catch {
      // ignore save error
    } finally {
      setSaving(false)
    }
  }

  const themeName =
    (week.expand?.theme?.title) ?? '—'
  const topicCount = week.topics.length

  return (
    <div
      draggable
      onDragStart={onDragStart}
      onDragOver={onDragOver}
      onDrop={onDrop}
      onDragEnd={onDragEnd}
      style={{
        background: 'var(--bg)',
        border: `1.5px solid ${isDragging ? 'var(--accent)' : 'var(--cream)'}`,
        borderRadius: 'var(--r-md)',
        padding: 'var(--s-4)',
        cursor: 'grab',
        opacity: isDragging ? 0.5 : 1,
        transition: 'opacity 150ms, border-color 150ms',
        display: 'flex',
        flexDirection: 'column',
        gap: 'var(--s-3)',
        userSelect: 'none',
      }}
    >
      <div style={{ display: 'flex', alignItems: 'center', gap: 'var(--s-3)' }}>
        {/* Drag handle */}
        <div
          style={{
            color: 'var(--fg-subtle)',
            fontSize: '18px',
            flexShrink: 0,
            cursor: 'grab',
          }}
          aria-hidden="true"
        >
          ⠿
        </div>

        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 'var(--s-2)' }}>
            <span
              style={{
                fontSize: 'var(--t-label)',
                fontFamily: 'var(--font-mono)',
                textTransform: 'uppercase',
                letterSpacing: 'var(--label-ls)',
                color: 'var(--fg-muted)',
              }}
            >
              Week {week.week_number}
            </span>
            <span
              style={{
                fontSize: 'var(--t-label)',
                fontFamily: 'var(--font-mono)',
                color: 'var(--fg-subtle)',
              }}
            >
              {week.estimated_duration_minutes}min · {topicCount} topic{topicCount !== 1 ? 's' : ''}
            </span>
          </div>
          <p
            style={{
              margin: 0,
              fontWeight: 600,
              fontSize: 'var(--t-body)',
              color: 'var(--fg)',
              overflow: 'hidden',
              textOverflow: 'ellipsis',
              whiteSpace: 'nowrap',
            }}
          >
            {themeName}
          </p>
        </div>
      </div>

      {editingNotes ? (
        <div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--s-2)' }}>
          <textarea
            value={notes}
            onChange={(e) => setNotes(e.target.value)}
            rows={2}
            style={{
              width: '100%',
              borderRadius: 'var(--r-sm)',
              border: '1.5px solid var(--accent)',
              padding: 'var(--s-2) var(--s-3)',
              fontSize: 'var(--t-small)',
              fontFamily: 'var(--font-sans)',
              color: 'var(--fg)',
              background: 'var(--bg)',
              resize: 'vertical',
              outline: 'none',
            }}
            autoFocus
          />
          <div style={{ display: 'flex', gap: 'var(--s-2)', justifyContent: 'flex-end' }}>
            <Button size="sm" variant="secondary" onClick={() => setEditingNotes(false)}>
              Cancel
            </Button>
            <Button size="sm" variant="primary" loading={saving} onClick={() => void saveNotes()}>
              Save
            </Button>
          </div>
        </div>
      ) : (
        <button
          onClick={() => setEditingNotes(true)}
          style={{
            background: 'none',
            border: 'none',
            padding: 0,
            cursor: 'text',
            textAlign: 'left',
            fontFamily: 'var(--font-sans)',
            fontSize: 'var(--t-small)',
            color: week.admin_notes ? 'var(--fg-muted)' : 'var(--fg-subtle)',
            fontStyle: week.admin_notes ? 'normal' : 'italic',
            minHeight: '24px',
          }}
        >
          {week.admin_notes || 'Add admin notes…'}
        </button>
      )}
    </div>
  )
}
