import Link from "next/link";
import { DashboardShell } from "@/components/dashboard/dashboard-shell";
import {
  PublicStudioHostLabel,
  PublicStudioLink,
} from "@/components/dashboard/public-studio-link";
import { requireDashboardContext } from "@/core/auth/dashboard-context";
import { buildTenantSubdomainUrl, getTenantPublicHostLabel } from "@/core/config/domains";
import { getRequestHostname } from "@/core/tenant/request-tenant";
import { getStorage } from "@/core/storage/storage";
import { countTenantInquiries, listInquiries } from "@/services/inquiry-service";
import { listDashboardJournal } from "@/services/journal-service";
import {
  countTenantProjects,
  listDashboardProjects,
} from "@/services/project-service";
import { listTenantMedia } from "@/services/media-service";
import { getArchitectProfile } from "@/services/profile-service";
import { listDashboardServices } from "@/services/studio-services-service";

function formatRelative(date: Date) {
  const diffMs = Date.now() - date.getTime();
  const mins = Math.floor(diffMs / 60000);
  if (mins < 1) return "Just now";
  if (mins < 60) return `${mins}m ago`;
  const hours = Math.floor(mins / 60);
  if (hours < 24) return `${hours}h ago`;
  const days = Math.floor(hours / 24);
  if (days < 14) return `${days}d ago`;
  return date.toLocaleDateString();
}

function statusTone(status: string) {
  if (status === "published") return "bg-emerald-500/15 text-emerald-800";
  if (status === "archived") {
    return "bg-[var(--archi-ink)]/10 text-[var(--archi-ink-muted)]";
  }
  return "bg-[var(--archi-gold)]/15 text-[#8a7010]";
}

function formatBytes(bytes: number) {
  if (bytes < 1024) return `${bytes} B`;
  if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
  return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
}

export default async function DashboardOverviewPage() {
  const ctx = await requireDashboardContext();
  const storage = getStorage();
  const requestHost = await getRequestHostname();
  const siteUrl = buildTenantSubdomainUrl(ctx.tenant.tenantSlug, {
    requestHost,
  });
  const hostLabel = getTenantPublicHostLabel(ctx.tenant.tenantSlug, {
    requestHost,
  });

  const [
    projectCount,
    inquiryCount,
    newInquiries,
    projects,
    inquiries,
    media,
    services,
    journalPosts,
    profileData,
  ] = await Promise.all([
    countTenantProjects(ctx.tenant),
    countTenantInquiries(ctx.tenant),
    countTenantInquiries(ctx.tenant, "new"),
    listDashboardProjects(ctx.tenant),
    listInquiries(ctx.tenant, 8),
    listTenantMedia(ctx.tenant, 100),
    listDashboardServices(ctx.tenant),
    listDashboardJournal(ctx.tenant),
    getArchitectProfile(ctx.tenant),
  ]);

  const published = projects.filter((p) => p.status === "published").length;
  const drafts = projects.filter((p) => p.status === "draft").length;
  const archived = projects.filter((p) => p.status === "archived").length;
  const publishedServices = services.filter((s) => s.isPublished).length;
  const publishedJournal = journalPosts.filter(
    (p) => p.status === "published",
  ).length;

  const storageUsed = media.reduce((sum, item) => sum + (item.fileSize || 0), 0);
  const imageBytes = media
    .filter((m) => m.fileType === "image")
    .reduce((sum, item) => sum + (item.fileSize || 0), 0);
  const docBytes = media
    .filter((m) => m.fileType !== "image")
    .reduce((sum, item) => sum + (item.fileSize || 0), 0);
  const storageCap = 100 * 1024 * 1024; // soft display cap 100MB (local/dev)
  const storagePct = Math.min(100, Math.round((storageUsed / storageCap) * 100));

  const recent = projects.slice(0, 3);
  const recentWithImages = await Promise.all(
    recent.map(async (project) => ({
      project,
      imageSrc: project.heroStorageKey
        ? await storage.getSignedUrl(
            project.heroStorageKey,
            ctx.tenant.tenantId,
          )
        : null,
    })),
  );

  const recentMedia = await Promise.all(
    media.slice(0, 5).map(async (item) => ({
      item,
      imageSrc:
        item.fileType === "image"
          ? await storage.getSignedUrl(item.storageKey, ctx.tenant.tenantId)
          : null,
    })),
  );

  const firstName =
    ctx.user.name?.trim().split(/\s+/)[0] ||
    ctx.user.email?.split("@")[0] ||
    "there";

  const activity = [
    ...inquiries.slice(0, 4).map((inq) => ({
      id: `inq-${inq.id}`,
      title: `New inquiry from ${inq.name}`,
      when: formatRelative(new Date(inq.createdAt)),
      href: `/dashboard/inquiries/${inq.id}`,
      tone: "inquiry" as const,
    })),
    ...recent.slice(0, 3).map((project) => ({
      id: `proj-${project.id}`,
      title: `${project.title} · ${project.status}`,
      when: formatRelative(new Date(project.updatedAt)),
      href: `/dashboard/projects/${project.id}`,
      tone: "project" as const,
    })),
  ].slice(0, 5);

  const pipelineMax = Math.max(published, drafts, archived, 1);
  const profileReady = Boolean(
    profileData.profile?.tagline || profileData.profile?.about,
  );

  const kpis = [
    {
      label: "Total projects",
      value: String(projectCount),
      hint: `${published} published`,
      href: "/dashboard/projects",
      iconBg: "bg-[var(--archi-gold)]/15 text-[#8a7010]",
    },
    {
      label: "Total inquiries",
      value: String(inquiryCount),
      hint: `${newInquiries} awaiting review`,
      href: "/dashboard/inquiries",
      iconBg: "bg-[var(--archi-ink)]/8 text-[var(--archi-ink)]",
    },
    {
      label: "New leads",
      value: String(newInquiries),
      hint: "Status: new",
      href: "/dashboard/inquiries?status=new",
      iconBg: "bg-emerald-500/12 text-emerald-800",
    },
    {
      label: "Media assets",
      value: String(media.length),
      hint: formatBytes(storageUsed),
      href: "/dashboard/media",
      iconBg: "bg-[var(--archi-bg-deep)] text-[var(--archi-ink-muted)]",
    },
  ];

  const quickActions = [
    { href: "/dashboard/projects/new", label: "New project", tone: "dark" },
    { href: "/dashboard/media", label: "Upload media", tone: "gold" },
    { href: "/dashboard/services/new", label: "New service", tone: "cream" },
    { href: "/dashboard/journal/new", label: "Write journal", tone: "cream" },
    { href: "/dashboard/settings", label: "Edit profile", tone: "cream" },
    { href: "/dashboard/inquiries", label: "View inquiries", tone: "ink" },
  ];

  return (
    <DashboardShell width="wide">
      <div className="mb-6 flex flex-wrap items-end justify-between gap-3">
        <div>
          <p className="text-xs tracking-[0.2em] text-[var(--archi-ink-muted)] uppercase">
            Overview
          </p>
          <h1 className="mt-1 font-[family-name:var(--font-display)] text-3xl tracking-tight sm:text-4xl">
            Welcome back, {firstName}
          </h1>
          <p className="mt-1 text-sm text-[var(--archi-ink-muted)]">
            {ctx.tenant.studioName} ·{" "}
            <PublicStudioLink
              slug={ctx.tenant.tenantSlug}
              href={siteUrl}
              target="_blank"
              rel="noreferrer"
              className="underline-offset-2 hover:underline"
            >
              <PublicStudioHostLabel
                slug={ctx.tenant.tenantSlug}
                label={hostLabel}
              />
            </PublicStudioLink>
          </p>
        </div>
        <PublicStudioLink
          slug={ctx.tenant.tenantSlug}
          href={siteUrl}
          target="_blank"
          rel="noreferrer"
          className="inline-flex items-center gap-1.5 border border-[var(--archi-line)] bg-white px-4 py-2 text-sm transition hover:border-[var(--archi-gold)]/40"
        >
          View live studio ↗
        </PublicStudioLink>
      </div>

      {/* KPI row */}
      <section className="grid gap-4 sm:grid-cols-2 xl:grid-cols-4">
        {kpis.map((kpi) => (
          <Link
            key={kpi.label}
            href={kpi.href}
            className="rounded-2xl border border-[var(--archi-line)] bg-white px-5 py-5 shadow-[0_8px_24px_rgba(18,18,18,0.04)] transition hover:border-[var(--archi-gold)]/35"
          >
            <div className="flex items-start justify-between gap-3">
              <div>
                <p className="text-xs tracking-[0.12em] text-[var(--archi-ink-muted)] uppercase">
                  {kpi.label}
                </p>
                <p className="mt-3 font-[family-name:var(--font-display)] text-3xl font-bold">
                  {kpi.value}
                </p>
                <p className="mt-2 text-xs text-[var(--archi-ink-muted)]">
                  {kpi.hint}
                </p>
              </div>
              <span
                className={`flex h-10 w-10 items-center justify-center rounded-xl ${kpi.iconBg}`}
              >
                <span className="text-sm font-semibold">
                  {kpi.label.charAt(0)}
                </span>
              </span>
            </div>
          </Link>
        ))}
      </section>

      {/* Performance + Activity */}
      <section className="mt-6 grid gap-6 xl:grid-cols-[1.55fr_1fr]">
        <div className="rounded-2xl border border-[var(--archi-line)] bg-white p-5 shadow-[0_8px_24px_rgba(18,18,18,0.04)]">
          <div className="flex flex-wrap items-center justify-between gap-3">
            <h2 className="font-[family-name:var(--font-display)] text-xl font-semibold">
              Studio pipeline
            </h2>
            <p className="text-xs text-[var(--archi-ink-muted)]">
              Live · Draft · Archived
            </p>
          </div>

          <div className="mt-6 grid gap-6 lg:grid-cols-[1.2fr_1fr]">
            <div className="flex h-44 items-end gap-4 px-2">
              {[
                { label: "Published", value: published, fill: "var(--archi-gold)" },
                { label: "Draft", value: drafts, fill: "var(--archi-ink)" },
                {
                  label: "Archived",
                  value: archived,
                  fill: "rgba(18,18,18,0.25)",
                },
              ].map((bar) => (
                <div key={bar.label} className="flex flex-1 flex-col items-center gap-2">
                  <div className="flex h-32 w-full items-end justify-center rounded-t-lg bg-[var(--archi-cream-soft)]">
                    <div
                      className="w-[55%] rounded-t-md transition-all"
                      style={{
                        height: `${Math.max(8, (bar.value / pipelineMax) * 100)}%`,
                        background: bar.fill,
                      }}
                    />
                  </div>
                  <p className="text-[11px] font-medium text-[var(--archi-ink-muted)]">
                    {bar.label}
                  </p>
                  <p className="text-sm font-semibold">{bar.value}</p>
                </div>
              ))}
            </div>

            <ul className="space-y-3 text-sm">
              {[
                {
                  label: "Published projects",
                  value: published,
                  hint: "On public site",
                },
                {
                  label: "Published services",
                  value: publishedServices,
                  hint: "Offerings live",
                },
                {
                  label: "Journal posts",
                  value: publishedJournal,
                  hint: "Public writing",
                },
                {
                  label: "Profile readiness",
                  value: profileReady ? "Ready" : "Incomplete",
                  hint: profileReady ? "Tagline / about set" : "Add studio profile",
                },
              ].map((row) => (
                <li
                  key={row.label}
                  className="flex items-center justify-between border-b border-[var(--archi-line)] pb-2 last:border-0"
                >
                  <div>
                    <p className="font-medium">{row.label}</p>
                    <p className="text-[11px] text-[var(--archi-ink-muted)]">
                      {row.hint}
                    </p>
                  </div>
                  <span className="font-semibold">{row.value}</span>
                </li>
              ))}
            </ul>
          </div>
        </div>

        <div className="rounded-2xl border border-[var(--archi-line)] bg-white p-5 shadow-[0_8px_24px_rgba(18,18,18,0.04)]">
          <div className="mb-4 flex items-center justify-between">
            <h2 className="font-[family-name:var(--font-display)] text-lg font-semibold">
              Recent activity
            </h2>
            <Link
              href="/dashboard/inquiries"
              className="text-xs text-[var(--archi-gold)]"
            >
              View all
            </Link>
          </div>
          {activity.length === 0 ? (
            <p className="text-sm text-[var(--archi-ink-muted)]">
              Activity appears when you publish projects or receive inquiries.
            </p>
          ) : (
            <ul className="space-y-3">
              {activity.map((item) => (
                <li key={item.id}>
                  <Link
                    href={item.href}
                    className="flex gap-3 rounded-xl px-2 py-2 text-sm transition hover:bg-[var(--archi-cream-soft)]"
                  >
                    <span
                      className={`mt-1.5 h-2.5 w-2.5 shrink-0 rounded-full ${
                        item.tone === "inquiry"
                          ? "bg-[var(--archi-gold)]"
                          : "bg-[var(--archi-ink)]"
                      }`}
                    />
                    <div className="min-w-0">
                      <p className="truncate font-medium">{item.title}</p>
                      <p className="text-[11px] text-[var(--archi-ink-muted)]">
                        {item.when}
                      </p>
                    </div>
                  </Link>
                </li>
              ))}
            </ul>
          )}
        </div>
      </section>

      {/* Projects + Media + Quick actions + Storage */}
      <section className="mt-6 grid gap-6 xl:grid-cols-[1.4fr_1fr]">
        <div className="space-y-6">
          <div className="rounded-2xl border border-[var(--archi-line)] bg-white p-5 shadow-[0_8px_24px_rgba(18,18,18,0.04)]">
            <div className="mb-4 flex items-center justify-between gap-3">
              <h2 className="font-[family-name:var(--font-display)] text-xl font-semibold">
                Recent projects
              </h2>
              <Link
                href="/dashboard/projects"
                className="text-sm text-[var(--archi-gold)]"
              >
                View all
              </Link>
            </div>
            {recentWithImages.length === 0 ? (
              <div className="rounded-xl border border-dashed border-[var(--archi-line)] px-4 py-10 text-center">
                <p className="text-sm text-[var(--archi-ink-muted)]">
                  Publish projects so visitors see your work on{" "}
                  <span className="font-medium text-[var(--archi-ink)]">
                    <PublicStudioHostLabel
                      slug={ctx.tenant.tenantSlug}
                      label={hostLabel}
                    />
                  </span>
                  .
                </p>
                <Link
                  href="/dashboard/projects/new"
                  className="archi-btn-primary mt-4"
                >
                  Create project
                </Link>
              </div>
            ) : (
              <div className="grid gap-4 sm:grid-cols-3">
                {recentWithImages.map(({ project, imageSrc }) => (
                  <Link
                    key={project.id}
                    href={`/dashboard/projects/${project.id}`}
                    className="group overflow-hidden rounded-2xl border border-[var(--archi-line)] bg-[var(--archi-cream-soft)] transition hover:border-[var(--archi-gold)]/40"
                  >
                    <div className="relative aspect-[16/11] overflow-hidden bg-[var(--archi-bg-deep)]">
                      {imageSrc ? (
                        // eslint-disable-next-line @next/next/no-img-element
                        <img
                          src={imageSrc}
                          alt=""
                          className="h-full w-full object-cover transition duration-500 group-hover:scale-105"
                        />
                      ) : (
                        <div className="flex h-full items-center justify-center text-[10px] text-[var(--archi-ink-muted)]">
                          No hero
                        </div>
                      )}
                      <span
                        className={`absolute top-2 left-2 rounded-full px-2 py-0.5 text-[10px] font-semibold tracking-wide uppercase ${statusTone(project.status)}`}
                      >
                        {project.status}
                      </span>
                    </div>
                    <div className="p-3">
                      <p className="truncate text-sm font-semibold">
                        {project.title}
                      </p>
                      <p className="mt-0.5 text-[11px] text-[var(--archi-ink-muted)]">
                        Updated {formatRelative(new Date(project.updatedAt))}
                      </p>
                    </div>
                  </Link>
                ))}
              </div>
            )}
          </div>

          <div className="rounded-2xl border border-[var(--archi-line)] bg-white p-5 shadow-[0_8px_24px_rgba(18,18,18,0.04)]">
            <div className="mb-4 flex items-center justify-between">
              <h2 className="font-[family-name:var(--font-display)] text-lg font-semibold">
                Recent media
              </h2>
              <Link href="/dashboard/media" className="text-xs text-[var(--archi-gold)]">
                Library
              </Link>
            </div>
            <div className="flex flex-wrap gap-3">
              {recentMedia.length === 0 ? (
                <p className="text-sm text-[var(--archi-ink-muted)]">
                  Upload from a project page to showcase 3D / photo assets.
                </p>
              ) : (
                recentMedia.map(({ item, imageSrc }) => (
                  <div
                    key={item.id}
                    className="h-16 w-16 overflow-hidden rounded-xl border border-[var(--archi-line)] bg-[var(--archi-bg-deep)]"
                  >
                    {imageSrc ? (
                      // eslint-disable-next-line @next/next/no-img-element
                      <img
                        src={imageSrc}
                        alt={item.altText ?? ""}
                        className="h-full w-full object-cover"
                      />
                    ) : (
                      <div className="flex h-full items-center justify-center text-[9px] text-[var(--archi-ink-muted)]">
                        file
                      </div>
                    )}
                  </div>
                ))
              )}
              <Link
                href="/dashboard/projects"
                className="flex h-16 w-16 items-center justify-center rounded-xl border border-dashed border-[var(--archi-line)] text-xl text-[var(--archi-ink-muted)] transition hover:border-[var(--archi-gold)]/40 hover:text-[var(--archi-ink)]"
                aria-label="Add media via project"
              >
                +
              </Link>
            </div>
          </div>
        </div>

        <div className="space-y-6">
          <div className="rounded-2xl border border-[var(--archi-line)] bg-white p-5 shadow-[0_8px_24px_rgba(18,18,18,0.04)]">
            <h2 className="font-[family-name:var(--font-display)] text-lg font-semibold">
              Quick actions
            </h2>
            <div className="mt-4 grid grid-cols-2 gap-2">
              {quickActions.map((action) => (
                <Link
                  key={action.href}
                  href={action.href}
                  className={`rounded-xl px-3 py-3 text-center text-sm font-medium transition ${
                    action.tone === "dark"
                      ? "bg-[var(--archi-ink)] text-white hover:opacity-90"
                      : action.tone === "gold"
                        ? "bg-[var(--archi-gold)]/20 text-[#6f5a10] hover:bg-[var(--archi-gold)]/30"
                        : action.tone === "ink"
                          ? "border border-[var(--archi-ink)] text-[var(--archi-ink)] hover:bg-[var(--archi-ink)] hover:text-white"
                          : "border border-[var(--archi-line)] bg-[var(--archi-cream-soft)] text-[var(--archi-ink)] hover:border-[var(--archi-gold)]/40"
                  }`}
                >
                  {action.label}
                </Link>
              ))}
            </div>
          </div>

          <div className="rounded-2xl border border-[var(--archi-line)] bg-white p-5 shadow-[0_8px_24px_rgba(18,18,18,0.04)]">
            <h2 className="font-[family-name:var(--font-display)] text-lg font-semibold">
              Storage usage
            </h2>
            <p className="mt-2 text-sm text-[var(--archi-ink-muted)]">
              {formatBytes(storageUsed)} used · {media.length} files
            </p>
            <div className="mt-4 h-2.5 overflow-hidden rounded-full bg-[var(--archi-cream-soft)]">
              <div
                className="h-full rounded-full bg-[var(--archi-gold)]"
                style={{ width: `${Math.max(storagePct, storageUsed > 0 ? 4 : 0)}%` }}
              />
            </div>
            <ul className="mt-4 space-y-2 text-sm">
              <li className="flex justify-between">
                <span className="flex items-center gap-2 text-[var(--archi-ink-muted)]">
                  <span className="h-2 w-2 rounded-full bg-[var(--archi-gold)]" />
                  Images
                </span>
                <span className="font-medium">{formatBytes(imageBytes)}</span>
              </li>
              <li className="flex justify-between">
                <span className="flex items-center gap-2 text-[var(--archi-ink-muted)]">
                  <span className="h-2 w-2 rounded-full bg-[var(--archi-ink)]" />
                  Documents / other
                </span>
                <span className="font-medium">{formatBytes(docBytes)}</span>
              </li>
            </ul>
          </div>

          <div className="rounded-2xl border border-[var(--archi-line)] bg-[var(--archi-dark)] p-5 text-white">
            <p className="text-[11px] tracking-[0.16em] text-white/45 uppercase">
              Your public studio
            </p>
            <p className="mt-2 font-[family-name:var(--font-display)] text-xl">
              {ctx.tenant.studioName}
            </p>
            <p className="mt-1 text-sm text-white/55">
              <PublicStudioHostLabel
                slug={ctx.tenant.tenantSlug}
                label={hostLabel}
              />
            </p>
            <p className="mt-3 text-xs text-white/45">
              Visitors open this link to see your projects, services, journal,
              and contact form — only this tenant&apos;s published work.
            </p>
            <PublicStudioLink
              slug={ctx.tenant.tenantSlug}
              href={siteUrl}
              target="_blank"
              rel="noreferrer"
              className="mt-4 inline-flex border border-white/20 bg-white/10 px-4 py-2 text-sm transition hover:border-[var(--archi-gold)]/50"
            >
              Open public profile ↗
            </PublicStudioLink>
          </div>
        </div>
      </section>
    </DashboardShell>
  );
}
