'use client'

import { useState } from 'react'
import { useRouter } from 'next/navigation'
import { Trash2, Mail, Phone } from 'lucide-react'

interface Contact {
  id: string
  name: string
  email?: string | null
  phone?: string | null
  whatsapp?: string | null
  role: string
  status: string
  notes?: string | null
}

interface Props {
  propertyId: string
  contacts: Contact[]
  readOnly?: boolean
}

const ROLE_COLORS: Record<string, string> = {
  BUYER: 'bg-blue-100 text-blue-800',
  BROKER: 'bg-purple-100 text-purple-800',
  OTHER: 'bg-gray-100 text-gray-700',
}

const STATUS_COLORS: Record<string, string> = {
  NEW: 'bg-gray-100 text-gray-700',
  CONTACTED: 'bg-yellow-100 text-yellow-800',
  INTERESTED: 'bg-green-100 text-green-800',
  NOT_INTERESTED: 'bg-red-100 text-red-700',
  CLOSED: 'bg-slate-200 text-slate-700',
}

export function ContactList({ propertyId, contacts, readOnly = false }: Props) {
  const router = useRouter()
  const [removing, setRemoving] = useState<string | null>(null)

  async function remove(id: string) {
    if (readOnly || !confirm('Delete this contact?')) return
    setRemoving(id)
    try {
      const res = await fetch(`/api/admin/properties/${propertyId}/contacts/${id}`, {
        method: 'DELETE',
      })
      if (!res.ok) throw new Error(`Delete failed (${res.status})`)
      router.refresh()
    } catch (e) {
      alert(e instanceof Error ? e.message : 'Delete failed')
    } finally {
      setRemoving(null)
    }
  }

  if (contacts.length === 0) {
    return (
      <p className="text-gray-500 text-sm text-center py-6 bg-gray-50 border border-dashed rounded">
        No contacts yet.
      </p>
    )
  }

  return (
    <ul className="space-y-2">
      {contacts.map((c) => (
        <li key={c.id} className="bg-white border rounded p-3 flex items-start justify-between gap-2">
          <div className="flex-1 min-w-0">
            <div className="flex items-center gap-2 flex-wrap mb-1">
              <p className="font-medium text-[#1D2019]">{c.name}</p>
              <span className={`text-xs px-2 py-0.5 rounded ${ROLE_COLORS[c.role] ?? 'bg-gray-100 text-gray-700'}`}>
                {c.role}
              </span>
              <span className={`text-xs px-2 py-0.5 rounded ${STATUS_COLORS[c.status] ?? 'bg-gray-100 text-gray-700'}`}>
                {c.status.replace(/_/g, ' ')}
              </span>
            </div>
            <div className="text-sm text-gray-700 space-y-0.5">
              {c.email && (
                <p className="flex items-center gap-1">
                  <Mail size={12} /> {c.email}
                </p>
              )}
              {c.phone && (
                <p className="flex items-center gap-1">
                  <Phone size={12} /> {c.phone}
                  {c.whatsapp && c.whatsapp !== c.phone && (
                    <span className="text-xs text-gray-500">(WA: {c.whatsapp})</span>
                  )}
                </p>
              )}
            </div>
            {c.notes && (
              <p className="text-sm text-gray-600 mt-1 whitespace-pre-wrap">{c.notes}</p>
            )}
          </div>
          {!readOnly && (
            <button
              onClick={() => remove(c.id)}
              disabled={removing === c.id}
              className="text-red-600 hover:text-red-800 disabled:opacity-50 flex-shrink-0"
              title="Delete contact"
            >
              <Trash2 size={16} />
            </button>
          )}
        </li>
      ))}
    </ul>
  )
}