'use client'

import { useState } from 'react'
import { useRouter } from 'next/navigation'
import { contactRoles, contactStatuses } from '@/lib/validations/property'

interface Props {
  propertyId: string
  readOnly?: boolean
}

export function ContactForm({ propertyId, readOnly = false }: Props) {
  const router = useRouter()
  const [name, setName] = useState('')
  const [email, setEmail] = useState('')
  const [phone, setPhone] = useState('')
  const [whatsapp, setWhatsapp] = useState('')
  const [role, setRole] = useState<'BUYER' | 'BROKER' | 'OTHER'>('BUYER')
  const [status, setStatus] = useState<'NEW' | 'CONTACTED' | 'INTERESTED' | 'NOT_INTERESTED' | 'CLOSED'>('NEW')
  const [notes, setNotes] = useState('')
  const [saving, setSaving] = useState(false)
  const [error, setError] = useState('')

  if (readOnly) return null

  function reset() {
    setName('')
    setEmail('')
    setPhone('')
    setWhatsapp('')
    setRole('BUYER')
    setStatus('NEW')
    setNotes('')
  }

  async function submit(e: React.FormEvent) {
    e.preventDefault()
    if (!name.trim()) {
      setError('Name is required')
      return
    }
    setSaving(true)
    setError('')
    try {
      const res = await fetch(`/api/admin/properties/${propertyId}/contacts`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          name: name.trim(),
          email: email.trim() || undefined,
          phone: phone.trim() || undefined,
          whatsapp: whatsapp.trim() || undefined,
          role,
          status,
          notes: notes.trim() || undefined,
        }),
      })
      if (!res.ok) {
        const err = await res.json().catch(() => ({}))
        throw new Error(err.error || `Save failed (${res.status})`)
      }
      reset()
      router.refresh()
    } catch (e) {
      setError(e instanceof Error ? e.message : 'Save failed')
    } finally {
      setSaving(false)
    }
  }

  return (
    <form
      onSubmit={submit}
      className="bg-gray-50 rounded border border-gray-200 p-3 space-y-2"
    >
      {error && (
        <p className="text-sm text-red-600" role="alert">
          {error}
        </p>
      )}
      <input
        value={name}
        onChange={(e) => setName(e.target.value)}
        placeholder="Contact name *"
        required
        className="w-full px-2 py-1 border rounded text-sm"
      />
      <div className="grid grid-cols-2 gap-2">
        <input
          value={email}
          onChange={(e) => setEmail(e.target.value)}
          type="email"
          placeholder="Email"
          className="px-2 py-1 border rounded text-sm"
        />
        <input
          value={phone}
          onChange={(e) => setPhone(e.target.value)}
          placeholder="Phone"
          className="px-2 py-1 border rounded text-sm"
        />
      </div>
      <input
        value={whatsapp}
        onChange={(e) => setWhatsapp(e.target.value)}
        placeholder="WhatsApp (optional)"
        className="w-full px-2 py-1 border rounded text-sm"
      />
      <div className="grid grid-cols-2 gap-2">
        <select
          value={role}
          onChange={(e) => setRole(e.target.value as 'BUYER' | 'BROKER' | 'OTHER')}
          className="px-2 py-1 border rounded text-sm"
        >
          {contactRoles.map((r) => (
            <option key={r} value={r}>{r}</option>
          ))}
        </select>
        <select
          value={status}
          onChange={(e) => setStatus(e.target.value as 'NEW' | 'CONTACTED' | 'INTERESTED' | 'NOT_INTERESTED' | 'CLOSED')}
          className="px-2 py-1 border rounded text-sm"
        >
          {contactStatuses.map((s) => (
            <option key={s} value={s}>{s.replace(/_/g, ' ')}</option>
          ))}
        </select>
      </div>
      <textarea
        value={notes}
        onChange={(e) => setNotes(e.target.value)}
        placeholder="Notes (optional)"
        rows={2}
        className="w-full px-2 py-1 border rounded text-sm"
      />
      <div className="flex justify-end">
        <button
          type="submit"
          disabled={saving}
          className="text-sm px-3 py-1 bg-[#374527] text-white rounded hover:bg-[#1D2019] disabled:opacity-50"
        >
          {saving ? 'Adding...' : 'Add contact'}
        </button>
      </div>
    </form>
  )
}