"use client";

import React, { useState, useRef, useMemo, useEffect } from "react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { DotsThree, Plus, PencilSimple, Trash, ArrowSquareOut, List, MapTrifold, MagnifyingGlass, X, ImageSquare, SquaresFour, CaretLeft, CaretRight } from '@/lib/icons';
import { toast } from "sonner";

import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import {
  Table, TableBody, TableCell, TableHead, TableHeader, TableRow,
} from "@/components/ui/table";
import {
  DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { deletePropertyAction } from "@/lib/appwrite/property-actions";
import { PropertyFormSheet } from "./property-form-sheet";
import { ImageLightbox } from "./image-lightbox";
import { DeleteConfirmDialog } from "@/components/ui/delete-confirm-dialog";
import { PropertiesMapView } from "@/components/map/properties-map-view";
import { getPropertyImagePreviewUrl, parseImageIds } from "@/lib/appwrite/storage-utils";
import { UsageBadge } from "@/components/ui/usage-badge";
import type { Property, PropertyStatus } from "@/lib/appwrite/schema";
import {
  PROPERTY_STATUS_LABELS,
  PROPERTY_TYPE_LABELS,
  LISTING_TYPE_LABELS,
} from "@/lib/appwrite/schema";

interface PropertiesClientProps {
  initialProperties: Property[];
  isOwner?: boolean;
  usageLimit?: { current: number; limit: number };
  maxImagesPerProperty?: number;
}

type ViewMode = "list" | "gallery" | "map";

export function PropertiesClient({ initialProperties, isOwner, usageLimit, maxImagesPerProperty }: PropertiesClientProps) {
  const router = useRouter();
  const [properties, setProperties] = useState(initialProperties);
  const [sheetOpen, setSheetOpen] = useState(false);
  const [editing, setEditing] = useState<Property | null>(null);
  const [viewMode, setViewMode] = useState<ViewMode>("list");
  const [selectedId, setSelectedId] = useState<string | null>(null);
  const [deleteTarget, setDeleteTarget] = useState<Property | null>(null);
  const [statusFilter, setStatusFilter] = useState<PropertyStatus | "all">("all");
  const [searchQuery, setSearchQuery] = useState("");
  const rowRefs = useRef<Record<string, HTMLTableRowElement>>({});
  const cardRefs = useRef<Record<string, HTMLDivElement>>({});

  useEffect(() => {
    const open = () => { setEditing(null); setSheetOpen(true); };
    const close = () => setSheetOpen(false);
    window.addEventListener("kovak:open-form-properties", open);
    window.addEventListener("kovak:close-form-properties", close);
    return () => {
      window.removeEventListener("kovak:open-form-properties", open);
      window.removeEventListener("kovak:close-form-properties", close);
    };
  }, []);

  function openCreate() { setEditing(null); setSheetOpen(true); }
  function openEdit(p: Property) { setEditing(p); setSheetOpen(true); }

  async function doDelete() {
    if (!deleteTarget) return;
    const result = await deletePropertyAction(deleteTarget.$id);
    if (result.ok) {
      setProperties((prev) => prev.filter((x) => x.$id !== deleteTarget.$id));
      setDeleteTarget(null);
      toast.success("İlan silindi.");
    } else {
      toast.error(result.error ?? "Silinemedi.");
    }
  }

  function handleMapSelect(id: string) {
    setSelectedId(id);
    // Scroll the card into view in the list panel
    const card = cardRefs.current[id];
    card?.scrollIntoView({ behavior: "smooth", block: "nearest" });
  }

  function handleCardClick(id: string) {
    setSelectedId(id === selectedId ? null : id);
  }

  const filteredProperties = useMemo(() => {
    let list = properties;
    if (statusFilter !== "all") list = list.filter((p) => p.status === statusFilter);
    if (searchQuery.trim()) {
      const q = searchQuery.toLowerCase();
      list = list.filter((p) =>
        p.title.toLowerCase().includes(q) ||
        (p.city ?? "").toLowerCase().includes(q) ||
        (p.district ?? "").toLowerCase().includes(q),
      );
    }
    return list;
  }, [properties, statusFilter, searchQuery]);

  const mappedCount = filteredProperties.filter((p) => p.mapLat != null && p.mapLng != null).length;

  const parsedImageIds = useMemo(() =>
    Object.fromEntries(properties.map((p) => [p.$id, parseImageIds(p.imageIds)])),
    [properties],
  );

  const { withImages, withoutImages } = useMemo(() => ({
    withImages: filteredProperties.filter((p) => (parsedImageIds[p.$id]?.length ?? 0) > 0),
    withoutImages: filteredProperties.filter((p) => (parsedImageIds[p.$id]?.length ?? 0) === 0),
  }), [filteredProperties, parsedImageIds]);

  const STATUS_TABS: Array<{ key: PropertyStatus | "all"; label: string }> = [
    { key: "all", label: "Tümü" },
    { key: "aktif", label: "Aktif" },
    { key: "rezerve", label: "Rezerve" },
    { key: "pasif", label: "Pasif" },
    { key: "satildi", label: "Satıldı" },
    { key: "kiralandit", label: "Kiralandı" },
  ];

  return (
    <div className="flex flex-col gap-4 flex-1">
      {/* Header */}
      <div className="flex items-center justify-between gap-3 flex-wrap">
        <div>
          <h1 className="text-2xl font-bold">İlanlar</h1>
          {viewMode === "map" && mappedCount < filteredProperties.length && (
            <p className="text-xs text-muted-foreground mt-0.5">
              {mappedCount} / {filteredProperties.length} ilanın koordinatı var
            </p>
          )}
        </div>
        <div className="flex items-center gap-2 flex-wrap">
          {isOwner && usageLimit && (
            <UsageBadge current={usageLimit.current} limit={usageLimit.limit} label="ilan" />
          )}
          {/* View toggle */}
          <div className="flex rounded-md border overflow-hidden">
            {([
              { mode: "list" as ViewMode, icon: List, label: "Liste" },
              { mode: "gallery" as ViewMode, icon: SquaresFour, label: "Galeri" },
              { mode: "map" as ViewMode, icon: MapTrifold, label: "Harita" },
            ]).map(({ mode, icon: Icon, label }, i) => (
              <button
                key={mode}
                type="button"
                onClick={() => setViewMode(mode)}
                className={`flex items-center gap-1.5 px-3 py-1.5 text-sm transition-colors ${i > 0 ? "border-l" : ""} ${
                  viewMode === mode
                    ? "bg-primary text-primary-foreground"
                    : "bg-background text-muted-foreground hover:text-foreground"
                }`}
              >
                <Icon className="size-3.5" />
                <span className="hidden sm:inline">{label}</span>
              </button>
            ))}
          </div>
          <Button onClick={openCreate} size="sm" data-tour="properties-add">
            <Plus className="mr-1.5 size-4" />
            Yeni İlan
          </Button>
        </div>
      </div>

      {/* Filter bar */}
      <div data-tour="properties-filters" className="flex flex-col gap-2 sm:flex-row sm:items-center">
        {/* Status tabs */}
        <div className="flex overflow-x-auto gap-1 shrink-0">
          {STATUS_TABS.map(({ key, label }) => {
            const count = key === "all" ? properties.length : properties.filter((p) => p.status === key).length;
            if (key !== "all" && count === 0) return null;
            return (
              <button
                key={key}
                type="button"
                onClick={() => setStatusFilter(key)}
                className={`shrink-0 px-3 py-1 text-xs rounded-full font-medium transition-colors ${
                  statusFilter === key
                    ? "bg-primary text-primary-foreground"
                    : "bg-muted text-muted-foreground hover:text-foreground"
                }`}
              >
                {label} <span className="opacity-70">{count}</span>
              </button>
            );
          })}
        </div>
        {/* MagnifyingGlass */}
        <div className="relative sm:ml-auto sm:w-56">
          <MagnifyingGlass className="absolute left-2.5 top-1/2 -translate-y-1/2 size-3.5 text-muted-foreground" />
          <input
            type="text"
            placeholder="Başlık veya şehir ara…"
            value={searchQuery}
            onChange={(e) => setSearchQuery(e.target.value)}
            className="w-full border-input bg-background h-8 rounded-md border pl-8 pr-7 text-sm focus:outline-none focus:ring-1 focus:ring-ring"
          />
          {searchQuery && (
            <button
              type="button"
              onClick={() => setSearchQuery("")}
              className="absolute right-2 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground"
            >
              <X className="size-3.5" />
            </button>
          )}
        </div>
      </div>

      {/* List view */}
      {viewMode === "list" && (
        <>
          {/* Mobile cards — hidden on md+ */}
          <div className="flex flex-col gap-3 md:hidden">
            {filteredProperties.length === 0 && (
              <p className="text-muted-foreground text-center py-10 text-sm">Henüz ilan yok.</p>
            )}
            {withImages.length > 0 && (
              <>
                {withoutImages.length > 0 && (
                  <ImageGroupHeader hasImages count={withImages.length} />
                )}
                {withImages.map((p) => <MobilePropertyCard key={p.$id} p={p} imageIds={parsedImageIds[p.$id] ?? []} openEdit={openEdit} setDeleteTarget={setDeleteTarget} />)}
              </>
            )}
            {withImages.length > 0 && withoutImages.length > 0 && (
              <ImageGroupHeader hasImages={false} count={withoutImages.length} />
            )}
            {withoutImages.map((p) => <MobilePropertyCard key={p.$id} p={p} imageIds={parsedImageIds[p.$id] ?? []} openEdit={openEdit} setDeleteTarget={setDeleteTarget} />)}
          </div>

          {/* Desktop table — hidden on mobile */}
          <div data-tour="properties-table" className="hidden md:block rounded-md border">
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead className="w-20" />
                  <TableHead>Başlık</TableHead>
                  <TableHead>Tip</TableHead>
                  <TableHead>Tür</TableHead>
                  <TableHead>Şehir</TableHead>
                  <TableHead className="text-right">Fiyat</TableHead>
                  <TableHead>Durum</TableHead>
                  <TableHead />
                </TableRow>
              </TableHeader>
              <TableBody>
                {filteredProperties.length === 0 && (
                  <TableRow>
                    <TableCell colSpan={8} className="text-muted-foreground text-center py-10">
                      Henüz ilan yok.
                    </TableCell>
                  </TableRow>
                )}
                {withImages.length > 0 && withoutImages.length > 0 && (
                  <TableRow className="hover:bg-transparent">
                    <TableCell colSpan={8} className="py-1.5 px-4">
                      <ImageGroupHeader hasImages count={withImages.length} />
                    </TableCell>
                  </TableRow>
                )}
                {withImages.map((p) => (
                  <PropertyTableRow key={p.$id} p={p} imageIds={parsedImageIds[p.$id] ?? []} rowRefs={rowRefs} openEdit={openEdit} setDeleteTarget={setDeleteTarget} router={router} />
                ))}
                {withImages.length > 0 && withoutImages.length > 0 && (
                  <TableRow className="hover:bg-transparent">
                    <TableCell colSpan={8} className="py-1.5 px-4">
                      <ImageGroupHeader hasImages={false} count={withoutImages.length} />
                    </TableCell>
                  </TableRow>
                )}
                {withoutImages.map((p) => (
                  <PropertyTableRow key={p.$id} p={p} imageIds={parsedImageIds[p.$id] ?? []} rowRefs={rowRefs} openEdit={openEdit} setDeleteTarget={setDeleteTarget} router={router} />
                ))}
              </TableBody>
            </Table>
          </div>
        </>
      )}

      {/* Gallery view */}
      {viewMode === "gallery" && (
        <div>
          {filteredProperties.length === 0 && (
            <p className="text-muted-foreground text-center py-10 text-sm">Henüz ilan yok.</p>
          )}
          {withImages.length > 0 && (
            <>
              {withoutImages.length > 0 && <ImageGroupHeader hasImages count={withImages.length} />}
              <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4 mt-3">
                {withImages.map((p) => (
                  <GalleryCard key={p.$id} p={p} imageIds={parsedImageIds[p.$id] ?? []} openEdit={openEdit} setDeleteTarget={setDeleteTarget} />
                ))}
              </div>
            </>
          )}
          {withImages.length > 0 && withoutImages.length > 0 && (
            <div className="mt-6 mb-3">
              <ImageGroupHeader hasImages={false} count={withoutImages.length} />
            </div>
          )}
          {withoutImages.length > 0 && (
            <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4 mt-3">
              {withoutImages.map((p) => (
                <GalleryCard key={p.$id} p={p} imageIds={parsedImageIds[p.$id] ?? []} openEdit={openEdit} setDeleteTarget={setDeleteTarget} />
              ))}
            </div>
          )}
        </div>
      )}

      {/* MapTrifold view — split layout */}
      {viewMode === "map" && (
        <div
          className="flex gap-4 min-h-0"
          style={{ height: "calc(100dvh - var(--header-height) - 8rem)" }}
        >
          {/* Left: scrollable property cards */}
          <div className="w-72 shrink-0 overflow-y-auto space-y-2 pr-1 h-full">
            {filteredProperties.length === 0 && (
              <p className="text-muted-foreground text-sm text-center py-10">Henüz ilan yok.</p>
            )}
            {filteredProperties.map((p) => {
              const coverImageId = (parsedImageIds[p.$id] ?? [])[0];
              const hasCoords = p.mapLat != null && p.mapLng != null;
              const isSelected = selectedId === p.$id;
              return (
                <div
                  key={p.$id}
                  ref={(el) => { if (el) cardRefs.current[p.$id] = el; }}
                  onClick={() => hasCoords && handleCardClick(p.$id)}
                  className={`rounded-lg border bg-card overflow-hidden transition-all ${
                    hasCoords ? "cursor-pointer hover:shadow-md" : "opacity-60"
                  } ${isSelected ? "ring-2 ring-primary shadow-md" : ""}`}
                >
                  {/* Cover image */}
                  {coverImageId && (
                    <div className="h-28 overflow-hidden bg-muted">
                      {/* eslint-disable-next-line @next/next/no-img-element */}
                      <img
                        src={getPropertyImagePreviewUrl(coverImageId, 320, 180)}
                        alt={p.title}
                        className="h-full w-full object-cover"
                      />
                    </div>
                  )}
                  <div className="p-3 space-y-1">
                    <div className="flex items-start justify-between gap-2">
                      <p className="text-sm font-semibold leading-snug line-clamp-2">{p.title}</p>
                      <StatusBadge status={p.status} />
                    </div>
                    <p className="text-xs text-muted-foreground line-clamp-1">
                      {[p.neighborhood, p.district, p.city].filter(Boolean).join(", ")}
                    </p>
                    <div className="flex items-center justify-between">
                      <p className="text-sm font-bold">
                        {p.price.toLocaleString("tr-TR")}
                        <span className="text-xs font-normal text-muted-foreground ml-1">{p.currency ?? "TRY"}</span>
                      </p>
                      <div className="flex gap-1">
                        {p.roomCount && (
                          <span className="text-xs bg-muted text-muted-foreground px-1.5 py-0.5 rounded">
                            {p.roomCount}
                          </span>
                        )}
                        {p.netM2 && (
                          <span className="text-xs bg-muted text-muted-foreground px-1.5 py-0.5 rounded">
                            {p.netM2}m²
                          </span>
                        )}
                      </div>
                    </div>
                    <div className="flex items-center justify-between pt-0.5">
                      {!hasCoords && (
                        <span className="text-xs text-muted-foreground">📍 Konum yok</span>
                      )}
                      <Link
                        href={`/properties/${p.$id}`}
                        onClick={(e) => e.stopPropagation()}
                        className="ml-auto text-xs text-primary hover:underline"
                      >
                        Detay →
                      </Link>
                    </div>
                  </div>
                </div>
              );
            })}
          </div>

          {/* Right: map */}
          <div className="flex-1 min-w-0 h-full">
            <PropertiesMapView
              properties={filteredProperties}
              selectedId={selectedId}
              onSelect={handleMapSelect}
            />
          </div>
        </div>
      )}

      <PropertyFormSheet
        open={sheetOpen}
        onOpenChange={setSheetOpen}
        property={editing}
        onSuccess={() => router.refresh()}
        maxImages={maxImagesPerProperty}
        isOwner={isOwner}
      />
      <DeleteConfirmDialog
        open={!!deleteTarget}
        onOpenChange={(v) => { if (!v) setDeleteTarget(null); }}
        title={`"${deleteTarget?.title}" silinsin mi?`}
        description="Bu ilan kalıcı olarak silinecek ve geri alınamaz."
        onConfirm={doDelete}
      />
    </div>
  );
}

/* ── Galeri kartı ── */
function GalleryCard({ p, imageIds, openEdit, setDeleteTarget }: {
  p: Property;
  imageIds: string[];
  openEdit: (p: Property) => void;
  setDeleteTarget: (p: Property) => void;
}) {
  const [idx, setIdx] = useState(0);
  const [lightbox, setLightbox] = useState(false);
  const safeIdx = Math.min(idx, imageIds.length - 1);

  return (
    <div className="rounded-xl border bg-card overflow-hidden flex flex-col group">
      {/* Görsel alanı */}
      <div className="relative aspect-[4/3] bg-muted overflow-hidden">
        {imageIds.length > 0 ? (
          <>
            {/* eslint-disable-next-line @next/next/no-img-element */}
            <img
              src={getPropertyImagePreviewUrl(imageIds[safeIdx], 640, 480)}
              alt={p.title}
              className="h-full w-full object-cover transition-transform duration-300 group-hover:scale-[1.02] cursor-zoom-in"
              onClick={() => setLightbox(true)}
            />
            {imageIds.length > 1 && (
              <>
                <button
                  type="button"
                  onClick={(e) => { e.stopPropagation(); setIdx((i) => (i - 1 + imageIds.length) % imageIds.length); }}
                  className="absolute left-2 top-1/2 -translate-y-1/2 size-7 rounded-full bg-black/40 hover:bg-black/65 text-white flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity"
                >
                  <CaretLeft className="size-3.5" />
                </button>
                <button
                  type="button"
                  onClick={(e) => { e.stopPropagation(); setIdx((i) => (i + 1) % imageIds.length); }}
                  className="absolute right-2 top-1/2 -translate-y-1/2 size-7 rounded-full bg-black/40 hover:bg-black/65 text-white flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity"
                >
                  <CaretRight className="size-3.5" />
                </button>
                <div className="absolute bottom-2 right-2 bg-black/50 text-white text-xs px-1.5 py-0.5 rounded-full tabular-nums opacity-0 group-hover:opacity-100 transition-opacity">
                  {safeIdx + 1}/{imageIds.length}
                </div>
                <div className="absolute bottom-2 left-1/2 -translate-x-1/2 flex gap-1 opacity-0 group-hover:opacity-100 transition-opacity">
                  {imageIds.map((_, i) => (
                    <button
                      key={i}
                      type="button"
                      onClick={(e) => { e.stopPropagation(); setIdx(i); }}
                      className={`size-1.5 rounded-full transition-colors ${i === safeIdx ? "bg-white" : "bg-white/40"}`}
                    />
                  ))}
                </div>
              </>
            )}
          </>
        ) : (
          <Link href={`/properties/${p.$id}`} className="flex h-full items-center justify-center flex-col gap-2">
            <ImageSquare className="size-10 text-muted-foreground/30" />
            <span className="text-xs text-muted-foreground/50">Görsel yok</span>
          </Link>
        )}
        {/* Status badge üstte */}
        <div className="absolute top-2 left-2">
          <StatusBadge status={p.status} />
        </div>
      </div>

      {lightbox && (
        <ImageLightbox
          imageIds={imageIds}
          title={p.title}
          initialIndex={safeIdx}
          onClose={() => setLightbox(false)}
        />
      )}

      {/* Bilgi + aksiyonlar */}
      <div className="p-3 flex flex-col gap-1.5 flex-1">
        <Link href={`/properties/${p.$id}`} className="font-semibold text-sm leading-snug line-clamp-2 hover:underline">
          {p.title}
        </Link>
        <p className="text-xs text-muted-foreground">
          {PROPERTY_TYPE_LABELS[p.propertyType] ?? p.propertyType}
          {" · "}{LISTING_TYPE_LABELS[p.listingType] ?? p.listingType}
          {p.city ? ` · ${p.city}` : ""}
          {p.roomCount ? ` · ${p.roomCount}` : ""}
          {p.netM2 ? ` · ${p.netM2}m²` : ""}
        </p>
        <div className="flex items-center justify-between mt-auto pt-1.5 border-t">
          <p className="text-sm font-bold tabular-nums">
            {p.price.toLocaleString("tr-TR")}
            <span className="text-xs font-normal text-muted-foreground ml-1">{p.currency ?? "TRY"}</span>
          </p>
          <div className="flex items-center gap-0.5">
            <Button variant="ghost" size="icon" className="size-7" onClick={() => openEdit(p)}>
              <PencilSimple className="size-3.5" />
            </Button>
            <Button
              variant="ghost"
              size="icon"
              className="size-7 text-destructive hover:text-destructive"
              onClick={() => setDeleteTarget(p)}
            >
              <Trash className="size-3.5" />
            </Button>
          </div>
        </div>
      </div>
    </div>
  );
}

/* ── Görsel grup ayracı ── */
function ImageGroupHeader({ hasImages, count }: { hasImages: boolean; count: number }) {
  return (
    <div className="flex items-center gap-2">
      <span className={`flex items-center gap-1.5 text-xs font-semibold px-2 py-0.5 rounded-full ${
        hasImages
          ? "bg-emerald-100 text-emerald-700 dark:bg-emerald-900/30 dark:text-emerald-400"
          : "bg-zinc-100 text-zinc-500 dark:bg-zinc-800 dark:text-zinc-400"
      }`}>
        <ImageSquare className="size-3" />
        {hasImages ? "Görselli" : "Görselsiz"}
        <span className="opacity-70 font-normal">({count})</span>
      </span>
      <div className="flex-1 h-px bg-border" />
    </div>
  );
}

/* ── Mobil kart ── */
function MobilePropertyCard({ p, imageIds, openEdit, setDeleteTarget }: {
  p: Property;
  imageIds: string[];
  openEdit: (p: Property) => void;
  setDeleteTarget: (p: Property) => void;
}) {
  const coverImageId = imageIds[0];
  return (
    <div className="rounded-lg border bg-card overflow-hidden">
      {coverImageId && (
        <div className="h-36 overflow-hidden bg-muted">
          {/* eslint-disable-next-line @next/next/no-img-element */}
          <img
            src={getPropertyImagePreviewUrl(coverImageId, 640, 288)}
            alt={p.title}
            className="h-full w-full object-cover"
          />
        </div>
      )}
      <div className="p-3 space-y-2">
        <div className="flex items-start justify-between gap-2">
          <p className="text-sm font-semibold leading-snug line-clamp-2 flex-1">{p.title}</p>
          <StatusBadge status={p.status} />
        </div>
        <p className="text-xs text-muted-foreground">
          {PROPERTY_TYPE_LABELS[p.propertyType] ?? p.propertyType}
          {" · "}{LISTING_TYPE_LABELS[p.listingType] ?? p.listingType}
          {p.city ? ` · ${p.city}` : ""}
          {p.district ? `, ${p.district}` : ""}
          {p.roomCount ? ` · ${p.roomCount}` : ""}
          {p.netM2 ? ` · ${p.netM2}m²` : ""}
        </p>
        <div className="flex items-center justify-between">
          <p className="text-base font-bold tabular-nums">
            {p.price.toLocaleString("tr-TR")}
            <span className="text-xs font-normal text-muted-foreground ml-1">{p.currency ?? "TRY"}</span>
          </p>
          <div className="flex items-center gap-1">
            <Button variant="ghost" size="icon" className="size-8" asChild>
              <Link href={`/properties/${p.$id}`}>
                <ArrowSquareOut className="size-4" />
              </Link>
            </Button>
            <Button variant="ghost" size="icon" className="size-8" onClick={() => openEdit(p)}>
              <PencilSimple className="size-4" />
            </Button>
            <Button
              variant="ghost"
              size="icon"
              className="size-8 text-destructive hover:text-destructive"
              onClick={() => setDeleteTarget(p)}
            >
              <Trash className="size-4" />
            </Button>
          </div>
        </div>
      </div>
    </div>
  );
}

/* ── Tablo satırı ── */
function PropertyTableRow({ p, imageIds, rowRefs, openEdit, setDeleteTarget, router }: {
  p: Property;
  imageIds: string[];
  rowRefs: React.MutableRefObject<Record<string, HTMLTableRowElement>>;
  openEdit: (p: Property) => void;
  setDeleteTarget: (p: Property) => void;
  router: ReturnType<typeof useRouter>;
}) {
  const coverImageId = imageIds[0];
  const [lightbox, setLightbox] = useState(false);

  return (
    <>
    <TableRow
      ref={(el) => { if (el) rowRefs.current[p.$id] = el; }}
      onClick={() => router.push(`/properties/${p.$id}`)}
      className="cursor-pointer"
    >
      <TableCell className="py-1.5 pl-4 pr-2 w-20">
        <div
          onClick={(e) => { e.stopPropagation(); coverImageId && setLightbox(true); }}
          className={`w-16 h-12 rounded overflow-hidden bg-muted flex items-center justify-center shrink-0 ${coverImageId ? "cursor-zoom-in" : ""}`}
        >
          {coverImageId ? (
            // eslint-disable-next-line @next/next/no-img-element
            <img
              src={getPropertyImagePreviewUrl(coverImageId, 128, 96)}
              alt=""
              className="h-full w-full object-cover"
            />
          ) : (
            <ImageSquare className="size-5 text-muted-foreground/30" />
          )}
        </div>
      </TableCell>
      <TableCell className="font-medium max-w-[200px] truncate">{p.title}</TableCell>
      <TableCell>{PROPERTY_TYPE_LABELS[p.propertyType] ?? p.propertyType}</TableCell>
      <TableCell>{LISTING_TYPE_LABELS[p.listingType] ?? p.listingType}</TableCell>
      <TableCell>{[p.city, p.district].filter(Boolean).join(", ")}</TableCell>
      <TableCell className="text-right tabular-nums">
        {p.price.toLocaleString("tr-TR")} {p.currency ?? "TRY"}
      </TableCell>
      <TableCell>
        <StatusBadge status={p.status} />
      </TableCell>
      <TableCell onClick={(e) => e.stopPropagation()}>
        <DropdownMenu>
          <DropdownMenuTrigger asChild>
            <Button variant="ghost" size="icon" className="size-8">
              <DotsThree className="size-4" />
            </Button>
          </DropdownMenuTrigger>
          <DropdownMenuContent align="end">
            <DropdownMenuItem asChild>
              <Link href={`/properties/${p.$id}`}>
                <ArrowSquareOut className="mr-2 size-4" />
                Detay
              </Link>
            </DropdownMenuItem>
            <DropdownMenuItem onClick={() => openEdit(p)}>
              <PencilSimple className="mr-2 size-4" />
              Düzenle
            </DropdownMenuItem>
            <DropdownMenuItem
              onClick={() => setDeleteTarget(p)}
              className="text-destructive focus:text-destructive"
            >
              <Trash className="mr-2 size-4" />
              Sil
            </DropdownMenuItem>
          </DropdownMenuContent>
        </DropdownMenu>
      </TableCell>
    </TableRow>
    {lightbox && (
      <ImageLightbox
        imageIds={imageIds}
        title={p.title}
        initialIndex={0}
        onClose={() => setLightbox(false)}
      />
    )}
    </>
  );
}

function StatusBadge({ status }: { status: string }) {
  const map: Record<string, "default" | "secondary" | "outline" | "destructive"> = {
    aktif: "default",
    rezerve: "secondary",
    pasif: "secondary",
    satildi: "outline",
    kiralandit: "outline",
  };
  return (
    <Badge variant={map[status] ?? "secondary"} className="shrink-0 text-xs">
      {PROPERTY_STATUS_LABELS[status as keyof typeof PROPERTY_STATUS_LABELS] ?? status}
    </Badge>
  );
}
