import { useState, useEffect } from "react";
import { MapPin } from "lucide-react";
import { cn } from "@/lib/utils";
import { geocodeAddress, staticSatelliteUrl } from "@/lib/leafletMaps";

interface PropertyImageProps {
  address: string;
  imageUrl?: string | null;
  width?: number;
  height?: number;
  className?: string;
}

export default function PropertyImage({ address, imageUrl, width = 320, height = 240, className }: PropertyImageProps) {
  const [imageSrc, setImageSrc] = useState<string | null>(null);
  const [imageType, setImageType] = useState<"custom" | "satellite" | "none">("none");
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    if (imageUrl) {
      setImageSrc(imageUrl);
      setImageType("custom");
      setLoading(false);
      return;
    }

    if (!address) {
      setImageSrc(null);
      setImageType("none");
      setLoading(false);
      return;
    }

    let cancelled = false;
    setLoading(true);
    setImageSrc(null);

    (async () => {
      const geo = await geocodeAddress(address);
      if (cancelled) return;
      if (!geo) {
        setImageSrc(null);
        setImageType("none");
        setLoading(false);
        return;
      }
      setImageSrc(staticSatelliteUrl(geo.lat, geo.lng, width, height, 19));
      setImageType("satellite");
      setLoading(false);
    })();

    return () => { cancelled = true; };
  }, [address, imageUrl, width, height]);

  if (!address && !imageUrl) return null;

  return (
    <div
      className={cn("rounded-lg overflow-hidden border bg-muted relative", className)}
      style={{ width, height }}
    >
      {loading && (
        <div className="absolute inset-0 flex flex-col items-center justify-center gap-2 bg-muted z-10">
          <div className="h-5 w-5 animate-spin rounded-full border-2 border-primary border-t-transparent" />
          <span className="text-xs text-muted-foreground">Loading image…</span>
        </div>
      )}

      {!loading && imageSrc && (
        <>
          <img
            src={imageSrc}
            alt={`${imageType === "satellite" ? "Satellite view" : "Property photo"} of ${address}`}
            className="w-full h-full object-cover"
            onError={() => { setImageSrc(null); setImageType("none"); }}
          />
          {imageType === "satellite" && (
            <div className="absolute bottom-1.5 left-1.5 bg-black/60 text-white text-[10px] px-1.5 py-0.5 rounded flex items-center gap-1">
              <MapPin className="h-3 w-3" /> Satellite View
            </div>
          )}
        </>
      )}

      {!loading && !imageSrc && (
        <div className="absolute inset-0 flex flex-col items-center justify-center gap-2 bg-muted">
          <MapPin className="h-8 w-8 text-muted-foreground/40" />
          <span className="text-xs text-muted-foreground">No image available</span>
        </div>
      )}
    </div>
  );
}
