'use client'

import { useEffect, useState } from 'react'
import type { NotebookSchemaPayload, NotePropertyValues } from '@/lib/structured-views/types'
import { NotePropertiesSection } from './note-properties-section'
import { AddPropertyDialog } from './add-property-dialog'

type NoteEditorPropertiesPanelProps = {
  noteId: string
  notebookId: string | null | undefined
  readOnly?: boolean
}

export function NoteEditorPropertiesPanel({
  noteId,
  notebookId,
  readOnly,
}: NoteEditorPropertiesPanelProps) {
  const [schema, setSchema] = useState<NotebookSchemaPayload | null>(null)
  const [values, setValues] = useState<NotePropertyValues>({})
  const [addOpen, setAddOpen] = useState(false)

  useEffect(() => {
    if (!notebookId) {
      setSchema(null)
      setValues({})
      return
    }
    let cancelled = false
    ;(async () => {
      try {
        const [schemaRes, valuesRes] = await Promise.all([
          fetch(`/api/notebooks/${notebookId}/schema`),
          fetch(`/api/notes/${noteId}/properties`),
        ])
        const schemaJson = await schemaRes.json()
        const valuesJson = await valuesRes.json()
        if (cancelled) return
        setSchema(schemaJson.success ? schemaJson.data.schema : null)
        setValues(valuesJson.success ? valuesJson.data.values ?? {} : {})
      } catch {
        if (!cancelled) {
          setSchema(null)
          setValues({})
        }
      }
    })()
    return () => {
      cancelled = true
    }
  }, [notebookId, noteId])

  if (!notebookId || !schema) return null

  const handleAddProperty = async (name: string, type: string, options?: string[]) => {
    const res = await fetch(`/api/notebooks/${notebookId}/schema`, {
      method: 'PATCH',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ action: 'addProperty', name, type, options }),
    })
    const json = await res.json()
    if (json.success) setSchema(json.data.schema)
  }

  return (
    <>
      <NotePropertiesSection
        noteId={noteId}
        schema={schema}
        initialValues={values}
        readOnly={readOnly}
        onAddProperty={() => setAddOpen(true)}
        onValuesChange={setValues}
      />
      <AddPropertyDialog
        open={addOpen}
        onClose={() => setAddOpen(false)}
        onSubmit={handleAddProperty}
      />
    </>
  )
}
