import { requireDashboardContext } from "@/core/auth/dashboard-context";
import {
  buildTenantSubdomainUrl,
  getTenantPublicHostLabel,
} from "@/core/config/domains";
import { getRequestHostname } from "@/core/tenant/request-tenant";
import { ArchitectPhotoUploader } from "@/components/dashboard/architect-photo-uploader";
import { AccountSettingsForm } from "@/components/dashboard/account-settings-form";
import { DashboardPageHeader } from "@/components/dashboard/page-header";
import { DashboardShell } from "@/components/dashboard/dashboard-shell";
import { ProfileSettingsForm } from "@/components/dashboard/profile-settings-form";
import {
  cancelEmailChangeAction,
  requestEmailChangeAction,
  resendEmailChangeAction,
  updateAccountProfileAction,
} from "@/app/dashboard/account-actions";
import { updateProfileAction } from "@/app/dashboard/actions";
import { getStorage } from "@/core/storage/storage";
import { getAccountProfile } from "@/services/account-service";
import { getArchitectProfile } from "@/services/profile-service";
import { getTenantSubscription } from "@/services/subscription-service";

export default async function DashboardSettingsPage() {
  const ctx = await requireDashboardContext("settings:manage");
  const requestHost = await getRequestHostname();
  const storage = getStorage();
  const [{ tenant, profile }, subscription, account] = await Promise.all([
    getArchitectProfile(ctx.tenant),
    getTenantSubscription(ctx.tenant.tenantId),
    getAccountProfile(ctx.user.id),
  ]);
  const membership = ctx.principal.tenantMemberships.find(
    (m) => m.tenantId === ctx.tenant.tenantId,
  );
  const siteUrl = buildTenantSubdomainUrl(ctx.tenant.tenantSlug, {
    requestHost,
  });
  const hostLabel = getTenantPublicHostLabel(ctx.tenant.tenantSlug, {
    requestHost,
  });
  const architectPhotoSrc = profile?.architectPhotoStorageKey
    ? `${await storage.getSignedUrl(
        profile.architectPhotoStorageKey,
        ctx.tenant.tenantId,
      )}&t=${profile.updatedAt?.getTime?.() ?? 0}`
    : null;

  return (
    <DashboardShell width="wide">
      <DashboardPageHeader
        eyebrow="Settings"
        title="Studio profile"
        description="Account security, public identity, portrait, and SEO for this tenant."
      />

      <section className="archi-panel mt-8 grid gap-5 p-5 text-sm sm:grid-cols-2 sm:p-6 lg:grid-cols-4">
        <div className="min-w-0">
          <p className="text-[0.65rem] tracking-[0.18em] text-[var(--archi-ink-muted)] uppercase">
            Slug
          </p>
          <p className="mt-1.5 truncate font-medium">{ctx.tenant.tenantSlug}</p>
        </div>
        <div className="min-w-0">
          <p className="text-[0.65rem] tracking-[0.18em] text-[var(--archi-ink-muted)] uppercase">
            Public site
          </p>
          <a
            href={siteUrl}
            target="_blank"
            rel="noreferrer"
            className="mt-1.5 inline-flex max-w-full truncate font-medium underline-offset-2 hover:underline"
          >
            {hostLabel}
          </a>
        </div>
        <div className="min-w-0">
          <p className="text-[0.65rem] tracking-[0.18em] text-[var(--archi-ink-muted)] uppercase">
            Your role
          </p>
          <p className="mt-1.5 capitalize">
            {membership?.role?.replaceAll("_", " ") ?? "—"}
          </p>
        </div>
        <div className="min-w-0">
          <p className="text-[0.65rem] tracking-[0.18em] text-[var(--archi-ink-muted)] uppercase">
            Signed in as
          </p>
          <p className="mt-1.5 truncate">
            {account?.email ?? ctx.user.email}
          </p>
        </div>
      </section>

      <div className="mt-8 grid items-start gap-8 lg:grid-cols-[minmax(0,1fr)_minmax(18rem,22rem)] xl:grid-cols-[minmax(0,1fr)_minmax(20rem,24rem)]">
        <div className="min-w-0 space-y-8">
          {account ? (
            <AccountSettingsForm
              name={account.name}
              email={account.email}
              pendingEmail={account.pendingEmail}
              phone={account.phone ?? ""}
              emailVerifiedAt={
                account.emailVerifiedAt
                  ? account.emailVerifiedAt.toISOString()
                  : null
              }
              updateProfileAction={updateAccountProfileAction}
              requestEmailChangeAction={requestEmailChangeAction}
              resendEmailChangeAction={resendEmailChangeAction}
              cancelEmailChangeAction={cancelEmailChangeAction}
            />
          ) : null}

          <ProfileSettingsForm
            studioName={tenant?.studioName ?? ctx.tenant.studioName}
            description={tenant?.description ?? ""}
            tagline={profile?.tagline ?? ""}
            about={profile?.about ?? ""}
            architectName={profile?.architectName ?? ""}
            architectTitle={profile?.architectTitle ?? ""}
            philosophy={profile?.philosophy ?? ""}
            vision={profile?.vision ?? ""}
            mission={profile?.mission ?? ""}
            approach={profile?.approach ?? ""}
            designPrinciples={profile?.designPrinciples ?? ""}
            experience={profile?.experience ?? ""}
            studioCulture={profile?.studioCulture ?? ""}
            workspace={profile?.workspace ?? ""}
            methodology={profile?.methodology ?? ""}
            collaborations={profile?.collaborations ?? ""}
            location={profile?.location ?? ""}
            foundedYear={profile?.foundedYear?.toString() ?? ""}
            websiteUrl={profile?.websiteUrl ?? ""}
            publicEmail={profile?.publicEmail ?? ""}
            phone={profile?.phone ?? ""}
            whatsapp={profile?.whatsapp ?? ""}
            businessHours={profile?.businessHours ?? ""}
            mapEmbedUrl={profile?.mapEmbedUrl ?? ""}
            socialInstagram={profile?.socialLinks?.instagram ?? ""}
            socialLinkedin={profile?.socialLinks?.linkedin ?? ""}
            socialX={profile?.socialLinks?.x ?? ""}
            seoTitle={profile?.seoTitle ?? ""}
            seoDescription={profile?.seoDescription ?? ""}
            action={updateProfileAction}
          />
        </div>

        <aside className="space-y-6 lg:sticky lg:top-24">
          <section className="archi-panel p-5 sm:p-6">
            <div className="mb-5 border-b border-[var(--archi-line)] pb-4">
              <p className="text-[0.65rem] tracking-[0.2em] text-[var(--archi-ink-muted)] uppercase">
                Portrait
              </p>
              <h2 className="mt-2 font-[family-name:var(--font-display)] text-xl tracking-tight">
                Architect photo
              </h2>
            </div>
            <ArchitectPhotoUploader
              photoSrc={architectPhotoSrc}
              architectName={profile?.architectName ?? undefined}
            />
          </section>

          <section className="archi-panel p-5 sm:p-6">
            <p className="text-[0.65rem] tracking-[0.2em] text-[var(--archi-ink-muted)] uppercase">
              Billing
            </p>
            <h2 className="mt-2 font-[family-name:var(--font-display)] text-xl tracking-tight">
              Subscription
            </h2>
            {subscription ? (
              <dl className="mt-5 space-y-3 text-sm">
                <div className="flex justify-between gap-4 border-b border-[var(--archi-line)] pb-3">
                  <dt className="text-[var(--archi-ink-muted)]">Plan</dt>
                  <dd className="font-medium">{subscription.planName}</dd>
                </div>
                <div className="flex justify-between gap-4 border-b border-[var(--archi-line)] pb-3">
                  <dt className="text-[var(--archi-ink-muted)]">Status</dt>
                  <dd className="capitalize">
                    {subscription.status.replaceAll("_", " ")}
                  </dd>
                </div>
                {subscription.currentPeriodEnd ? (
                  <div className="flex justify-between gap-4">
                    <dt className="text-[var(--archi-ink-muted)]">
                      {subscription.status === "trialing"
                        ? "Trial ends"
                        : "Period ends"}
                    </dt>
                    <dd className="text-right">
                      {subscription.currentPeriodEnd.toLocaleDateString(
                        undefined,
                        {
                          year: "numeric",
                          month: "short",
                          day: "numeric",
                        },
                      )}
                    </dd>
                  </div>
                ) : null}
              </dl>
            ) : (
              <p className="mt-4 text-sm text-[var(--archi-ink-muted)]">
                No subscription record found for this studio.
              </p>
            )}
            <p className="mt-4 text-xs leading-5 text-[var(--archi-ink-muted)]">
              Billing is managed at the platform layer.
            </p>
          </section>
        </aside>
      </div>
    </DashboardShell>
  );
}
