import { notFound, redirect } from "next/navigation";

export const dynamic = "force-dynamic";

import { CustomerCreateForm } from "../_components/customer-form/customer-create-form";
import { CustomerCredentialsForm } from "../_components/customer-credentials/customer-credentials-form";
import { CustomerDashboardSettingsForm } from "../_components/customer-dashboard-settings/customer-dashboard-settings-form";
import {
  fetchBackendCustomerById,
  fetchBackendCustomerRawById,
  normalizeCustomerRow,
} from "../_lib/customers-server-api";
import { resolveImpersonationTenantSlug } from "../_lib/resolve-impersonation-tenant";
import { fetchBackendCustomerCredentials } from "../_lib/customer-credentials-server-api";
import { fetchBackendCustomerDashboardSettings } from "../_lib/customer-dashboard-settings-server-api";

type PageProps = {
  params: Promise<{ id: string }>;
  searchParams: Promise<{ action?: string; parentCustomer?: string }>;
};

export default async function CustomerDetailPage({ params, searchParams }: PageProps) {
  const { id } = await params;
  const { action, parentCustomer } = await searchParams;
  const customerId = Number(id);
  const parentId = parentCustomer ? Number(parentCustomer) : NaN;
  const parentCustomerId = Number.isFinite(parentId) && parentId > 0 ? parentId : undefined;

  if (!Number.isFinite(customerId)) {
    notFound();
  }

  if (action === "settings") {
    const { settings, widgets, customerName, errorMessage } =
      await fetchBackendCustomerDashboardSettings(customerId);

    return (
      <CustomerDashboardSettingsForm
        customerId={customerId}
        customerName={customerName}
        initial={settings}
        widgets={widgets}
        initialErrorMessage={errorMessage}
      />
    );
  }

  if (action === "impersonate") {
    const { row } = await fetchBackendCustomerRawById(customerId, parentCustomerId);
    const normalized = row ? normalizeCustomerRow(row) : null;
    if (!normalized?.customerUid) {
      notFound();
    }

    let parentRow = null;
    if (parentCustomerId) {
      const parentResult = await fetchBackendCustomerRawById(parentCustomerId);
      parentRow = parentResult.row;
    }

    const subdomain = row ? resolveImpersonationTenantSlug(row, parentRow) : "";
    if (!subdomain) {
      notFound();
    }

    const params = new URLSearchParams({ id: String(customerId) });
    if (parentCustomerId) {
      params.set("parentCustomer", String(parentCustomerId));
    }

    redirect(`/dashboard/customers/impersonate?${params.toString()}`);
  }

  if (action === "send-credentials") {
    const { credentials, customerName, errorMessage } =
      await fetchBackendCustomerCredentials(customerId, parentCustomerId);

    return (
      <CustomerCredentialsForm
        customerId={customerId}
        customerName={customerName}
        initial={credentials}
        initialErrorMessage={errorMessage}
        parentCustomerId={parentCustomerId}
      />
    );
  }

  const { customer, errorMessage } = await fetchBackendCustomerById(customerId, parentCustomerId);

  if (!customer) {
    notFound();
  }

  return (
    <CustomerCreateForm
      mode="update"
      customerId={customerId}
      initial={customer}
      initialErrorMessage={errorMessage}
    />
  );
}
