import { notFound } from "next/navigation";
import { Query } from "node-appwrite";
import { Buildings, House } from '@/lib/icons';

import { DATABASE_ID, TABLES, type Presentation, type Property } from "@/lib/appwrite/schema";
import { createAdminClient } from "@/lib/appwrite/server";
import { incrementPresentationViewCount } from "@/lib/appwrite/presentation-actions";
import { SunumClient } from "./sunum-client";

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

export default async function SunumPage({ params }: Props) {
  const { token } = await params;
  const { tablesDB, teams, users } = createAdminClient();

  const result = await tablesDB.listRows({
    databaseId: DATABASE_ID,
    tableId: TABLES.presentations,
    queries: [Query.equal("shareToken", token), Query.limit(1)],
  });

  if (!result.rows.length) notFound();

  const presentation = result.rows[0] as unknown as Presentation;

  if (presentation.expiresAt && new Date(presentation.expiresAt) < new Date()) {
    return (
      <div className="min-h-screen flex items-center justify-center bg-slate-50">
        <div className="text-center px-6">
          <div className="inline-flex items-center justify-center w-16 h-16 rounded-full bg-orange-100 mb-4">
            <Buildings className="size-8 text-orange-500" />
          </div>
          <h1 className="text-2xl font-bold text-gray-900 mb-2">Sunum Süresi Doldu</h1>
          <p className="text-gray-500">Bu sunum bağlantısı artık geçerli değil.</p>
        </div>
      </div>
    );
  }

  void incrementPresentationViewCount(presentation.$id, presentation.viewCount ?? 0);

  const [creatorResult, teamResult] = await Promise.allSettled([
    users.get(presentation.createdBy),
    teams.get(presentation.tenantId),
  ]);
  const creatorName = creatorResult.status === "fulfilled" ? creatorResult.value.name : null;
  const companyName = teamResult.status === "fulfilled" ? teamResult.value.name : null;

  let propertyIds: string[] = [];
  try {
    propertyIds = JSON.parse(presentation.propertyIds) as string[];
  } catch {
    propertyIds = [];
  }

  const properties: Property[] = [];
  for (const pid of propertyIds) {
    try {
      const row = await tablesDB.getRow(DATABASE_ID, TABLES.properties, pid);
      properties.push(JSON.parse(JSON.stringify(row)) as Property);
    } catch {
      // deleted
    }
  }

  return (
    <div className="min-h-screen bg-slate-50">
      {/* Hero header */}
      <header className="bg-gradient-to-br from-slate-900 via-slate-800 to-slate-900 text-white">
        <div className="max-w-5xl mx-auto px-6 py-10">
          <div className="flex items-center gap-2 text-slate-400 text-sm mb-5">
            <Buildings className="size-4" />
            <span>Emlak Sunumu</span>
          </div>
          <h1 className="text-3xl font-bold tracking-tight">{presentation.title}</h1>
          {presentation.notes && (
            <p className="mt-3 text-slate-300 text-sm max-w-2xl leading-relaxed">
              {presentation.notes}
            </p>
          )}
          <div className="mt-5 flex items-center gap-3 flex-wrap">
            <span className="inline-flex items-center gap-1.5 bg-white/10 rounded-full px-3 py-1.5 text-sm">
              <span className="font-semibold text-white">{properties.length}</span>
              <span className="text-slate-300">ilan</span>
            </span>
            {(creatorName || companyName) && (
              <span className="text-slate-400 text-sm">
                {creatorName && <span className="text-slate-200 font-medium">{creatorName}</span>}
                {creatorName && companyName && <span className="mx-1.5">·</span>}
                {companyName && <span>{companyName}</span>}
              </span>
            )}
          </div>
        </div>
      </header>

      {/* Grid */}
      <main className="max-w-5xl mx-auto px-4 py-10">
        {properties.length === 0 ? (
          <div className="text-center py-20">
            <House className="size-10 text-gray-200 mx-auto mb-3" />
            <p className="text-gray-400">Bu sunumda ilan bulunmuyor.</p>
          </div>
        ) : (
          <SunumClient properties={properties} />
        )}
      </main>

      {/* Footer */}
      <footer className="border-t bg-white mt-8 py-6 text-center text-xs text-gray-400">
        {creatorName || companyName ? (
          <>
            Bu sunum{" "}
            {companyName && <span className="font-medium text-gray-600">{companyName}</span>}
            {creatorName && companyName && " · "}
            {creatorName && <span className="font-medium text-gray-600">{creatorName}</span>}
            {" "}tarafından hazırlanmıştır.
          </>
        ) : (
          "Bu sunum Emlak CRM tarafından hazırlanmıştır."
        )}
      </footer>
    </div>
  );
}
