import Link from "next/link";
import { redirect } from "next/navigation";

import { ShellPage } from "@/components/page-templates";
import { SectionCard } from "@/components/ui";
import { getSession } from "@/lib/auth";
import { prisma } from "@/lib/prisma";

export default async function ContactDetailPage({ params }: { params: Promise<{ contactId: string }> }) {
  const { contactId } = await params;
  const session = await getSession();
  if (!session) {
    redirect("/login");
  }

  const contact = await prisma.contact.findFirst({
    where: { id: contactId, tenantId: session.tenantId },
    include: {
      contactTags: { include: { tag: true } },
      conversations: true,
      channel: true
    }
  });

  if (!contact) {
    redirect("/contacts?error=contact_not_found");
  }

  return (
    <ShellPage
      shell="admin"
      title="Contact Detail"
      description="Profile, tags, conversation history, dan campaign history."
      actions={<Link href={`/contacts/${contactId}/edit`}>Edit contact</Link>}
    >
      <div className="grid gap-6 xl:grid-cols-[340px_1fr]">
        <SectionCard title="Profile card">
          <p className="text-sm text-on-surface-variant">
            <strong>Nama:</strong> {contact.fullName}
          </p>
          <p className="text-sm text-on-surface-variant">
            <strong>Phone:</strong> {contact.phoneNumber}
          </p>
          <p className="text-sm text-on-surface-variant">
            <strong>Email:</strong> {contact.email || "-"}
          </p>
          <p className="text-sm text-on-surface-variant">
            <strong>Channel:</strong> {contact.channel?.channelName || "Unset"}
          </p>
          <p className="text-sm text-on-surface-variant">
            <strong>Opt-in:</strong> {contact.optInStatus}
          </p>
          <p className="text-sm text-on-surface-variant">
            <strong>Last interaction:</strong> {contact.lastInteractionAt?.toLocaleString() || "-"}
          </p>
          <p className="mt-3 text-xs text-outline">
            <Link href="/contacts" className="text-on-surface-variant hover:underline">
              Kembali ke daftar
            </Link>
          </p>
        </SectionCard>
        <SectionCard title="History">
          <p className="text-sm text-on-surface-variant">
            Total conversations: <strong>{contact.conversations.length}</strong>
          </p>
          <p className="mt-2 text-sm text-on-surface-variant">
            Tags: {contact.contactTags.map((item) => item.tag.name).join(", ") || "-"}
          </p>
        </SectionCard>
      </div>
    </ShellPage>
  );
}
