"use client"

import { useState, useEffect } from "react"
import { useParams, useRouter } from "next/navigation"
import Link from "next/link"
import { FileText, Download, Trash2, Loader2 } from "lucide-react"
import { FileUpload } from "@/components/shared/file-upload"
import { formatDate } from "@/lib/utils"

function formatBytes(bytes: number) {
  if (bytes < 1024) return `${bytes} B`
  if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`
  return `${(bytes / (1024 * 1024)).toFixed(1)} MB`
}

export default function DocumentsPage() {
  const params = useParams()
  const propertyId = params.propertyId as string
  const router = useRouter()

  const [docs, setDocs] = useState<any[]>([])
  const [loading, setLoading] = useState(true)
  const [deleting, setDeleting] = useState<string | null>(null)
  const [propertyName, setPropertyName] = useState("")

  useEffect(() => {
    fetch(`/api/documents?property_id=${propertyId}`)
      .then((r) => r.json())
      .then((data) => {
        setDocs(data.documents ?? [])
        setPropertyName(data.propertyName ?? "")
        setLoading(false)
      })
  }, [propertyId])

  async function deleteDoc(id: string) {
    setDeleting(id)
    await fetch(`/api/documents/${id}`, { method: "DELETE" })
    setDocs((prev) => prev.filter((d) => d.id !== id))
    setDeleting(null)
  }

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <div className="flex items-center gap-2 text-sm text-white/40 mb-1">
            <Link href="/properties" className="hover:text-white transition">Properties</Link>
            <span>/</span>
            <Link href={`/properties/${propertyId}`} className="hover:text-white transition">{propertyName || propertyId}</Link>
            <span>/</span>
            <span className="text-white/70">Documents</span>
          </div>
          <h2 className="text-lg font-semibold text-white">Documents</h2>
          <p className="text-sm text-white/40">{docs.length} file{docs.length !== 1 ? "s" : ""}</p>
        </div>
      </div>

      <FileUpload
        propertyId={propertyId}
        onUploaded={(doc) => setDocs((prev) => [doc, ...prev])}
      />

      {loading ? (
        <div className="flex items-center justify-center py-16">
          <Loader2 className="h-6 w-6 animate-spin text-white/30" />
        </div>
      ) : docs.length === 0 ? (
        <div className="flex flex-col items-center justify-center rounded-xl border border-white/[0.06] bg-[#16161f] py-16 text-center">
          <FileText className="h-10 w-10 text-white/10 mb-3" />
          <p className="text-sm text-white/40">No documents yet</p>
          <p className="text-xs text-white/25 mt-1">Upload leases, insurance, or any property files</p>
        </div>
      ) : (
        <div className="rounded-xl border border-white/[0.06] bg-[#16161f] overflow-hidden">
          <div className="divide-y divide-white/[0.04]">
            {docs.map((doc) => (
              <div key={doc.id} className="flex items-center gap-4 px-5 py-4">
                <div className="flex h-9 w-9 flex-shrink-0 items-center justify-center rounded-lg bg-indigo-500/10">
                  <FileText className="h-4 w-4 text-indigo-400" />
                </div>
                <div className="flex-1 min-w-0">
                  <p className="truncate text-sm font-medium text-white">{doc.name}</p>
                  <p className="text-xs text-white/40">
                    {formatBytes(doc.file_size ?? 0)} · {formatDate(doc.created_at)}
                  </p>
                </div>
                <div className="flex items-center gap-2">
                  <a
                    href={doc.file_url}
                    target="_blank"
                    rel="noopener noreferrer"
                    className="flex h-8 w-8 items-center justify-center rounded-lg border border-white/10 text-white/50 hover:text-white transition"
                  >
                    <Download className="h-3.5 w-3.5" />
                  </a>
                  <button
                    onClick={() => deleteDoc(doc.id)}
                    disabled={deleting === doc.id}
                    className="flex h-8 w-8 items-center justify-center rounded-lg border border-white/10 text-white/50 hover:text-red-400 hover:border-red-500/30 transition disabled:opacity-40"
                  >
                    {deleting === doc.id ? (
                      <Loader2 className="h-3.5 w-3.5 animate-spin" />
                    ) : (
                      <Trash2 className="h-3.5 w-3.5" />
                    )}
                  </button>
                </div>
              </div>
            ))}
          </div>
        </div>
      )}
    </div>
  )
}
