'use client'

import { useState } from 'react'
import { useRouter } from 'next/navigation'
import { Check, X, Eye, Building2, Pencil, Trash2 } from 'lucide-react'
import Link from 'next/link'
import { StatusBadge } from '@/components/agent/StatusBadge'

interface ImageLite {
  id: string
  path: string
  alt?: string | null
  isCover: boolean
}

interface AgentLite {
  id: string
  name?: string | null
  email: string
}

interface ListingLite {
  id: string
  title: string
  description: string
  type: string
  beds?: number | null
  baths?: unknown // Prisma Decimal
  priceUsd?: unknown // Prisma Decimal
  status: string
  images: ImageLite[]
  agent: AgentLite
  /** Set true si ya fue ingestado como Property (muestra badge en vez de botón) */
  ingestedAsProperty?: boolean
}

export function ListingModerationCard({ listing }: { listing: ListingLite }) {
  const router = useRouter()
  const [processing, setProcessing] = useState(false)
  const [showReject, setShowReject] = useState(false)
  const [note, setNote] = useState('')
  const [error, setError] = useState('')
  const [ingesting, setIngesting] = useState(false)
  const [deleting, setDeleting] = useState(false)

  async function ingest() {
    setIngesting(true)
    setError('')
    try {
      const res = await fetch('/api/admin/properties', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ listingId: listing.id }),
      })
      if (!res.ok) {
        const err = await res.json().catch(() => ({}))
        throw new Error(err.error || `Ingest failed (${res.status})`)
      }
      router.refresh()
    } catch (e) {
      setError(e instanceof Error ? e.message : 'Ingest failed')
    } finally {
      setIngesting(false)
    }
  }

  async function deleteListing() {
    if (!confirm(`Delete "${listing.title}"? This removes the listing + all images + its property (if ingested). Cannot be undone.`)) {
      return
    }
    setDeleting(true)
    setError('')
    try {
      const res = await fetch(`/api/agent/listings/${listing.id}`, {
        method: 'DELETE',
      })
      if (!res.ok) {
        const err = await res.json().catch(() => ({}))
        throw new Error(err.error || `Delete failed (${res.status})`)
      }
      router.push('/admin/listings')
      router.refresh()
    } catch (e) {
      setError(e instanceof Error ? e.message : 'Delete failed')
      setDeleting(false)
    }
  }

  const cover = listing.images.find((i) => i.isCover) || listing.images[0]
  const baths = listing.baths ? Number(listing.baths) : null
  const price = listing.priceUsd ? Number(listing.priceUsd) : null

  async function approve() {
    setProcessing(true)
    setError('')
    try {
      const res = await fetch(`/api/admin/listings/${listing.id}/approve`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({}),
      })
      if (!res.ok) throw new Error(`Approve failed (${res.status})`)
      router.refresh()
    } catch (e) {
      setError(e instanceof Error ? e.message : 'Approve failed')
    } finally {
      setProcessing(false)
    }
  }

  async function reject() {
    if (note.trim().length < 5) {
      setError('Please provide a reason (min 5 chars)')
      return
    }
    setProcessing(true)
    setError('')
    try {
      const res = await fetch(`/api/admin/listings/${listing.id}/reject`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ note }),
      })
      if (!res.ok) throw new Error(`Reject failed (${res.status})`)
      setShowReject(false)
      setNote('')
      router.refresh()
    } catch (e) {
      setError(e instanceof Error ? e.message : 'Reject failed')
    } finally {
      setProcessing(false)
    }
  }

  return (
    <div className="bg-white rounded-lg shadow-sm overflow-hidden border">
      <div className="flex flex-col md:flex-row">
        <div className="w-full md:w-48 h-32 bg-gray-100 flex-shrink-0">
          {cover ? (
            // eslint-disable-next-line @next/next/no-img-element
            <img src={cover.path} alt="" className="w-full h-full object-cover" />
          ) : (
            <div className="w-full h-full flex items-center justify-center text-gray-400 text-xs">
              No image
            </div>
          )}
        </div>
        <div className="flex-1 p-4">
          <div className="flex justify-between items-start gap-3">
            <div className="flex-1 min-w-0">
              <h3 className="font-semibold text-lg text-[#1D2019] truncate">
                {listing.title}
              </h3>
              <p className="text-sm text-gray-500 truncate">
                by {listing.agent.name || listing.agent.email}
              </p>
            </div>
            <StatusBadge status={listing.status} />
          </div>
          <p className="text-sm text-gray-700 mt-2 line-clamp-2">{listing.description}</p>
          <p className="text-xs text-gray-500 mt-2">
            {listing.images.length} {listing.images.length === 1 ? 'photo' : 'photos'} ·{' '}
            {listing.type}
            {listing.beds ? ` · ${listing.beds}bd` : ''}
            {baths ? ` / ${baths}ba` : ''}
            {price ? ` · $${price.toLocaleString()}` : ''}
          </p>
          {error && (
            <p className="text-sm text-red-600 mt-2" role="alert">
              {error}
            </p>
          )}

          {!showReject ? (
            <div className="flex gap-2 mt-3 flex-wrap">
              <Link
                href={`/admin/listings/${listing.id}`}
                className="flex items-center gap-1 text-sm px-3 py-1 border rounded hover:bg-gray-50"
              >
                <Eye size={14} />
                View
              </Link>
              {(listing.status === 'PENDING' || listing.status === 'DRAFT') && (
                <>
                  <button
                    onClick={approve}
                    disabled={processing}
                    className="flex items-center gap-1 text-sm px-3 py-1 bg-green-600 text-white rounded hover:bg-green-700 disabled:opacity-50"
                  >
                    <Check size={14} />
                    Approve
                  </button>
                  {listing.status === 'PENDING' && (
                    <button
                      onClick={() => setShowReject(true)}
                      disabled={processing}
                      className="flex items-center gap-1 text-sm px-3 py-1 bg-red-600 text-white rounded hover:bg-red-700 disabled:opacity-50"
                    >
                      <X size={14} />
                      Reject
                    </button>
                  )}
                </>
              )}
              {listing.status === 'REJECTED' && (
                <button
                  onClick={approve}
                  disabled={processing}
                  className="flex items-center gap-1 text-sm px-3 py-1 bg-green-600 text-white rounded hover:bg-green-700 disabled:opacity-50"
                >
                  <Check size={14} />
                  Approve anyway
                </button>
              )}
              {listing.status === 'APPROVED' && (
                <span className="text-xs text-green-700 px-3 py-1 bg-green-50 rounded">
                  Published
                </span>
              )}
              {listing.status === 'ARCHIVED' && (
                <button
                  onClick={approve}
                  disabled={processing}
                  className="flex items-center gap-1 text-sm px-3 py-1 bg-green-600 text-white rounded hover:bg-green-700 disabled:opacity-50"
                >
                  <Check size={14} />
                  Re-publish
                </button>
              )}
              {listing.status === 'APPROVED' && !listing.ingestedAsProperty && (
                <button
                  onClick={ingest}
                  disabled={ingesting}
                  className="flex items-center gap-1 text-sm px-3 py-1 bg-[#374527] text-white rounded hover:bg-[#1D2019] disabled:opacity-50"
                  title="Ingest into Property pipeline for CRM tracking"
                >
                  <Building2 size={14} />
                  {ingesting ? 'Ingesting...' : 'Ingest to Property'}
                </button>
              )}
              {listing.status === 'APPROVED' && listing.ingestedAsProperty && (
                <span className="text-xs text-gray-500 px-3 py-1 bg-gray-50 rounded">
                  Ingested as Property
                </span>
              )}
              <Link
                href={`/admin/listings/${listing.id}/edit`}
                className="flex items-center gap-1 text-sm px-3 py-1 border rounded hover:bg-gray-50"
              >
                <Pencil size={14} />
                Edit
              </Link>
              <button
                onClick={deleteListing}
                disabled={deleting}
                className="flex items-center gap-1 text-sm px-3 py-1 border border-red-300 text-red-700 rounded hover:bg-red-50 disabled:opacity-50"
                title="Delete listing + all images + property"
              >
                <Trash2 size={14} />
                {deleting ? 'Deleting...' : 'Delete'}
              </button>
            </div>
          ) : (
            <div className="mt-3 space-y-2">
              <textarea
                value={note}
                onChange={(e) => setNote(e.target.value)}
                placeholder="Reason for rejection (will be emailed to agent)"
                rows={2}
                minLength={5}
                className="w-full px-2 py-1 border rounded text-sm"
              />
              <div className="flex gap-2">
                <button
                  onClick={reject}
                  disabled={processing || note.length < 5}
                  className="text-sm px-3 py-1 bg-red-600 text-white rounded disabled:opacity-50"
                >
                  Confirm reject
                </button>
                <button
                  onClick={() => {
                    setShowReject(false)
                    setNote('')
                    setError('')
                  }}
                  className="text-sm px-3 py-1 border rounded hover:bg-gray-50"
                >
                  Cancel
                </button>
              </div>
            </div>
          )}
        </div>
      </div>
    </div>
  )
}