'use client'

import Link from 'next/link'
import { useRouter } from 'next/navigation'
import { useState } from 'react'
import { Mail, Phone, Search as SearchIcon } from 'lucide-react'
import { contactRoles, contactStatuses } from '@/lib/validations/property'

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

interface Props {
  contacts: Contact[]
  filters: { role: string; status: string; q: string }
  basePath: string
}

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 ContactsTable({ contacts, filters, basePath }: Props) {
  const router = useRouter()
  const [q, setQ] = useState(filters.q)
  const [role, setRole] = useState(filters.role)
  const [status, setStatus] = useState(filters.status)

  function applyFilters(e?: React.FormEvent) {
    e?.preventDefault()
    const params = new URLSearchParams()
    if (q.trim()) params.set('q', q.trim())
    if (role) params.set('role', role)
    if (status) params.set('status', status)
    router.push(`${basePath}?${params.toString()}`)
  }

  function clearFilters() {
    setQ('')
    setRole('')
    setStatus('')
    router.push(basePath)
  }

  return (
    <div>
      <form onSubmit={applyFilters} className="flex flex-wrap gap-2 mb-4 items-end">
        <div className="flex-1 min-w-[200px]">
          <label className="block text-xs text-gray-600 mb-1">Search</label>
          <div className="relative">
            <SearchIcon size={14} className="absolute left-2 top-1/2 -translate-y-1/2 text-gray-400" />
            <input
              value={q}
              onChange={(e) => setQ(e.target.value)}
              placeholder="Name, email or phone..."
              className="w-full pl-7 pr-2 py-1.5 border rounded"
            />
          </div>
        </div>
        <div>
          <label className="block text-xs text-gray-600 mb-1">Role</label>
          <select
            value={role}
            onChange={(e) => setRole(e.target.value)}
            className="py-1.5 border rounded"
          >
            <option value="">All</option>
            {contactRoles.map((r) => (
              <option key={r} value={r}>{r}</option>
            ))}
          </select>
        </div>
        <div>
          <label className="block text-xs text-gray-600 mb-1">Status</label>
          <select
            value={status}
            onChange={(e) => setStatus(e.target.value)}
            className="py-1.5 border rounded"
          >
            <option value="">All</option>
            {contactStatuses.map((s) => (
              <option key={s} value={s}>{s.replace(/_/g, ' ')}</option>
            ))}
          </select>
        </div>
        <button
          type="submit"
          className="px-4 py-1.5 bg-[#374527] text-white rounded hover:bg-[#1D2019]"
        >
          Filter
        </button>
        {(filters.q || filters.role || filters.status) && (
          <button
            type="button"
            onClick={clearFilters}
            className="px-3 py-1.5 border rounded hover:bg-gray-50"
          >
            Clear
          </button>
        )}
      </form>

      {contacts.length === 0 ? (
        <p className="text-gray-500 text-center py-12 bg-white border rounded-lg">
          No contacts match your filters.
        </p>
      ) : (
        <div className="bg-white rounded-lg shadow-sm border overflow-hidden">
          <table className="w-full text-sm">
            <thead className="bg-gray-50 border-b">
              <tr>
                <th className="text-left px-4 py-3 font-medium text-gray-700">Name</th>
                <th className="text-left px-4 py-3 font-medium text-gray-700">Role</th>
                <th className="text-left px-4 py-3 font-medium text-gray-700">Status</th>
                <th className="text-left px-4 py-3 font-medium text-gray-700">Contact</th>
                <th className="text-left px-4 py-3 font-medium text-gray-700">Property</th>
                <th className="text-left px-4 py-3 font-medium text-gray-700">Added</th>
                <th className="px-4 py-3"></th>
              </tr>
            </thead>
            <tbody>
              {contacts.map((c) => (
                <tr key={c.id} className="border-b last:border-0 hover:bg-gray-50">
                  <td className="px-4 py-3">
                    <p className="font-medium text-[#1D2019]">{c.name}</p>
                  </td>
                  <td className="px-4 py-3">
                    <span className={`text-xs px-2 py-0.5 rounded ${ROLE_COLORS[c.role] ?? 'bg-gray-100 text-gray-700'}`}>
                      {c.role}
                    </span>
                  </td>
                  <td className="px-4 py-3">
                    <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>
                  </td>
                  <td className="px-4 py-3 text-xs">
                    {c.email && (
                      <p className="flex items-center gap-1">
                        <Mail size={10} /> {c.email}
                      </p>
                    )}
                    {c.phone && (
                      <p className="flex items-center gap-1">
                        <Phone size={10} /> {c.phone}
                      </p>
                    )}
                  </td>
                  <td className="px-4 py-3">
                    <Link
                      href={`${basePath.replace('/contacts', '/properties')}/${c.property.id}`}
                      className="text-[#374527] hover:underline text-xs truncate inline-block max-w-[180px]"
                    >
                      {c.property.title}
                    </Link>
                  </td>
                  <td className="px-4 py-3 text-xs text-gray-500">
                    {new Date(c.createdAt).toLocaleDateString()}
                  </td>
                  <td className="px-4 py-3">
                    <Link
                      href={`${basePath}/${c.id}`}
                      className="text-[#374527] hover:underline text-xs"
                    >
                      Open →
                    </Link>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}
    </div>
  )
}