'use client'

import { useState } from 'react'
import { useRouter } from 'next/navigation'

interface Props {
  propertyId: string
  initialNotes: string | null
  readOnly?: boolean
}

export function InternalNotesForm({ propertyId, initialNotes, readOnly = false }: Props) {
  const router = useRouter()
  const [notes, setNotes] = useState(initialNotes ?? '')
  const [saving, setSaving] = useState(false)
  const [saved, setSaved] = useState(false)
  const [error, setError] = useState('')

  async function save() {
    setSaving(true)
    setSaved(false)
    setError('')
    try {
      const res = await fetch(`/api/admin/properties/${propertyId}`, {
        method: 'PATCH',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ internalNotes: notes || null }),
      })
      if (!res.ok) throw new Error(`Save failed (${res.status})`)
      setSaved(true)
      router.refresh()
    } catch (e) {
      setError(e instanceof Error ? e.message : 'Save failed')
    } finally {
      setSaving(false)
      setTimeout(() => setSaved(false), 2000)
    }
  }

  return (
    <div className="bg-white rounded-lg shadow-sm border p-6">
      <h2 className="text-lg font-semibold mb-3 text-[#1D2019]">Internal notes</h2>
      {error && (
        <p className="text-sm text-red-600 mb-2" role="alert">{error}</p>
      )}
      <textarea
        value={notes}
        onChange={(e) => setNotes(e.target.value)}
        disabled={readOnly}
        rows={4}
        placeholder={readOnly ? '(no notes)' : 'Private notes for admin/agent team only...'}
        className="w-full px-3 py-2 border rounded text-sm disabled:bg-gray-50 disabled:text-gray-500"
      />
      {!readOnly && (
        <div className="flex items-center justify-end gap-3 mt-2">
          {saved && <span className="text-xs text-green-600">Saved</span>}
          <button
            onClick={save}
            disabled={saving || notes === (initialNotes ?? '')}
            className="text-sm px-4 py-1.5 bg-[#374527] text-white rounded hover:bg-[#1D2019] disabled:opacity-50"
          >
            {saving ? 'Saving...' : 'Save notes'}
          </button>
        </div>
      )}
    </div>
  )
}