'use client'

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

interface Advance {
  id: string
  type: string
  title: string
  description?: string | null
  fromStatus?: string | null
  toStatus?: string | null
  createdAt: string | Date
  createdBy?: { id: string; name?: string | null; email: string }
}

interface Props {
  propertyId: string
  advances: Advance[]
  readOnly?: boolean
}

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

  async function remove(id: string) {
    if (readOnly || !confirm('Delete this entry?')) return
    setRemoving(id)
    try {
      const res = await fetch(`/api/admin/properties/${propertyId}/advances/${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 (advances.length === 0) {
    return (
      <p className="text-gray-500 text-sm text-center py-6 bg-gray-50 border border-dashed rounded">
        No advances yet.
      </p>
    )
  }

  return (
    <ol className="space-y-3">
      {advances.map((a) => {
        const isStatusChange = a.type === 'STATUS_CHANGE'
        const date = new Date(a.createdAt)
        return (
          <li
            key={a.id}
            className={`p-3 rounded border ${
              isStatusChange
                ? 'bg-purple-50 border-purple-200'
                : 'bg-white border-gray-200'
            }`}
          >
            <div className="flex items-start justify-between gap-2">
              <div className="flex-1 min-w-0">
                <div className="flex items-center gap-2 flex-wrap">
                  <span
                    className={`text-xs px-2 py-0.5 rounded font-medium ${
                      isStatusChange
                        ? 'bg-purple-200 text-purple-800'
                        : 'bg-gray-200 text-gray-700'
                    }`}
                  >
                    {isStatusChange ? 'Status change' : 'Note'}
                  </span>
                  <p className="font-medium text-[#1D2019]">{a.title}</p>
                </div>
                {a.description && (
                  <p className="text-sm text-gray-700 mt-1 whitespace-pre-wrap">{a.description}</p>
                )}
                <p className="text-xs text-gray-500 mt-2">
                  {date.toLocaleString()} ·{' '}
                  {a.createdBy?.name || a.createdBy?.email || 'unknown'}
                </p>
              </div>
              {!readOnly && (
                <button
                  onClick={() => remove(a.id)}
                  disabled={removing === a.id}
                  className="text-red-600 hover:text-red-800 disabled:opacity-50 flex-shrink-0"
                  title="Delete"
                >
                  <Trash2 size={16} />
                </button>
              )}
            </div>
          </li>
        )
      })}
    </ol>
  )
}