export const dynamic = "force-dynamic";

import { notFound } from "next/navigation";
import Link from "next/link";
import { ArrowLeft, Phone, Envelope, CalendarCheck, Tag } from '@/lib/icons';
import { Query } from "node-appwrite";

import { requireTenant } from "@/lib/appwrite/tenant-guard";
import { getCustomer } from "@/lib/appwrite/customer-queries";
import {
  DATABASE_ID, TABLES,
  CUSTOMER_TYPE_LABELS, CUSTOMER_STAGE_LABELS, CUSTOMER_SOURCE_LABELS,
  ACTIVITY_TYPE_LABELS, PROPERTY_TYPE_LABELS, LISTING_TYPE_LABELS,
  type Activity, type CustomerSearch, type PropertyMatch, type Property,
} from "@/lib/appwrite/schema";
import { createAdminClient } from "@/lib/appwrite/server";
import { Badge } from "@/components/ui/badge";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";

interface Props {
  params: Promise<{ id: string }>;
}

const STAGE_COLORS: Record<string, string> = {
  ilk_temas: "bg-slate-100 text-slate-700",
  aktif_arama: "bg-blue-100 text-blue-700",
  teklif: "bg-amber-100 text-amber-700",
  sozlesme: "bg-purple-100 text-purple-700",
  kapandi: "bg-emerald-100 text-emerald-700",
};

export default async function CustomerDetailPage({ params }: Props) {
  const { id } = await params;
  const ctx = await requireTenant();
  const { tablesDB } = createAdminClient();

  const customer = await getCustomer(id, ctx.tenantId);
  if (!customer) notFound();

  const [activitiesRes, searchesRes, matchesRes] = await Promise.all([
    tablesDB.listRows({
      databaseId: DATABASE_ID,
      tableId: TABLES.activities,
      queries: [
        Query.equal("customerId", id),
        Query.equal("tenantId", ctx.tenantId),
        Query.orderDesc("$createdAt"),
        Query.limit(20),
      ],
    }),
    tablesDB.listRows({
      databaseId: DATABASE_ID,
      tableId: TABLES.customerSearches,
      queries: [
        Query.equal("customerId", id),
        Query.equal("tenantId", ctx.tenantId),
        Query.limit(20),
      ],
    }),
    tablesDB.listRows({
      databaseId: DATABASE_ID,
      tableId: TABLES.propertyMatches,
      queries: [
        Query.equal("customerId", id),
        Query.equal("tenantId", ctx.tenantId),
        Query.orderDesc("score"),
        Query.limit(20),
      ],
    }),
  ]);

  const activities = JSON.parse(JSON.stringify(activitiesRes.rows)) as Activity[];
  const searches = JSON.parse(JSON.stringify(searchesRes.rows)) as CustomerSearch[];
  const matches = JSON.parse(JSON.stringify(matchesRes.rows)) as PropertyMatch[];

  // Fetch matched properties for display
  const matchedPropertyIds = [...new Set(matches.map((m) => m.propertyId))];
  const propertiesMap: Record<string, Property> = {};
  if (matchedPropertyIds.length > 0) {
    const propsRes = await tablesDB.listRows({
      databaseId: DATABASE_ID,
      tableId: TABLES.properties,
      queries: [
        Query.equal("$id", matchedPropertyIds.slice(0, 25)),
        Query.limit(25),
      ],
    });
    for (const row of propsRes.rows) {
      const p = row as unknown as Property;
      propertiesMap[p.$id] = p;
    }
  }

  const stageKey = customer.stage ?? "ilk_temas";

  function parseJsonList(json?: string | null): string[] {
    if (!json) return [];
    try { return JSON.parse(json) as string[]; } catch { return [json]; }
  }

  return (
    <div className="flex flex-1 flex-col gap-6 p-4 md:p-6 max-w-5xl">
      {/* Back */}
      <div>
        <Link href="/customers" className="text-muted-foreground hover:text-foreground flex items-center gap-1 text-sm">
          <ArrowLeft className="size-4" />
          Müşteriler
        </Link>
      </div>

      {/* Header */}
      <div className="flex items-start justify-between gap-4 flex-wrap">
        <div className="space-y-1">
          <h1 className="text-2xl font-bold">{customer.name}</h1>
          <div className="flex items-center gap-2 flex-wrap">
            <Badge variant="outline">{CUSTOMER_TYPE_LABELS[customer.type] ?? customer.type}</Badge>
            <span className={`text-xs font-medium px-2 py-0.5 rounded-full ${STAGE_COLORS[stageKey] ?? STAGE_COLORS.ilk_temas}`}>
              {CUSTOMER_STAGE_LABELS[stageKey as keyof typeof CUSTOMER_STAGE_LABELS] ?? stageKey}
            </span>
            {customer.source && (
              <span className="text-xs text-muted-foreground flex items-center gap-1">
                <Tag className="size-3" />
                {CUSTOMER_SOURCE_LABELS[customer.source] ?? customer.source}
              </span>
            )}
          </div>
        </div>
        <Link
          href="/customers"
          className="text-sm text-primary hover:underline"
        >
          Düzenle →
        </Link>
      </div>

      <div className="grid gap-6 md:grid-cols-3">
        {/* Left: info + searches + activities */}
        <div className="md:col-span-2 space-y-6">
          {/* Contact card */}
          <Card>
            <CardHeader className="pb-3">
              <CardTitle className="text-sm">İletişim</CardTitle>
            </CardHeader>
            <CardContent className="space-y-2">
              {customer.phone && (
                <div className="flex items-center gap-2 text-sm">
                  <Phone className="size-4 text-muted-foreground shrink-0" />
                  <a href={`tel:${customer.phone}`} className="hover:underline">{customer.phone}</a>
                </div>
              )}
              {customer.email && (
                <div className="flex items-center gap-2 text-sm">
                  <Envelope className="size-4 text-muted-foreground shrink-0" />
                  <a href={`mailto:${customer.email}`} className="hover:underline">{customer.email}</a>
                </div>
              )}
              {customer.nextFollowUpDate && (
                <div className="flex items-center gap-2 text-sm">
                  <CalendarCheck className="size-4 text-muted-foreground shrink-0" />
                  <span>Takip: {new Date(customer.nextFollowUpDate).toLocaleDateString("tr-TR", { day: "numeric", month: "long", year: "numeric" })}</span>
                </div>
              )}
              {!customer.phone && !customer.email && !customer.nextFollowUpDate && (
                <p className="text-sm text-muted-foreground">İletişim bilgisi yok.</p>
              )}
              {customer.notes && (
                <div className="pt-2 border-t">
                  <p className="text-xs text-muted-foreground whitespace-pre-wrap">{customer.notes}</p>
                </div>
              )}
            </CardContent>
          </Card>

          {/* MagnifyingGlass criteria */}
          {searches.length > 0 && (
            <Card>
              <CardHeader className="pb-3">
                <CardTitle className="text-sm">Arama Kriterleri ({searches.length})</CardTitle>
              </CardHeader>
              <CardContent className="space-y-3">
                {searches.map((s) => (
                  <div key={s.$id} className="rounded-lg border p-3 text-sm space-y-1.5">
                    <div className="flex items-center justify-between gap-2">
                      <span className="font-medium">
                        {s.listingType ? (s.listingType === "satilik" ? "Satılık" : "Kiralık") : "Tümü"}
                        {parseJsonList(s.propertyTypes).length > 0 && ` · ${parseJsonList(s.propertyTypes).join(", ")}`}
                      </span>
                      <Badge variant={s.isActive ? "default" : "secondary"} className="text-xs">
                        {s.isActive ? "Aktif" : "Pasif"}
                      </Badge>
                    </div>
                    <div className="flex flex-wrap gap-x-4 gap-y-1 text-xs text-muted-foreground">
                      {parseJsonList(s.roomCounts).length > 0 && (
                        <span>Oda: {parseJsonList(s.roomCounts).join(", ")}</span>
                      )}
                      {(s.minPrice || s.maxPrice) && (
                        <span>Fiyat: {s.minPrice ? s.minPrice.toLocaleString("tr-TR") : "–"} – {s.maxPrice ? s.maxPrice.toLocaleString("tr-TR") : "–"} ₺</span>
                      )}
                      {(s.minM2 || s.maxM2) && (
                        <span>m²: {s.minM2 ?? "–"}–{s.maxM2 ?? "–"}</span>
                      )}
                      {parseJsonList(s.cities).length > 0 && (
                        <span>Şehir: {parseJsonList(s.cities).join(", ")}</span>
                      )}
                      {parseJsonList(s.districts).length > 0 && (
                        <span>İlçe: {parseJsonList(s.districts).join(", ")}</span>
                      )}
                    </div>
                    {s.notes && <p className="text-xs text-muted-foreground italic">{s.notes}</p>}
                  </div>
                ))}
              </CardContent>
            </Card>
          )}

          {/* Activities */}
          {activities.length > 0 && (
            <Card>
              <CardHeader className="pb-3">
                <CardTitle className="text-sm">Aktiviteler ({activities.length})</CardTitle>
              </CardHeader>
              <CardContent className="divide-y px-0">
                {activities.map((a) => (
                  <div key={a.$id} className="flex items-start gap-3 px-6 py-3 text-sm">
                    <div className="mt-0.5">
                      <Badge variant="outline" className="text-xs px-1.5 py-0">
                        {ACTIVITY_TYPE_LABELS[a.type] ?? a.type}
                      </Badge>
                    </div>
                    <div className="flex-1 min-w-0">
                      <p className="font-medium truncate">{a.title}</p>
                      {a.description && (
                        <p className="text-xs text-muted-foreground mt-0.5 line-clamp-2">{a.description}</p>
                      )}
                    </div>
                    <span className="text-xs text-muted-foreground shrink-0">
                      {new Date(a.$createdAt).toLocaleDateString("tr-TR")}
                    </span>
                  </div>
                ))}
              </CardContent>
            </Card>
          )}
        </div>

        {/* Right: matches */}
        <div>
          <Card>
            <CardHeader className="pb-3">
              <CardTitle className="text-sm">
                Eşleşen İlanlar
                {matches.length > 0 && (
                  <span className="ml-1.5 text-muted-foreground font-normal text-xs">({matches.length})</span>
                )}
              </CardTitle>
            </CardHeader>
            <CardContent className="space-y-2">
              {matches.length === 0 ? (
                <p className="text-xs text-muted-foreground">Henüz eşleşme yok.</p>
              ) : (
                matches.map((m) => {
                  const p = propertiesMap[m.propertyId];
                  const score = m.score ?? 0;
                  const scoreColor =
                    score >= 80 ? "text-green-600" : score >= 60 ? "text-blue-600" : score >= 40 ? "text-amber-600" : "text-gray-400";
                  return (
                    <div key={m.$id} className="rounded-lg border p-2.5 text-sm space-y-1">
                      <div className="flex items-center justify-between gap-2">
                        <p className="font-medium truncate text-xs leading-snug">
                          {p?.title ?? m.propertyId}
                        </p>
                        <span className={`text-xs font-bold ${scoreColor}`}>{score}</span>
                      </div>
                      {p && (
                        <p className="text-xs text-muted-foreground">
                          {PROPERTY_TYPE_LABELS[p.propertyType] ?? p.propertyType}
                          {p.city ? ` · ${p.city}` : ""}
                          {p.price ? ` · ${p.price.toLocaleString("tr-TR")} ₺` : ""}
                        </p>
                      )}
                      <div className="flex items-center justify-between">
                        <span className={`text-[10px] ${m.notified ? "text-muted-foreground" : "text-amber-600 font-medium"}`}>
                          {m.notified ? "Bildirildi" : "Bekliyor"}
                        </span>
                        {p && (
                          <Link href={`/properties/${p.$id}`} className="text-[10px] text-primary hover:underline">
                            Detay →
                          </Link>
                        )}
                      </div>
                    </div>
                  );
                })
              )}
            </CardContent>
          </Card>
        </div>
      </div>
    </div>
  );
}
