import React, { useState, useCallback, useEffect } from 'react'
import { useScale } from '../../context/ScaleContext'

export interface Note {
  id: number
  text: string
}

interface NotesProps {
  /** Callback to get notes. If not provided, uses localStorage. */
  onGetNotes?: () => Note[] | Promise<Note[]>
  /** Callback to save notes. If not provided, uses localStorage. */
  onSaveNotes?: (notes: Note[]) => void | Promise<void>
  /** Storage key for localStorage (default: 'mc-inv-notes') */
  storageKey?: string
  className?: string
  style?: React.CSSProperties
}

const DEFAULT_STORAGE_KEY = 'mc-inv-notes'

function loadNotesFromStorage(key: string): Note[] {
  try {
    const raw = localStorage.getItem(key)
    return raw ? JSON.parse(raw) : []
  } catch {
    return []
  }
}

function saveNotesToStorage(key: string, notes: Note[]) {
  try {
    localStorage.setItem(key, JSON.stringify(notes))
  } catch {}
}

export function Notes({
  onGetNotes,
  onSaveNotes,
  storageKey = DEFAULT_STORAGE_KEY,
  className,
  style,
}: NotesProps) {
  const { scale } = useScale()
  const [notes, setNotes] = useState<Note[]>([])
  const [draft, setDraft] = useState('')
  const [loading, setLoading] = useState(true)
  const [showInput, setShowInput] = useState(false)

  // Load notes on mount
  useEffect(() => {
    let cancelled = false
    setLoading(true)

    const loadNotes = async () => {
      if (onGetNotes) {
        try {
          const loaded = await onGetNotes()
          if (!cancelled) {
            setNotes(loaded)
            setLoading(false)
          }
        } catch (err) {
          console.error('Failed to load notes:', err)
          if (!cancelled) {
            setNotes([])
            setLoading(false)
          }
        }
      } else {
        // Use localStorage
        const loaded = loadNotesFromStorage(storageKey)
        if (!cancelled) {
          setNotes(loaded)
          setLoading(false)
        }
      }
    }

    loadNotes()
    return () => {
      cancelled = true
    }
  }, [onGetNotes, storageKey])

  const saveNotes = useCallback(async (newNotes: Note[]) => {
    setNotes(newNotes)
    if (onSaveNotes) {
      try {
        await onSaveNotes(newNotes)
      } catch (err) {
        console.error('Failed to save notes:', err)
      }
    } else {
      // Use localStorage
      saveNotesToStorage(storageKey, newNotes)
    }
  }, [onSaveNotes, storageKey])

  const addNote = useCallback(() => {
    const text = draft.trim()
    if (!text) return
    const next = [...notes, { id: Date.now(), text }]
    saveNotes(next)
    setDraft('')
  }, [draft, notes, saveNotes])

  const handleAddButtonClick = useCallback(() => {
    if (!showInput) {
      setShowInput(true)
    } else {
      addNote()
    }
  }, [showInput, addNote])

  const removeNote = useCallback((id: number) => {
    const next = notes.filter((n) => n.id !== id)
    saveNotes(next)
  }, [notes, saveNotes])

  const fs = Math.max(9, Math.round(7 * scale))

  return (
    <div
      className={['mc-inv-root', 'mc-inv-notes', className].filter(Boolean).join(' ')}
      style={{
        width: '100%',
        height: '100%',
        fontFamily: "'Minecraftia', 'Minecraft', monospace",
        fontSize: fs,
        display: 'flex',
        flexDirection: 'column',
        minHeight: 0,
        ...style,
      }}
    >
      {/* <div style={{
        padding: `${3 * scale}px ${4 * scale}px`,
        color: '#404040',
        fontWeight: 'bold',
        flexShrink: 0,
      }}>
        Current Tasks
      </div> */}

      {/* Task list */}
      <div style={{ overflowY: 'auto', padding: `${2 * scale}px`, minHeight: 0 }}>
        {loading ? (
          <div style={{ color: '#888', fontSize: Math.round(6 * scale), textAlign: 'center', padding: `${4 * scale}px` }}>
            Loading...
          </div>
        ) : notes.length === 0 ? (
          <div style={{ color: '#888', fontSize: Math.round(6 * scale), textAlign: 'center', padding: `${4 * scale}px` }}>
            {/* No tasks yet */}
          </div>
        ) : (
          notes.map((note) => (
            <div key={note.id} style={{
              display: 'flex',
              alignItems: 'flex-start',
              gap: scale,
              marginBottom: 2 * scale,
              padding: `${2 * scale}px`,
            }}>
              <span style={{ flex: 1, color: '#d6d6d6', wordBreak: 'break-word', lineHeight: 1.3 }}>
                {note.text}
              </span>
              <button
                type="button"
                onMouseDown={(e) => e.stopPropagation()}
                onClick={(e) => {
                  e.stopPropagation()
                  removeNote(note.id)
                }}
                style={{
                  background: '#8b0000',
                  color: '#fff',
                  border: 'none',
                  cursor: 'pointer',
                  fontSize: Math.round(6 * scale),
                  padding: `0 ${2 * scale}px`,
                  fontFamily: 'inherit',
                  flexShrink: 0,
                }}
              >
                ×
              </button>
            </div>
          ))
        )}
      </div>

      {/* Add task input */}
      <div style={{
        padding: `${2 * scale}px`,
        display: 'flex',
        gap: scale,
        flexShrink: 0,
        alignItems: 'flex-end',
        width: '100%',
        boxSizing: 'border-box',
        // borderTop: `${scale}px solid #555555`,
      }}>
        {showInput && (
          <textarea
            value={draft}
            rows={2}
            autoFocus
            onMouseDown={(e) => e.stopPropagation()}
            onClick={(e) => e.stopPropagation()}
            onChange={(e) => {
              setDraft(e.target.value.replace(/[\r\n]/g, ''))
            }}
            onKeyDown={(e) => {
              if (e.code === 'Enter') { e.preventDefault(); addNote() }
              if (e.code === 'Escape') { setShowInput(false); setDraft('') }
            }}
            placeholder="Add task…"
            style={{
              flex: 1,
              minWidth: 0,
              resize: 'none',
              background: '#8b8b8b',
              border: `${scale}px solid #373737`,
              color: '#fff',
              fontSize: Math.round(6 * scale),
              padding: `${scale}px`,
              fontFamily: 'inherit',
              outline: 'none',
              lineHeight: 1.4,
              boxSizing: 'border-box',
              overflowY: 'hidden',
            }}
          />
        )}
        <div style={{ display: 'flex', flexDirection: 'column', gap: scale, flexShrink: 0 }}>
          {showInput && (
            <button
              type="button"
              onMouseDown={(e) => e.stopPropagation()}
              onClick={(e) => {
                e.stopPropagation()
                setShowInput(false)
                setDraft('')
              }}
              title="Hide"
              style={{
                background: '#5a3a3a',
                color: '#ccc',
                border: `${scale}px solid #666`,
                cursor: 'pointer',
                fontSize: Math.round(6 * scale),
                padding: `${scale}px ${2 * scale}px`,
                fontFamily: 'inherit',
                lineHeight: 1,
              }}
            >
              ×
            </button>
          )}
          <button
            type="button"
            onMouseDown={(e) => e.stopPropagation()}
            onClick={(e) => {
              e.stopPropagation()
              handleAddButtonClick()
            }}
            disabled={showInput && !draft.trim()}
            style={{
              background: '#404040',
              color: '#fff',
              border: `${scale}px solid #666`,
              cursor: showInput && !draft.trim() ? 'not-allowed' : 'pointer',
              fontSize: Math.round(6 * scale),
              padding: `${scale}px ${2 * scale}px`,
              fontFamily: 'inherit',
              opacity: showInput && !draft.trim() ? 0.5 : 1,
            }}
          >
            +
          </button>
        </div>
      </div>
    </div>
  )
}
