"use client"

import { useState, useRef } from "react"
import { useRouter } from "next/navigation"
import { toast } from "sonner"
import { Camera, Loader2, X } from "lucide-react"

interface Props {
  propertyId: string
  currentImageUrl?: string | null
}

export function PropertyPhotoUpload({ propertyId, currentImageUrl }: Props) {
  const router = useRouter()
  const fileRef = useRef<HTMLInputElement>(null)
  const [uploading, setUploading] = useState(false)
  const [preview, setPreview] = useState<string | null>(currentImageUrl ?? null)

  async function handleFile(e: React.ChangeEvent<HTMLInputElement>) {
    const file = e.target.files?.[0]
    if (!file) return

    if (!file.type.startsWith("image/")) {
      toast.error("Please select an image file")
      return
    }
    if (file.size > 5 * 1024 * 1024) {
      toast.error("Image must be under 5MB")
      return
    }

    setUploading(true)
    try {
      // Upload to local storage via the gated upload endpoint
      const uploadData = new FormData()
      uploadData.append("file", file)
      uploadData.append("scope", "property-images")
      uploadData.append("fixed_name", propertyId)

      const uploadRes = await fetch("/api/upload", { method: "POST", body: uploadData })
      if (!uploadRes.ok) throw new Error("Upload failed")
      const { url: publicUrl } = await uploadRes.json()

      // Update property record
      const res = await fetch(`/api/properties/${propertyId}`, {
        method: "PATCH",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ image_url: publicUrl }),
      })

      if (!res.ok) throw new Error("Failed to save image URL")

      setPreview(publicUrl)
      toast.success("Photo updated")
      router.refresh()
    } catch (err: any) {
      toast.error(err.message ?? "Upload failed")
    } finally {
      setUploading(false)
    }
  }

  async function removePhoto() {
    setUploading(true)
    try {
      const res = await fetch(`/api/properties/${propertyId}`, {
        method: "PATCH",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ image_url: null }),
      })
      if (!res.ok) throw new Error("Failed to remove photo")
      setPreview(null)
      toast.success("Photo removed")
      router.refresh()
    } catch {
      toast.error("Failed to remove photo")
    } finally {
      setUploading(false)
    }
  }

  return (
    <div className="relative">
      {preview ? (
        <div className="group relative h-44 w-full overflow-hidden rounded-xl border border-white/[0.06]">
          <img src={preview} alt="Property" className="h-full w-full object-cover" />
          <div className="absolute inset-0 flex items-center justify-center gap-2 bg-black/50 opacity-0 group-hover:opacity-100 transition">
            <button
              onClick={() => fileRef.current?.click()}
              disabled={uploading}
              className="flex items-center gap-1.5 rounded-lg bg-white/10 px-3 py-2 text-xs text-white hover:bg-white/20 transition"
            >
              <Camera className="h-3.5 w-3.5" /> Change
            </button>
            <button
              onClick={removePhoto}
              disabled={uploading}
              className="flex items-center gap-1.5 rounded-lg bg-red-500/20 px-3 py-2 text-xs text-red-400 hover:bg-red-500/30 transition"
            >
              <X className="h-3.5 w-3.5" /> Remove
            </button>
          </div>
          {uploading && (
            <div className="absolute inset-0 flex items-center justify-center bg-black/60">
              <Loader2 className="h-6 w-6 animate-spin text-white" />
            </div>
          )}
        </div>
      ) : (
        <button
          onClick={() => fileRef.current?.click()}
          disabled={uploading}
          className="flex h-44 w-full flex-col items-center justify-center gap-2 rounded-xl border-2 border-dashed border-white/10 bg-white/[0.02] text-white/30 hover:border-indigo-500/40 hover:text-white/50 transition disabled:opacity-50"
        >
          {uploading
            ? <Loader2 className="h-6 w-6 animate-spin" />
            : <>
                <Camera className="h-6 w-6" />
                <span className="text-xs">Add property photo</span>
              </>
          }
        </button>
      )}
      <input
        ref={fileRef}
        type="file"
        accept="image/*"
        className="hidden"
        onChange={handleFile}
      />
    </div>
  )
}
