import type { Metadata } from "next";
import Link from "next/link";

import { Button } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Logo } from "@/components/logo";
import { resolveInviteCode } from "@/lib/appwrite/team-actions";
import { createAdminClient, getCurrentUser } from "@/lib/appwrite/server";
import { DATABASE_ID, TABLES, type TenantSettings } from "@/lib/appwrite/schema";
import { AcceptInviteButton } from "./accept-invite-button";
import { Query } from "node-appwrite";

export const metadata: Metadata = {
  title: "DLS — Davet",
};

async function getCompanyName(tenantId: string): Promise<string | null> {
  try {
    const { tablesDB } = createAdminClient();
    const result = await tablesDB.listRows({
      databaseId: DATABASE_ID,
      tableId: TABLES.tenantSettings,
      queries: [Query.equal("tenantId", tenantId), Query.limit(1)],
    });
    return (result.rows[0] as unknown as TenantSettings | undefined)?.companyName ?? null;
  } catch {
    return null;
  }
}

export default async function InvitePage({
  params,
}: {
  params: Promise<{ code: string }>;
}) {
  const { code } = await params;
  const invite = await resolveInviteCode(code);
  const user = await getCurrentUser();

  return (
    <div className="bg-muted flex min-h-svh flex-col items-center justify-center p-6 md:p-10">
      <div className="flex w-full max-w-md flex-col gap-6">
        <Link href="/" className="flex items-center justify-center gap-2 font-medium">
          <div className="bg-primary text-primary-foreground flex size-9 items-center justify-center rounded-md">
            <Logo size={22} />
          </div>
          <span className="text-xl font-semibold">DLS</span>
        </Link>

        {!invite || invite.status === "cancelled" ? (
          <InvalidCard reason="Davet bulunamadı veya iptal edilmiş." />
        ) : invite.status === "accepted" ? (
          <InvalidCard reason="Bu davet daha önce kabul edilmiş." action="dashboard" />
        ) : invite.expiresAt && new Date(invite.expiresAt).getTime() < Date.now() ? (
          <InvalidCard reason="Bu davetin süresi dolmuş." />
        ) : (
          <ValidInvite
            code={code}
            email={invite.email}
            role={invite.role ?? "member"}
            companyName={(await getCompanyName(invite.tenantId)) ?? "Bir çalışma alanı"}
            currentUserEmail={user?.email ?? null}
          />
        )}
      </div>
    </div>
  );
}

function InvalidCard({ reason, action }: { reason: string; action?: "dashboard" }) {
  return (
    <Card>
      <CardHeader className="text-center">
        <CardTitle>Davet kullanılamıyor</CardTitle>
        <CardDescription>{reason}</CardDescription>
      </CardHeader>
      <CardContent className="flex justify-center">
        <Button asChild variant="outline">
          <Link href={action === "dashboard" ? "/dashboard" : "/sign-in"}>
            {action === "dashboard" ? "Panele git" : "Giriş yap"}
          </Link>
        </Button>
      </CardContent>
    </Card>
  );
}

function ValidInvite({
  code,
  email,
  role,
  companyName,
  currentUserEmail,
}: {
  code: string;
  email: string;
  role: string;
  companyName: string;
  currentUserEmail: string | null;
}) {
  const roleLabel = role === "admin" ? "Yönetici" : "Üye";
  const emailMatches = currentUserEmail?.toLowerCase() === email.toLowerCase();

  return (
    <Card>
      <CardHeader className="text-center">
        <CardTitle className="text-2xl">{companyName}</CardTitle>
        <CardDescription>
          <strong>{email}</strong> olarak <strong>{roleLabel}</strong> rolüyle çalışma alanına davet
          edildiniz.
        </CardDescription>
      </CardHeader>
      <CardContent className="flex flex-col gap-3">
        {!currentUserEmail ? (
          <>
            <Button asChild className="w-full">
              <Link href={`/sign-up?invite=${code}&email=${encodeURIComponent(email)}`}>
                Hesap oluşturup katıl
              </Link>
            </Button>
            <Button asChild variant="outline" className="w-full">
              <Link href={`/sign-in?invite=${code}`}>Zaten hesabım var, giriş yap</Link>
            </Button>
          </>
        ) : emailMatches ? (
          <AcceptInviteButton code={code} />
        ) : (
          <>
            <p className="text-destructive text-center text-sm">
              Şu an <strong>{currentUserEmail}</strong> ile giriş yapmışsınız. Davet{" "}
              <strong>{email}</strong> içindir. Doğru hesabı kullanın.
            </p>
            <Button asChild variant="outline" className="w-full">
              <Link href={`/sign-in?invite=${code}`}>Farklı hesapla giriş yap</Link>
            </Button>
          </>
        )}
      </CardContent>
    </Card>
  );
}
