"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";
import Link from "next/link";
import { ArrowLeft, PencilSimple, MapPin, ImageSquare, Plus, FileText, ClipboardText, Users, CaretLeft, CaretRight, X, Phone, Envelope, BellRinging, Checks } from '@/lib/icons';

import { Button } from "@/components/ui/button";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { PropertyFormSheet } from "./property-form-sheet";
import { PropertyImageSheet } from "./property-image-sheet";
import { ImageLightbox } from "./image-lightbox";
import { PropertyMapView } from "@/components/map/property-map-view";
import { getPropertyImagePreviewUrl } from "@/lib/appwrite/storage-utils";
import {
  PROPERTY_TYPE_LABELS,
  LISTING_TYPE_LABELS,
  PROPERTY_STATUS_LABELS,
  ACTIVITY_TYPE_LABELS,
  type Property,
  type PropertyMatch,
  type CustomerSearch,
  type Customer,
  type Activity,
} from "@/lib/appwrite/schema";
import { getPropertyImageUrl } from "@/lib/appwrite/storage-utils";

interface Props {
  property: Property;
  matches: PropertyMatch[];
  activities: Activity[];
  imageIds: string[];
  customers: Customer[];
  searches: CustomerSearch[];
}

const STATUS_COLOR: Record<string, string> = {
  aktif:      "bg-emerald-100 text-emerald-700 dark:bg-emerald-900/30 dark:text-emerald-400",
  pasif:      "bg-zinc-100 text-zinc-600 dark:bg-zinc-800 dark:text-zinc-400",
  satildi:    "bg-blue-100 text-blue-700 dark:bg-blue-900/30 dark:text-blue-400",
  kiralandit: "bg-orange-100 text-orange-700 dark:bg-orange-900/30 dark:text-orange-400",
  rezerve:    "bg-purple-100 text-purple-700 dark:bg-purple-900/30 dark:text-purple-400",
};

export function PropertyDetailClient({ property, matches, activities, imageIds, customers, searches }: Props) {
  const customerMap = Object.fromEntries(customers.map((c) => [c.$id, c]));
  const searchMap = Object.fromEntries(searches.map((s) => [s.$id, s]));
  const router = useRouter();
  const [editOpen, setEditOpen] = useState(false);
  const [imageOpen, setImageOpen] = useState(false);

  const location = [property.neighborhood, property.district, property.city]
    .filter(Boolean).join(", ");

  const formattedPrice = new Intl.NumberFormat("tr-TR").format(property.price);

  return (
    <div className="flex flex-1 flex-col gap-4 p-4 md:p-6 overflow-x-hidden">

      {/* Üst bar: geri + düzenle */}
      <div className="flex items-center justify-between gap-3">
        <Link
          href="/properties"
          className="flex items-center gap-1.5 text-sm text-muted-foreground hover:text-foreground transition-colors"
        >
          <ArrowLeft className="size-4" />
          İlanlar
        </Link>
        <Button size="sm" variant="outline" onClick={() => setEditOpen(true)} className="px-2 sm:px-3">
          <PencilSimple className="size-3.5" />
          <span className="hidden sm:inline">Düzenle</span>
        </Button>
      </div>

      {/* Başlık */}
      <div>
        <h1 className="text-xl sm:text-2xl font-bold leading-tight">{property.title}</h1>
        {location && (
          <p className="flex items-center gap-1 text-sm text-muted-foreground mt-1">
            <MapPin className="size-3.5 shrink-0" />
            {location}
          </p>
        )}
      </div>

      {/* HERO: galeri (sol) + bilgi kartı (sağ) */}
      <div className="grid gap-4 lg:grid-cols-3 lg:items-start">

        {/* Galeri — her zaman solda, fotoğraf yoksa placeholder */}
        <div className="lg:col-span-2">
          <Gallery
            imageIds={imageIds}
            title={property.title}
            type={property.propertyType}
            onAddPhoto={() => setImageOpen(true)}
          />
        </div>

        {/* Bilgi kartı — sağda */}
        <div className="rounded-xl border bg-card p-5 space-y-4">
          {/* Status */}
          <span className={`inline-flex items-center rounded-full px-2.5 py-0.5 text-xs font-medium ${STATUS_COLOR[property.status] ?? "bg-zinc-100 text-zinc-600"}`}>
            {PROPERTY_STATUS_LABELS[property.status] ?? property.status}
          </span>

          {/* Fiyat */}
          <div>
            <div className="flex items-baseline gap-2 flex-wrap">
              <span className="text-3xl font-bold tabular-nums">{formattedPrice}</span>
              <span className="text-muted-foreground text-sm">{property.currency ?? "TRY"}</span>
            </div>
            <p className="text-sm text-muted-foreground mt-0.5">
              {LISTING_TYPE_LABELS[property.listingType]} · {PROPERTY_TYPE_LABELS[property.propertyType]}
            </p>
          </div>

          {/* Temel özellikler */}
          <div className="grid grid-cols-2 gap-x-4 gap-y-2.5 pt-4 border-t text-sm">
            {property.roomCount   && <Spec label="Oda"        value={property.roomCount} />}
            {property.netM2       && <Spec label="Net m²"     value={`${property.netM2} m²`} />}
            {property.grossM2     && <Spec label="Brüt m²"    value={`${property.grossM2} m²`} />}
            {property.floor != null       && <Spec label="Kat"        value={String(property.floor)} />}
            {property.totalFloors != null && <Spec label="Top. kat"   value={String(property.totalFloors)} />}
            {property.buildingAge != null && <Spec label="Bina yaşı"  value={`${property.buildingAge} yıl`} />}
          </div>

          {/* Adres */}
          {(property.address || property.mapLat != null) && (
            <div className="pt-3 border-t space-y-1.5 text-sm">
              {property.address && (
                <p className="text-muted-foreground leading-snug">{property.address}</p>
              )}
              {property.mapLat != null && property.mapLng != null && (
                <a
                  href={`https://www.google.com/maps?q=${property.mapLat},${property.mapLng}`}
                  target="_blank"
                  rel="noopener noreferrer"
                  className="text-xs text-blue-600 hover:underline inline-flex items-center gap-1"
                >
                  Google Maps&apos;te aç ↗
                </a>
              )}
            </div>
          )}
        </div>
      </div>

      {/* ALT KISIM: tabbed content */}
      <Tabs defaultValue={property.description ? "aciklama" : property.mapLat != null ? "konum" : activities.length > 0 ? "aktiviteler" : "musteriler"}>
        <TabsList className="flex h-auto w-full gap-1.5 rounded-xl bg-muted/60 p-1.5 flex-wrap">
          {property.description && (
            <TabsTrigger value="aciklama" className="flex items-center gap-1.5 rounded-lg px-3.5 py-2 text-sm font-medium data-[state=active]:bg-background data-[state=active]:shadow-sm">
              <FileText className="size-3.5" />
              Açıklama
            </TabsTrigger>
          )}
          {property.mapLat != null && property.mapLng != null && (
            <TabsTrigger value="konum" className="flex items-center gap-1.5 rounded-lg px-3.5 py-2 text-sm font-medium data-[state=active]:bg-background data-[state=active]:shadow-sm">
              <MapPin className="size-3.5" />
              Konum
            </TabsTrigger>
          )}
          {activities.length > 0 && (
            <TabsTrigger value="aktiviteler" className="flex items-center gap-1.5 rounded-lg px-3.5 py-2 text-sm font-medium data-[state=active]:bg-background data-[state=active]:shadow-sm">
              <ClipboardText className="size-3.5" />
              Aktiviteler
              <span className="ml-0.5 text-xs opacity-60">({activities.length})</span>
            </TabsTrigger>
          )}
          <TabsTrigger value="musteriler" className="flex items-center gap-1.5 rounded-lg px-3.5 py-2 text-sm font-medium data-[state=active]:bg-background data-[state=active]:shadow-sm">
            <Users className="size-3.5" />
            Müşteriler
            {matches.length > 0 && (
              <span className="ml-0.5 text-xs opacity-60">({matches.length})</span>
            )}
          </TabsTrigger>
        </TabsList>

        {property.description && (
          <TabsContent value="aciklama" className="mt-4">
            <p className="text-sm text-muted-foreground whitespace-pre-wrap leading-relaxed">
              {property.description}
            </p>
          </TabsContent>
        )}

        {property.mapLat != null && property.mapLng != null && (
          <TabsContent value="konum" className="mt-4">
            <div className="rounded-xl border overflow-hidden">
              <PropertyMapView
                lat={property.mapLat}
                lng={property.mapLng}
                title={property.title}
                className="h-64 sm:h-80 rounded-none border-0"
              />
            </div>
          </TabsContent>
        )}

        {activities.length > 0 && (
          <TabsContent value="aktiviteler" className="mt-4">
            <div className="space-y-3">
              {activities.map((a) => (
                <div key={a.$id} className="flex items-start gap-3 text-sm border-b pb-3 last:border-0 last:pb-0">
                  <span className="shrink-0 mt-0.5 text-xs text-muted-foreground border rounded px-1.5 py-0.5">
                    {ACTIVITY_TYPE_LABELS[a.type] ?? a.type}
                  </span>
                  <div className="min-w-0 flex-1">
                    <p className="font-medium truncate">{a.title}</p>
                    {a.description && (
                      <p className="text-xs text-muted-foreground line-clamp-2 mt-0.5">{a.description}</p>
                    )}
                  </div>
                  <span className="shrink-0 text-xs text-muted-foreground">
                    {new Date(a.$createdAt).toLocaleDateString("tr-TR")}
                  </span>
                </div>
              ))}
            </div>
          </TabsContent>
        )}

        <TabsContent value="musteriler" className="mt-4">
          {matches.length === 0 ? (
            <p className="text-sm text-muted-foreground">Henüz eşleşme yok.</p>
          ) : (
            <div className="space-y-3">
              {matches.map((m) => {
                const customer = customerMap[m.customerId];
                const search = searchMap[m.searchId];
                return (
                  <MatchCard
                    key={m.$id}
                    match={m}
                    customer={customer}
                    search={search}
                  />
                );
              })}
            </div>
          )}
        </TabsContent>
      </Tabs>

      <PropertyFormSheet
        open={editOpen}
        onOpenChange={setEditOpen}
        property={property}
        onSuccess={() => router.refresh()}
      />
      <PropertyImageSheet
        open={imageOpen}
        onOpenChange={setImageOpen}
        propertyId={property.$id}
        initialImageIds={imageIds}
        onSuccess={() => router.refresh()}
      />
    </div>
  );
}

/* ── Galeri ── */
function Gallery({ imageIds, title, type, onAddPhoto }: {
  imageIds: string[];
  title: string;
  type: string;
  onAddPhoto: () => void;
}) {
  const [active, setActive] = useState(0);
  const [lightbox, setLightbox] = useState(false);

  if (imageIds.length === 0) {
    return (
      <div className="aspect-[16/10] rounded-xl border-2 border-dashed border-muted-foreground/20 bg-muted/30 flex flex-col items-center justify-center gap-4">
        <div className="size-16 rounded-full bg-background border flex items-center justify-center">
          <ImageSquare className="size-7 text-muted-foreground/50" />
        </div>
        <div className="text-center">
          <p className="text-sm font-medium">Fotoğraf eklenmedi</p>
          <p className="text-xs text-muted-foreground mt-0.5">
            {PROPERTY_TYPE_LABELS[type as keyof typeof PROPERTY_TYPE_LABELS] ?? type} · Görsel henüz yüklenmemiş
          </p>
        </div>
        <Button variant="outline" size="sm" onClick={onAddPhoto}>
          <Plus className="size-3.5" />
          Fotoğraf Ekle
        </Button>
      </div>
    );
  }

  const safeActive = Math.min(active, imageIds.length - 1);
  const prev = () => setActive((i) => (i - 1 + imageIds.length) % imageIds.length);
  const next = () => setActive((i) => (i + 1) % imageIds.length);

  return (
    <div className="space-y-2">
      {/* Ana görsel */}
      <div className="relative aspect-[16/10] rounded-xl overflow-hidden border bg-black group">
        {/* eslint-disable-next-line @next/next/no-img-element */}
        <img
          src={getPropertyImageUrl(imageIds[safeActive])}
          alt={`${title} ${safeActive + 1}`}
          className="w-full h-full object-contain cursor-zoom-in"
          onClick={() => setLightbox(true)}
        />

        {/* Sayaç */}
        <div className="absolute bottom-2.5 right-3 bg-black/50 text-white text-xs font-medium px-2 py-0.5 rounded-full tabular-nums">
          {safeActive + 1} / {imageIds.length}
        </div>

        {/* Ok butonları — birden fazla görsel varsa */}
        {imageIds.length > 1 && (
          <>
            <button
              type="button"
              onClick={prev}
              className="absolute left-2 top-1/2 -translate-y-1/2 size-8 rounded-full bg-black/40 hover:bg-black/65 text-white flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity"
              aria-label="Önceki"
            >
              <CaretLeft className="size-4" />
            </button>
            <button
              type="button"
              onClick={next}
              className="absolute right-2 top-1/2 -translate-y-1/2 size-8 rounded-full bg-black/40 hover:bg-black/65 text-white flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity"
              aria-label="Sonraki"
            >
              <CaretRight className="size-4" />
            </button>
          </>
        )}
      </div>

      {/* Thumbnail şeridi */}
      {imageIds.length > 1 && (
        <div className="flex gap-1.5 overflow-x-auto pb-0.5 scrollbar-hide">
          {imageIds.map((id, i) => (
            <button
              key={id}
              type="button"
              onClick={() => setActive(i)}
              className={`relative shrink-0 w-16 h-12 sm:w-20 sm:h-14 rounded-md overflow-hidden border-2 transition-all ${
                i === safeActive
                  ? "border-primary"
                  : "border-transparent hover:border-muted-foreground/40"
              }`}
            >
              {/* eslint-disable-next-line @next/next/no-img-element */}
              <img
                src={getPropertyImagePreviewUrl(id, 200, 150)}
                alt={`${title} ${i + 1}`}
                className="w-full h-full object-cover"
              />
              {i !== safeActive && (
                <div className="absolute inset-0 bg-black/20" />
              )}
            </button>
          ))}
        </div>
      )}

      {lightbox && (
        <ImageLightbox
          imageIds={imageIds}
          title={title}
          initialIndex={safeActive}
          onClose={() => setLightbox(false)}
        />
      )}
    </div>
  );
}

/* ── Yardımcı bileşenler ── */
function Spec({ label, value }: { label: string; value: string }) {
  return (
    <div>
      <p className="text-xs text-muted-foreground">{label}</p>
      <p className="font-semibold">{value}</p>
    </div>
  );
}


function MatchCard({ match, customer, search }: {
  match: PropertyMatch;
  customer?: Customer;
  search?: CustomerSearch;
}) {
  const fmt = (n: number) => n.toLocaleString("tr-TR");

  const criteria: string[] = [];
  if (search?.listingType) criteria.push(LISTING_TYPE_LABELS[search.listingType] ?? search.listingType);
  if (search?.propertyTypes) {
    try {
      const types = JSON.parse(search.propertyTypes) as string[];
      types.forEach((t) => criteria.push(PROPERTY_TYPE_LABELS[t as keyof typeof PROPERTY_TYPE_LABELS] ?? t));
    } catch { /* ignore */ }
  }
  if (search?.roomCounts) {
    try {
      const rooms = JSON.parse(search.roomCounts) as string[];
      if (rooms.length) criteria.push(`${rooms.join(", ")} oda`);
    } catch { /* ignore */ }
  }
  if (search?.minPrice != null || search?.maxPrice != null) {
    const min = search.minPrice != null ? `${fmt(search.minPrice)} ₺` : null;
    const max = search.maxPrice != null ? `${fmt(search.maxPrice)} ₺` : null;
    criteria.push(min && max ? `${min} – ${max}` : min ? `min ${min}` : `max ${max!}`);
  }
  if (search?.minM2 != null || search?.maxM2 != null) {
    const min = search.minM2 != null ? `${search.minM2} m²` : null;
    const max = search.maxM2 != null ? `${search.maxM2} m²` : null;
    criteria.push(min && max ? `${min} – ${max}` : min ? `min ${min}` : `max ${max!}`);
  }
  if (search?.cities) {
    try {
      const cities = JSON.parse(search.cities) as string[];
      if (cities.length) criteria.push(cities.join(", "));
    } catch { /* ignore */ }
  }
  if (search?.districts) {
    try {
      const districts = JSON.parse(search.districts) as string[];
      if (districts.length) criteria.push(districts.join(", "));
    } catch { /* ignore */ }
  }

  return (
    <div className={`rounded-lg border p-3 space-y-2.5 ${match.notified !== true ? "bg-amber-50/30 dark:bg-amber-950/10 border-amber-200/50 dark:border-amber-800/30" : ""}`}>
      {/* Üst satır: isim + puan + bildirim durumu */}
      <div className="flex items-start justify-between gap-2">
        <div className="min-w-0">
          <Link
            href={`/customers/${match.customerId}`}
            className="font-medium text-sm hover:text-primary hover:underline transition-colors"
          >
            {customer?.name ?? match.customerId}
          </Link>
          <div className="flex flex-wrap gap-x-3 gap-y-0.5 mt-0.5">
            {customer?.phone && (
              <a href={`tel:${customer.phone}`} className="flex items-center gap-1 text-xs text-foreground/80 hover:text-primary transition-colors">
                <Phone className="size-3 shrink-0" />
                {customer.phone}
              </a>
            )}
            {customer?.email && (
              <a href={`mailto:${customer.email}`} className="flex items-center gap-1 text-xs text-muted-foreground hover:text-primary transition-colors">
                <Envelope className="size-3 shrink-0" />
                {customer.email}
              </a>
            )}
          </div>
        </div>
        <div className="flex items-center gap-2 shrink-0">
          {match.notified === true ? (
            <span className="flex items-center gap-1 text-xs text-muted-foreground">
              <Checks className="size-3.5 text-green-500" />
              Bildirildi
            </span>
          ) : (
            <span className="flex items-center gap-1 text-xs text-amber-600 font-medium">
              <BellRinging className="size-3.5" />
              Bekliyor
            </span>
          )}
          <ScoreBadge score={match.score} />
        </div>
      </div>

      {/* Arama kriterleri */}
      {criteria.length > 0 && (
        <div className="flex flex-wrap gap-1.5 pt-1.5 border-t border-dashed">
          {criteria.map((c, i) => (
            <span key={i} className="inline-flex items-center rounded-md bg-muted px-2 py-0.5 text-xs text-muted-foreground">
              {c}
            </span>
          ))}
        </div>
      )}
      {search?.notes && (
        <p className="text-xs text-muted-foreground italic border-t pt-1.5">{search.notes}</p>
      )}
    </div>
  );
}

function ScoreBadge({ score }: { score?: number | null }) {
  const s = score ?? 0;
  const color =
    s >= 80 ? "bg-emerald-100 text-emerald-700" :
    s >= 60 ? "bg-blue-100 text-blue-700" :
    s >= 40 ? "bg-yellow-100 text-yellow-700" :
              "bg-zinc-100 text-zinc-500";
  return (
    <span className={`inline-flex shrink-0 items-center rounded-full px-2 py-0.5 text-xs font-semibold ${color}`}>
      {s}
    </span>
  );
}
