import Link from "next/link";
import { requireAuth } from "@/lib/auth/session";
import { db } from "@/lib/db";
import { AddWebsiteForm } from "@/components/AddWebsiteForm";

const STATUS_STYLES: Record<string, string> = {
  COMPLETED: "bg-green-100 text-green-800",
  RUNNING: "bg-blue-100 text-blue-800",
  QUEUED: "bg-amber-100 text-amber-800",
  FAILED: "bg-red-100 text-red-800",
  CANCELLED: "bg-slate-200 text-slate-600",
};

export default async function DashboardPage() {
  const auth = await requireAuth();
  const organisationIds = auth.memberships.map((m) => m.organisationId);

  const organisations = await db.organisation.findMany({
    where: { id: { in: organisationIds }, deletedAt: null },
    select: {
      id: true,
      name: true,
      websites: {
        where: { archivedAt: null },
        orderBy: { createdAt: "desc" },
        select: {
          id: true,
          name: true,
          url: true,
          isVerified: true,
          crawls: {
            orderBy: { createdAt: "desc" },
            take: 1,
            select: { id: true, status: true, pagesCrawled: true, createdAt: true },
          },
        },
      },
    },
    orderBy: { createdAt: "asc" },
  });

  const primaryOrg = organisations[0];

  return (
    <div className="space-y-10">
      {!auth.user.emailVerifiedAt && (
        <p className="rounded-lg bg-amber-50 px-4 py-3 text-sm text-amber-800">
          Your email address isn&apos;t verified yet — check your inbox for the verification link.
        </p>
      )}

      {organisations.map((org) => (
        <section key={org.id}>
          <div className="flex items-center justify-between">
            <h1 className="text-xl font-semibold">{org.name}</h1>
          </div>

          {org.websites.length === 0 ? (
            <p className="mt-4 rounded-xl border border-dashed border-slate-300 bg-white p-8 text-center text-sm text-slate-500">
              No websites yet. Add your first website below to run an SEO audit.
            </p>
          ) : (
            <ul className="mt-4 grid gap-4 sm:grid-cols-2">
              {org.websites.map((site) => {
                const crawl = site.crawls[0];
                return (
                  <li key={site.id}>
                    <Link
                      href={`/dashboard/websites/${site.id}`}
                      className="block rounded-xl border border-slate-200 bg-white p-5 hover:border-slate-400"
                    >
                      <div className="flex items-center justify-between gap-2">
                        <span className="font-medium">{site.name}</span>
                        {site.isVerified ? (
                          <span className="rounded-full bg-green-100 px-2 py-0.5 text-xs text-green-800">
                            Verified
                          </span>
                        ) : (
                          <span className="rounded-full bg-slate-100 px-2 py-0.5 text-xs text-slate-600">
                            Unverified
                          </span>
                        )}
                      </div>
                      <p className="mt-1 truncate text-sm text-slate-500">{site.url}</p>
                      <p className="mt-3 text-xs text-slate-500">
                        {crawl ? (
                          <>
                            Last crawl:{" "}
                            <span
                              className={`rounded-full px-2 py-0.5 ${STATUS_STYLES[crawl.status] ?? "bg-slate-100"}`}
                            >
                              {crawl.status.toLowerCase()}
                            </span>{" "}
                            · {crawl.pagesCrawled} pages
                          </>
                        ) : (
                          "Not crawled yet"
                        )}
                      </p>
                    </Link>
                  </li>
                );
              })}
            </ul>
          )}
        </section>
      ))}

      {primaryOrg && (
        <section className="rounded-xl border border-slate-200 bg-white p-6">
          <h2 className="font-semibold">Add a website</h2>
          <p className="mt-1 text-sm text-slate-500">
            We&apos;ll check the address is reachable, then guide you through verification and your
            first audit.
          </p>
          <AddWebsiteForm organisationId={primaryOrg.id} />
        </section>
      )}
    </div>
  );
}
