import { Metadata } from "next";
import { notFound, redirect } from "next/navigation";
import Link from "next/link";
import { auth } from "@/auth";
import { db } from "@/lib/db";
import { Building2, Mail, User2, Phone, ArrowLeft, ExternalLink, Copy } from "lucide-react";
import { Button } from "@/components/ui/button";
import { ShareReviewDialog } from "@/components/clients/ShareReviewDialog";
import { ReviewSessionList } from "@/components/clients/ReviewSessionList";
import { cn } from "@/lib/utils";

export const metadata: Metadata = { title: "Client Detail" };

async function getClient(clientId: string) {
  return db.client.findUnique({
    where: { id: clientId },
    include: {
      projects: {
        orderBy: { createdAt: "desc" },
        include: {
          _count: { select: { shots: true } },
        },
      },
    },
  });
}

async function getReviewSessions(projectIds: string[]) {
  if (projectIds.length === 0) return [];
  return db.reviewSession.findMany({
    where: { projectId: { in: projectIds }, isActive: true },
    orderBy: { createdAt: "desc" },
    include: { project: { select: { name: true } } },
  });
}

export default async function ClientDetailPage({
  params,
}: {
  params: Promise<{ clientId: string }>;
}) {
  const { clientId } = await params;
  const session = await auth();
  if (!session || !["ADMIN", "PRODUCER"].includes(session.user.role as string)) {
    redirect("/dashboard");
  }

  const client = await getClient(clientId);
  if (!client) notFound();

  const projectIds = client.projects.map((p) => p.id);
  const reviewSessions = await getReviewSessions(projectIds);

  const PROJECT_STATUS_COLORS: Record<string, string> = {
    ACTIVE: "text-emerald-400 bg-emerald-500/10",
    COMPLETED: "text-zinc-400 bg-zinc-700",
    ON_HOLD: "text-amber-400 bg-amber-500/10",
    CANCELLED: "text-red-400 bg-red-500/10",
  };

  return (
    <div className="p-6 max-w-5xl mx-auto space-y-6">
      {/* Back */}
      <Link
        href="/clients"
        className="inline-flex items-center gap-1.5 text-sm text-zinc-400 hover:text-white transition-colors"
      >
        <ArrowLeft className="h-4 w-4" />
        All Clients
      </Link>

      {/* Client header */}
      <div className="rounded-xl border border-zinc-800 bg-zinc-900 p-6">
        <div className="flex items-start justify-between gap-4">
          <div className="flex items-start gap-4">
            <div className="w-12 h-12 rounded-xl bg-zinc-800 border border-zinc-700 flex items-center justify-center shrink-0">
              <Building2 className="h-6 w-6 text-zinc-400" />
            </div>
            <div>
              <h1 className="text-2xl font-bold text-white">{client.company}</h1>
              <span
                className={cn(
                  "text-xs px-2 py-0.5 rounded-full mt-1 inline-block",
                  client.isActive
                    ? "bg-emerald-500/10 text-emerald-400"
                    : "bg-zinc-700 text-zinc-500"
                )}
              >
                {client.isActive ? "Active" : "Inactive"}
              </span>
            </div>
          </div>
          <ShareReviewDialog
            clientId={client.id}
            clientEmail={client.email ?? ""}
            projects={client.projects}
          >
            <Button className="gap-2 shrink-0">
              <ExternalLink className="h-4 w-4" />
              Share Review Link
            </Button>
          </ShareReviewDialog>
        </div>

        <div className="mt-5 grid grid-cols-1 sm:grid-cols-3 gap-4">
          {client.contactPerson && (
            <div className="flex items-center gap-2 text-sm text-zinc-300">
              <User2 className="h-4 w-4 text-zinc-600 shrink-0" />
              <span>{client.contactPerson}</span>
            </div>
          )}
          {client.email && (
            <div className="flex items-center gap-2 text-sm text-zinc-300">
              <Mail className="h-4 w-4 text-zinc-600 shrink-0" />
              <a href={`mailto:${client.email}`} className="hover:text-amber-400 transition-colors">
                {client.email}
              </a>
            </div>
          )}
          {client.phone && (
            <div className="flex items-center gap-2 text-sm text-zinc-300">
              <Phone className="h-4 w-4 text-zinc-600 shrink-0" />
              <span>{client.phone}</span>
            </div>
          )}
        </div>

        {client.notes && (
          <p className="mt-4 text-sm text-zinc-400 border-t border-zinc-800 pt-4">
            {client.notes}
          </p>
        )}
      </div>

      {/* Projects */}
      <div>
        <h2 className="text-base font-semibold text-white mb-3">
          Projects ({client.projects.length})
        </h2>
        {client.projects.length === 0 ? (
          <p className="text-sm text-zinc-500">No projects assigned to this client.</p>
        ) : (
          <div className="space-y-2">
            {client.projects.map((project) => (
              <Link
                key={project.id}
                href={`/projects/${project.id}`}
                className="flex items-center gap-4 p-4 rounded-xl border border-zinc-800 bg-zinc-900 hover:border-zinc-600 hover:bg-zinc-800/60 transition-all group"
              >
                <div className="flex-1 min-w-0">
                  <p className="font-semibold text-white">{project.name}</p>
                  <p className="text-xs font-mono text-zinc-500">{project.code}</p>
                </div>
                <div className="flex items-center gap-3 shrink-0">
                  <span className="text-xs text-zinc-500">
                    {project._count.shots} shots
                  </span>
                  <span
                    className={cn(
                      "text-xs px-2 py-0.5 rounded-full",
                      PROJECT_STATUS_COLORS[project.status] ?? "text-zinc-400 bg-zinc-700"
                    )}
                  >
                    {project.status}
                  </span>
                </div>
              </Link>
            ))}
          </div>
        )}
      </div>

      {/* Review sessions */}
      <ReviewSessionList sessions={reviewSessions} />
    </div>
  );
}
