"use client";

import * as React from "react";
import Link from "next/link";
import {
  Bed,
  Bath,
  Maximize,
  MapPin,
  Calendar,
  Phone,
  Mail,
  CheckCircle,
  ShieldCheck,
  Tag,
  Edit,
  ExternalLink,
} from "lucide-react";
import {
  Sheet,
  SheetContent,
  SheetHeader,
  SheetTitle,
  SheetDescription,
} from "@/components/ui/sheet";
import { Button, buttonVariants } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
import { Property } from "@/lib/mock-data";
import { formatNaira, cn } from "@/lib/utils";

interface PropertyDetailSheetProps {
  property: Property | any | null;
  open: boolean;
  onOpenChange: (open: boolean) => void;
  onRequestVisit?: (property: Property) => void;
}

export function PropertyDetailSheet({
  property,
  open,
  onOpenChange,
  onRequestVisit,
}: PropertyDetailSheetProps) {
  const [activeImgIdx, setActiveImgIdx] = React.useState(0);

  if (!property) return null;

  const rawImages = Array.isArray(property.images) ? property.images : [];
  const images = rawImages.map((img: any) => (typeof img === "string" ? img : img?.url || "")).filter(Boolean);
  const finalImages = images.length > 0
    ? images
    : ["https://images.unsplash.com/photo-1600585154340-be6161a56a0c?auto=format&fit=crop&w=800&q=80"];

  const amenitiesList = Array.isArray(property.amenities)
    ? property.amenities.map((a: any) => (typeof a === "string" ? a : a?.name || String(a))).filter(Boolean)
    : ["24/7 Electricity", "Uniformed Security", "Treated Water", "Dedicated Parking"];

  const agentName = property.assignedAgent?.name || "Verified Listing Agent";
  const agentEmail = property.assignedAgent?.email || "agent@nigerialisting.com";
  const agentPhone = property.assignedAgent?.phone || "+234 800 000 0000";
  const agentAvatar = property.assignedAgent?.avatar || "";

  return (
    <Sheet open={open} onOpenChange={onOpenChange}>
      <SheetContent side="right" className="w-full sm:max-w-xl overflow-y-auto p-0 border-l border-border bg-card">
        <SheetHeader className="p-6 border-b border-border/60 bg-muted/20">
          <div className="flex items-center justify-between pr-8">
            <div className="flex items-center gap-2">
              <span className="rounded-md bg-primary/10 px-2 py-0.5 text-xs font-bold text-primary">
                {property.referenceCode || property.reference_code || "JAZ-NG"}
              </span>
              <span className="capitalize text-xs font-semibold text-muted-foreground">
                {(property.propertyType || property.property_type || "Apartment").replace(/_/g, " ")}
              </span>
            </div>
            <span
              className={cn(
                "rounded-full px-2.5 py-0.5 text-xs font-bold uppercase tracking-wider",
                property.status === "occupied" || property.status === "PUBLISHED"
                  ? "bg-emerald-500/10 text-emerald-600 dark:text-emerald-400"
                  : "bg-amber-500/10 text-amber-600 dark:text-amber-400"
              )}
            >
              {property.status || "PUBLISHED"}
            </span>
          </div>
          <SheetTitle className="text-xl font-bold text-foreground mt-2">
            {property.title || "Property Details"}
          </SheetTitle>
          <SheetDescription className="flex items-center gap-1 text-xs text-muted-foreground">
            <MapPin className="size-3.5 text-primary shrink-0" />
            <span>
              {property.address || property.street_address || ""}{property.city ? `, ${property.city}` : ""}{property.state ? `, ${property.state}` : ""}
            </span>
          </SheetDescription>

          {/* Quick Action Links */}
          <div className="flex items-center gap-2 pt-2.5">
            <Link
              href={`/dashboard/properties/${property.id}/edit`}
              className={buttonVariants({
                variant: "outline",
                size: "sm",
                className: "h-8 text-xs gap-1.5 rounded-xl font-semibold hover:bg-primary hover:text-primary-foreground",
              })}
            >
              <Edit className="size-3.5" />
              <span>Edit Listing</span>
            </Link>
            {property.slug && (
              <Link
                href={`/properties/${property.slug}`}
                target="_blank"
                className={buttonVariants({
                  variant: "ghost",
                  size: "sm",
                  className: "h-8 text-xs gap-1.5 rounded-xl text-muted-foreground hover:text-foreground hover:bg-muted",
                })}
              >
                <ExternalLink className="size-3.5" />
                <span>View Public Ad</span>
              </Link>
            )}
          </div>
        </SheetHeader>

        <div className="p-6 space-y-6">
          {/* Main Photo Gallery */}
          <div className="space-y-2">
            <div className="relative aspect-16/10 w-full overflow-hidden rounded-2xl bg-muted">
              <img
                src={finalImages[activeImgIdx] || finalImages[0]}
                alt={property.title || "Property"}
                className="size-full object-cover"
              />
            </div>
            {finalImages.length > 1 && (
              <div className="flex gap-2 overflow-x-auto pb-1">
                {finalImages.map((img: string, idx: number) => (
                  <button
                    key={idx}
                    onClick={() => setActiveImgIdx(idx)}
                    className={cn(
                      "relative size-16 shrink-0 overflow-hidden rounded-xl border-2 transition-all",
                      activeImgIdx === idx
                        ? "border-primary ring-2 ring-primary/30"
                        : "border-transparent opacity-70 hover:opacity-100"
                    )}
                  >
                    <img src={img} alt="" className="size-full object-cover" />
                  </button>
                ))}
              </div>
            )}
          </div>

          {/* Pricing & Key Numbers */}
          <div className="flex items-center justify-between rounded-2xl bg-muted/50 p-4 border border-border/60">
            <div>
              <span className="text-xs text-muted-foreground block">Listing Price</span>
              <span className="text-2xl font-extrabold text-foreground tracking-tight">
                {formatNaira(Number(property.price) || 0)}
                {property.listingType === "FOR_RENT" || property.listing_type === "FOR_RENT" ? (
                  <span className="text-xs text-muted-foreground font-normal ml-1">/year</span>
                ) : null}
              </span>
            </div>
            <div className="text-right">
              <span className="text-xs text-muted-foreground block">Listed Since</span>
              <span className="text-sm font-semibold text-foreground">
                {property.listedDate || "Recently"}
              </span>
            </div>
          </div>

          {/* Specs Grid */}
          <div className="grid grid-cols-3 gap-3">
            <div className="flex flex-col items-center justify-center rounded-xl border border-border/60 p-3 text-center bg-card">
              <Bed className="size-5 text-primary mb-1" />
              <span className="text-base font-bold text-foreground">{property.bedrooms ?? 0}</span>
              <span className="text-xs text-muted-foreground">Bedrooms</span>
            </div>
            <div className="flex flex-col items-center justify-center rounded-xl border border-border/60 p-3 text-center bg-card">
              <Bath className="size-5 text-primary mb-1" />
              <span className="text-base font-bold text-foreground">{property.bathrooms ?? 0}</span>
              <span className="text-xs text-muted-foreground">Bathrooms</span>
            </div>
            <div className="flex flex-col items-center justify-center rounded-xl border border-border/60 p-3 text-center bg-card">
              <Maximize className="size-5 text-primary mb-1" />
              <span className="text-base font-bold text-foreground">{property.totalAreaSqm || property.total_area_sqm || 0}</span>
              <span className="text-xs text-muted-foreground">Total m²</span>
            </div>
          </div>

          {/* Description */}
          {property.description && (
            <div className="space-y-2">
              <h4 className="text-sm font-bold text-foreground">About this property</h4>
              <p className="text-sm text-muted-foreground leading-relaxed">
                {property.description}
              </p>
            </div>
          )}

          {/* Amenities */}
          {amenitiesList.length > 0 && (
            <div className="space-y-3">
              <h4 className="text-sm font-bold text-foreground">Features & Amenities</h4>
              <div className="grid grid-cols-2 gap-2">
                {amenitiesList.map((amenity: string, idx: number) => (
                  <div
                    key={`${amenity}-${idx}`}
                    className="flex items-center gap-2 rounded-lg bg-muted/40 p-2 text-xs font-medium text-foreground"
                  >
                    <CheckCircle className="size-4 text-emerald-500 shrink-0" />
                    <span>{amenity}</span>
                  </div>
                ))}
              </div>
            </div>
          )}

          {/* Assigned Agent Profile */}
          <div className="space-y-3 rounded-2xl border border-border/60 p-4 bg-muted/30">
            <h4 className="text-xs font-semibold text-muted-foreground uppercase tracking-wider">
              Assigned Listing Agent
            </h4>
            <div className="flex items-center justify-between">
              <div className="flex items-center gap-3">
                <Avatar className="size-11 border border-border">
                  <AvatarImage src={agentAvatar} />
                  <AvatarFallback className="font-semibold text-xs bg-primary/10 text-primary">
                    {agentName.slice(0, 2).toUpperCase()}
                  </AvatarFallback>
                </Avatar>
                <div className="flex flex-col">
                  <span className="text-sm font-bold text-foreground">
                    {agentName}
                  </span>
                  <span className="text-xs text-muted-foreground">
                    {agentEmail}
                  </span>
                </div>
              </div>
              <Button
                variant="outline"
                size="sm"
                onClick={() => window.open(`tel:${agentPhone}`)}
                className="h-8 gap-1.5 rounded-full px-3 text-xs font-semibold"
              >
                <Phone className="size-3.5" />
                <span>Contact</span>
              </Button>
            </div>
          </div>

          {/* Location & Map Directions */}
          <div className="space-y-3 rounded-2xl border border-border/60 p-4 bg-card">
            <div className="flex items-center justify-between">
              <h4 className="text-xs font-semibold text-muted-foreground uppercase tracking-wider flex items-center gap-1.5">
                <MapPin className="size-3.5 text-primary" /> Location & Directions
              </h4>
              <span className="text-[11px] text-muted-foreground font-mono">
                {property.city || "Lagos"}, {property.state || "Nigeria"}
              </span>
            </div>
            <p className="text-xs text-foreground font-medium">
              {property.address || "Property address on file"}
            </p>
            <div className="grid grid-cols-2 gap-2 pt-1">
              <Button
                variant="outline"
                size="sm"
                onClick={() => {
                  const lat = property.latitude || 6.4474;
                  const lng = property.longitude || 3.4723;
                  window.open(`https://www.google.com/maps/dir/?api=1&destination=${lat},${lng}`, "_blank");
                }}
                className="h-8 text-xs gap-1 rounded-xl"
              >
                <span>Google Maps</span>
              </Button>
              <Button
                variant="outline"
                size="sm"
                onClick={() => {
                  const lat = property.latitude || 6.4474;
                  const lng = property.longitude || 3.4723;
                  window.open(`https://maps.apple.com/?daddr=${lat},${lng}&dirflg=d`, "_blank");
                }}
                className="h-8 text-xs gap-1 rounded-xl"
              >
                <span>Apple Maps</span>
              </Button>
            </div>
          </div>

          {/* Bottom Action */}
          <div className="pt-2">
            <Button
              size="lg"
              onClick={() => {
                onRequestVisit?.(property);
                onOpenChange(false);
              }}
              className="w-full rounded-xl font-bold bg-primary text-primary-foreground shadow-md hover:bg-primary/95"
            >
              <Calendar className="size-4 mr-2" />
              Schedule a Visit Request
            </Button>
          </div>
        </div>
      </SheetContent>
    </Sheet>
  );
}

