"use client";

import * as React from "react";
import Link from "next/link";
import {
  Plus,
  Search,
  LayoutGrid,
  List,
  Eye,
  Edit,
  Trash2,
  ExternalLink,
  Handshake,
  AlertTriangle,
  Loader2,
  CheckCircle2,
} from "lucide-react";
import { MdCorporateFare } from "react-icons/md";
import { PropertyCard } from "@/components/properties/property-card";
import { PropertyDetailSheet } from "@/components/properties/property-detail-sheet";
import { AddPropertySheet } from "@/components/properties/add-property-sheet";
import { MarkSoldModal } from "@/components/deals/mark-sold-modal";
import { Button, buttonVariants } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Badge } from "@/components/ui/badge";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogDescription,
  DialogFooter,
} from "@/components/ui/dialog";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { cn, formatNaira } from "@/lib/utils";
import { EmptyState } from "@/components/ui/empty-state";
import { archivePropertyAction } from "@/app/actions/property.actions";

interface PropertiesClientViewProps {
  initialProperties: any[];
}

export function PropertiesClientView({
  initialProperties = [],
}: PropertiesClientViewProps) {
  const [properties, setProperties] = React.useState<any[]>(initialProperties);
  const [searchQuery, setSearchQuery] = React.useState("");
  const [statusFilter, setStatusFilter] = React.useState("all");
  const [typeFilter, setTypeFilter] = React.useState("all");
  const [viewMode, setViewMode] = React.useState<"grid" | "table">("grid");
  const [selectedProperty, setSelectedProperty] = React.useState<any | null>(null);
  const [isDetailOpen, setIsDetailOpen] = React.useState(false);
  const [isAddOpen, setIsAddOpen] = React.useState(false);
  const [propertyToDelete, setPropertyToDelete] = React.useState<any | null>(null);
  const [isDeleting, setIsDeleting] = React.useState(false);
  const [selectedPropForSold, setSelectedPropForSold] = React.useState<any | null>(null);

  // Sync if initial properties change
  React.useEffect(() => {
    setProperties(initialProperties);
  }, [initialProperties]);

  const handleAddProperty = (newProp: any) => {
    setProperties((prev) => [newProp, ...prev]);
  };

  const confirmDeleteProperty = async () => {
    if (!propertyToDelete) return;
    setIsDeleting(true);
    try {
      await archivePropertyAction(propertyToDelete.id);
      setProperties((prev) => prev.filter((p) => p.id !== propertyToDelete.id));
      setPropertyToDelete(null);
    } catch (err) {
      console.error("Failed to delete property:", err);
    } finally {
      setIsDeleting(false);
    }
  };

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

    return {
      id: p.id,
      title: p.title,
      slug: p.slug,
      referenceCode: p.reference_code || p.referenceCode || "JAZ-NG",
      description: p.description || "",
      listingType: p.listing_type || p.listingType || "FOR_SALE",
      propertyType: p.property_type || p.propertyType || "Apartment",
      price: Number(p.price || 0),
      currency: p.currency || "NGN",
      bedrooms: p.bedrooms || 0,
      bathrooms: p.bathrooms || 0,
      parkingSpaces: p.parking_spaces || 0,
      totalAreaSqm: p.total_area_sqm || 0,
      address: p.street_address || p.address || "",
      city: p.district?.name || p.lga?.name || p.city || "Lagos",
      state: p.state?.name || p.state || "Nigeria",
      status: p.status || "PUBLISHED",
      viewsCount: p.view_count || p.views || 0,
      inquiriesCount: p.inquiry_count || p.inquiries || 0,
      listedDate: p.created_at ? new Date(p.created_at).toLocaleDateString() : "Recently",
      images: finalImages,
      amenities: Array.isArray(p.amenities)
        ? p.amenities.map((a: any) => (typeof a === "string" ? a : a?.name || "")).filter(Boolean)
        : ["24/7 Power", "Security Guard", "Water Treatment", "Ample Parking"],
      latitude: p.latitude ? Number(p.latitude) : null,
      longitude: p.longitude ? Number(p.longitude) : null,
      assignedAgent: p.assignedAgent || {
        name: "Verified Agent",
        email: "agent@nigerialisting.com",
        phone: "+2348000000000",
      },
    };
  });

  const filteredProperties = normalizedProperties.filter((prop) => {
    const matchesSearch =
      prop.title.toLowerCase().includes(searchQuery.toLowerCase()) ||
      prop.address.toLowerCase().includes(searchQuery.toLowerCase()) ||
      prop.city.toLowerCase().includes(searchQuery.toLowerCase());

    const matchesStatus =
      statusFilter === "all" || prop.status.toLowerCase() === statusFilter.toLowerCase();

    const matchesType =
      typeFilter === "all" || prop.propertyType.toLowerCase().includes(typeFilter.toLowerCase());

    return matchesSearch && matchesStatus && matchesType;
  });

  const publishedCount = normalizedProperties.filter(
    (p) => p.status.toUpperCase() === "PUBLISHED" || p.status.toLowerCase() === "occupied"
  ).length;

  const getStatusBadge = (status: string) => {
    const upper = status.toUpperCase();
    switch (upper) {
      case "PUBLISHED":
      case "OCCUPIED":
        return "bg-emerald-500/10 text-emerald-600 dark:text-emerald-400 border-emerald-500/20";
      case "PENDING_REVIEW":
      case "VACANT":
        return "bg-amber-500/10 text-amber-600 dark:text-amber-400 border-amber-500/20";
      case "UNDER_OFFER":
        return "bg-sky-500/10 text-sky-600 dark:text-sky-400 border-sky-500/20";
      case "SOLD":
      case "RENTED":
        return "bg-blue-500/10 text-blue-600 dark:text-blue-400 border-blue-500/20";
      default:
        return "bg-muted text-muted-foreground";
    }
  };

  return (
    <div className="space-y-6">
      {/* Header - Clean Consolidated */}
      <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4 pb-4 border-b border-border">
        <div className="space-y-0.5">
          <h1 className="text-xl sm:text-2xl font-bold tracking-tight text-foreground">
            My Direct Ads
          </h1>
          <p className="text-xs sm:text-sm text-muted-foreground">
            {normalizedProperties.length === 0
              ? "No listings posted yet"
              : `${normalizedProperties.length} total ${normalizedProperties.length === 1 ? "listing" : "listings"} · ${publishedCount} published on marketplace`}
          </p>
        </div>

        <div className="flex items-center gap-2">
          <Link
            href="/dashboard/properties/new"
            className={buttonVariants({
              className:
                "rounded-md bg-primary hover:bg-primary/90 text-primary-foreground font-semibold text-xs gap-1.5 shadow-2xs h-9 px-3.5",
            })}
          >
            <Plus className="size-3.5 mr-1" />
            <span>Post New Ad</span>
          </Link>
        </div>
      </div>

      {/* Filters Bar */}
      <div className="flex flex-col sm:flex-row items-center justify-between gap-3 rounded-2xl border border-border/80 bg-card p-3 shadow-xs">
        <div className="flex flex-1 flex-wrap items-center gap-2.5 w-full sm:w-auto">
          {/* Search Input */}
          <div className="relative flex-1 sm:max-w-xs w-full">
            <Search className="absolute left-3 top-1/2 size-4 -translate-y-1/2 text-muted-foreground" />
            <Input
              placeholder="Search properties..."
              value={searchQuery}
              onChange={(e) => setSearchQuery(e.target.value)}
              className="pl-9 rounded-xl bg-muted/40 border-border/60"
            />
          </div>

          {/* Status Filter */}
          <Select value={statusFilter} onValueChange={(val) => setStatusFilter(val ?? "all")}>
            <SelectTrigger className="w-36 rounded-xl bg-muted/40 border-border/60">
              <SelectValue placeholder="All Status" />
            </SelectTrigger>
            <SelectContent className="rounded-xl">
              <SelectItem value="all">All Status</SelectItem>
              <SelectItem value="published">Published</SelectItem>
              <SelectItem value="pending_review">Pending Review</SelectItem>
              <SelectItem value="draft">Draft</SelectItem>
              <SelectItem value="under_offer">Under Offer</SelectItem>
              <SelectItem value="sold">Sold</SelectItem>
            </SelectContent>
          </Select>

          {/* Type Filter */}
          <Select value={typeFilter} onValueChange={(val) => setTypeFilter(val ?? "all")}>
            <SelectTrigger className="w-36 rounded-xl bg-muted/40 border-border/60">
              <SelectValue placeholder="All Types" />
            </SelectTrigger>
            <SelectContent className="rounded-xl">
              <SelectItem value="all">All Types</SelectItem>
              <SelectItem value="apartment">Apartment</SelectItem>
              <SelectItem value="duplex">Duplex</SelectItem>
              <SelectItem value="mansion">Mansion</SelectItem>
              <SelectItem value="commercial">Commercial</SelectItem>
              <SelectItem value="land">Land</SelectItem>
            </SelectContent>
          </Select>
        </div>

        {/* View Mode Toggle */}
        <div className="flex items-center gap-1 self-end sm:self-auto border border-border/60 rounded-xl p-1 bg-muted/30">
          <Button
            variant={viewMode === "grid" ? "secondary" : "ghost"}
            size="icon"
            onClick={() => setViewMode("grid")}
            className="size-8 rounded-lg"
            aria-label="Grid view"
          >
            <LayoutGrid className="size-4" />
          </Button>
          <Button
            variant={viewMode === "table" ? "secondary" : "ghost"}
            size="icon"
            onClick={() => setViewMode("table")}
            className="size-8 rounded-lg"
            aria-label="Table view"
          >
            <List className="size-4" />
          </Button>
        </div>
      </div>

      {/* Content Area */}
      {filteredProperties.length === 0 ? (
        <EmptyState
          icon={MdCorporateFare}
          title={
            searchQuery || statusFilter !== "all" || typeFilter !== "all"
              ? "No Matching Properties Found"
              : "No Properties in Your Portfolio"
          }
          description={
            searchQuery || statusFilter !== "all" || typeFilter !== "all"
              ? "No property records match your current filters. Try clearing your search keyword or status filter."
              : "Start managing your real estate portfolio by adding your first residential or commercial property unit."
          }
          primaryAction={{
            label: "Add New Property",
            href: "/dashboard/properties/new",
            icon: Plus,
          }}
          secondaryAction={
            searchQuery || statusFilter !== "all" || typeFilter !== "all"
              ? {
                  label: "Clear Filters",
                  onClick: () => {
                    setSearchQuery("");
                    setStatusFilter("all");
                    setTypeFilter("all");
                  },
                }
              : undefined
          }
          variant="refero"
        />
      ) : viewMode === "grid" ? (
        /* Grid View */
        <div className="grid grid-cols-1 gap-6 sm:grid-cols-2 lg:grid-cols-3">
          {filteredProperties.map((property) => (
            <PropertyCard
              key={property.id}
              property={property as any}
              onViewDetails={(prop) => {
                setSelectedProperty(prop);
                setIsDetailOpen(true);
              }}
              onDelete={(prop) => setPropertyToDelete(prop)}
              onMarkSold={(prop) => setSelectedPropForSold(prop)}
            />
          ))}
        </div>
      ) : (
        /* Table View */
        <div className="overflow-hidden rounded-2xl border border-border/80 bg-card shadow-xs">
          <div className="overflow-x-auto">
            <table className="w-full text-left text-sm">
              <thead>
                <tr className="border-b border-border bg-muted/40 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground">
                  <th className="py-3 px-4">Property</th>
                  <th className="py-3 px-4">Type</th>
                  <th className="py-3 px-4">Price</th>
                  <th className="py-3 px-4">Status</th>
                  <th className="py-3 px-4">Inquiries</th>
                  <th className="py-3 px-4">Listed</th>
                  <th className="py-3 px-4 text-center">Actions</th>
                </tr>
              </thead>
              <tbody className="divide-y divide-border/60">
                {filteredProperties.map((property) => (
                  <tr key={property.id} className="hover:bg-muted/40 transition-colors group">
                    <td className="py-3.5 px-4">
                      <div className="flex items-center gap-3">
                        <img
                          src={property.images[0]}
                          alt=""
                          className="size-10 rounded-lg object-cover bg-muted"
                        />
                        <div className="flex flex-col min-w-0">
                          <span className="font-semibold text-foreground truncate max-w-xs group-hover:text-primary transition-colors">
                            {property.title}
                          </span>
                          <span className="text-xs text-muted-foreground truncate">
                            {property.address}, {property.city}
                          </span>
                        </div>
                      </div>
                    </td>
                    <td className="py-3.5 px-4 font-medium text-foreground text-xs">
                      {property.propertyType}
                    </td>
                    <td className="py-3.5 px-4 font-bold text-foreground text-xs">
                      {formatNaira(property.price)}
                    </td>
                    <td className="py-3.5 px-4">
                      <span
                        className={cn(
                          "inline-flex items-center rounded-full px-2.5 py-0.5 text-xs font-semibold capitalize border",
                          getStatusBadge(property.status)
                        )}
                      >
                        {property.status}
                      </span>
                    </td>
                    <td className="py-3.5 px-4 text-xs text-muted-foreground">
                      {property.inquiriesCount} inquiries
                    </td>
                    <td className="py-3.5 px-4 text-xs text-muted-foreground font-mono">
                      {property.listedDate}
                    </td>
                    <td className="py-3.5 px-4 text-center">
                      <div className="flex items-center justify-center gap-1">
                        {property.slug && (
                          <Link
                            href={`/properties/${property.slug}`}
                            target="_blank"
                            className={buttonVariants({
                              variant: "ghost",
                              size: "icon",
                              className: "size-8 rounded-full text-muted-foreground hover:text-foreground",
                            })}
                            title="View public listing"
                          >
                            <ExternalLink className="size-3.5" />
                          </Link>
                        )}
                        <Button
                          variant="ghost"
                          size="icon"
                          onClick={() => {
                            setSelectedProperty(property);
                            setIsDetailOpen(true);
                          }}
                          className="size-8 rounded-full text-muted-foreground hover:text-foreground"
                          title="View property details"
                        >
                          <Eye className="size-4" />
                        </Button>
                        <Link
                          href={`/dashboard/properties/${property.id}/edit`}
                          className={buttonVariants({
                            variant: "ghost",
                            size: "icon",
                            className: "size-8 rounded-full text-muted-foreground hover:text-foreground hover:bg-muted",
                          })}
                          title="Edit listing details and pricing"
                          aria-label="Edit listing"
                        >
                          <Edit className="size-3.5" />
                        </Link>
                        {property.status !== "SOLD" && property.status !== "RENTED" && (
                          <Button
                            variant="ghost"
                            size="icon"
                            onClick={() => setSelectedPropForSold(property)}
                            className="size-8 rounded-full text-primary hover:text-primary/90 hover:bg-primary/10 cursor-pointer"
                            title={property.listingType === "FOR_RENT" || property.listingType === "SHORTLET" ? "Mark listing as rented" : "Mark listing as sold"}
                            aria-label="Mark listing as sold"
                          >
                            <Handshake className="size-4" />
                          </Button>
                        )}
                        <Button
                          variant="ghost"
                          size="icon"
                          onClick={() => setPropertyToDelete(property)}
                          className="size-8 rounded-full text-muted-foreground hover:text-destructive hover:bg-destructive/10"
                          title="Delete listing"
                          aria-label="Delete listing"
                        >
                          <Trash2 className="size-4" />
                        </Button>
                      </div>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </div>
      )}

      {/* Property Detail Drawer */}
      <PropertyDetailSheet
        property={selectedProperty}
        open={isDetailOpen}
        onOpenChange={setIsDetailOpen}
      />

      {/* Add Property Drawer */}
      <AddPropertySheet
        open={isAddOpen}
        onOpenChange={setIsAddOpen}
        onAddProperty={handleAddProperty}
      />

      {/* Mark Sold Modal */}
      {selectedPropForSold && (
        <MarkSoldModal
          isOpen={Boolean(selectedPropForSold)}
          onClose={() => setSelectedPropForSold(null)}
          property={{
            id: selectedPropForSold.id,
            title: selectedPropForSold.title,
            reference_code: selectedPropForSold.referenceCode || selectedPropForSold.reference_code || "JAZ-NG",
            price: Number(selectedPropForSold.price) || 0,
            listing_type: selectedPropForSold.listingType || selectedPropForSold.listing_type || "FOR_SALE",
          }}
          onSuccess={() => {
            const isRental =
              selectedPropForSold.listingType === "FOR_RENT" ||
              selectedPropForSold.listing_type === "FOR_RENT" ||
              selectedPropForSold.listingType === "SHORTLET" ||
              selectedPropForSold.listing_type === "SHORTLET";
            const targetStatus = isRental ? "RENTED" : "SOLD";
            setProperties((prev) =>
              prev.map((p) => (p.id === selectedPropForSold.id ? { ...p, status: targetStatus } : p))
            );
          }}
        />
      )}

      {/* Delete / Archive Confirmation Dialog */}
      <Dialog
        open={Boolean(propertyToDelete)}
        onOpenChange={(open) => {
          if (!open && !isDeleting) {
            setPropertyToDelete(null);
          }
        }}
      >
        <DialogContent className="sm:max-w-md p-6 rounded-2xl bg-card border border-border shadow-xl">
          <DialogHeader className="space-y-3">
            <div className="flex items-center gap-3">
              <div className="flex size-11 items-center justify-center rounded-2xl bg-destructive/10 text-destructive shrink-0">
                <AlertTriangle className="size-5.5" />
              </div>
              <div>
                <DialogTitle className="text-lg font-bold text-foreground">
                  Delete Property Listing?
                </DialogTitle>
                <p className="text-xs text-muted-foreground font-mono mt-0.5">
                  Ref: {propertyToDelete?.referenceCode || propertyToDelete?.reference_code || "JAZ-NG"}
                </p>
              </div>
            </div>
            <DialogDescription className="text-sm text-muted-foreground leading-relaxed pt-1">
              Are you sure you want to delete{" "}
              <span className="font-semibold text-foreground">
                "{propertyToDelete?.title}"
              </span>
              ? This listing will be immediately removed from active search and archived.
            </DialogDescription>
          </DialogHeader>

          <DialogFooter className="mt-6 flex flex-col-reverse sm:flex-row sm:justify-end gap-2.5">
            <Button
              type="button"
              variant="outline"
              disabled={isDeleting}
              onClick={() => setPropertyToDelete(null)}
              className="rounded-xl font-semibold text-xs h-9 px-4"
            >
              Cancel
            </Button>
            <Button
              type="button"
              variant="destructive"
              disabled={isDeleting}
              onClick={confirmDeleteProperty}
              className="rounded-xl font-semibold text-xs h-9 px-4 gap-2 shadow-xs"
            >
              {isDeleting ? (
                <>
                  <Loader2 className="size-3.5 animate-spin" />
                  <span>Deleting...</span>
                </>
              ) : (
                <>
                  <Trash2 className="size-3.5" />
                  <span>Yes, Delete Property</span>
                </>
              )}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
}
