import { notFound } from "next/navigation";

import { CustomerPageShell } from "@/app/customer/_components/customer-page-shell";
import {
  fetchAccessCustomer,
  fetchAccessCustomers,
  fetchAccessUsers,
} from "@/app/customer/_lib/admin/access-server-api";
import { normalizeFormDate } from "@/app/customer/_lib/normalize-form-date";
import { PHONE_COUNTRIES } from "@/app/dashboard/customers/_components/customer-form/constants";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";

import {
  TenantCustomerAccountForm,
  type TenantCustomerAccountFormValues,
} from "./_components/tenant-customer-account-form";
import {
  TenantCustomerEditForm,
  type TenantCustomerEditFormValues,
} from "./_components/tenant-customer-edit-form";

type PageProps = {
  params: Promise<{ tenant: string; id: string }>;
};

/** Split a stored `+<dial><digits>` phone into a country code and local digits. */
function splitPhone(raw: string | null): { country: string; digits: string } {
  const value = (raw ?? "").trim();
  if (!value) {
    return { country: "AE", digits: "" };
  }

  const match = [...PHONE_COUNTRIES]
    .filter((country) => value.startsWith(country.dial))
    .sort((a, b) => b.dial.length - a.dial.length)[0];

  if (match) {
    return { country: match.code, digits: value.slice(match.dial.length).replace(/\D/g, "") };
  }

  return { country: "AE", digits: value.replace(/\D/g, "") };
}

export default async function CustomerAdminEditCustomerPage({ params }: Readonly<PageProps>) {
  const { tenant, id } = await params;
  const customerId = Number(id);

  if (!Number.isInteger(customerId) || customerId <= 0) {
    notFound();
  }

  const [detailResult, usersResult, customersResult] = await Promise.all([
    fetchAccessCustomer(tenant, customerId),
    fetchAccessUsers(tenant),
    fetchAccessCustomers(tenant),
  ]);

  const customer = detailResult.customer;
  if (!customer) {
    if (detailResult.errorMessage) {
      return (
        <CustomerPageShell>
          <TenantCustomerEditFormFallbackError message={detailResult.errorMessage} />
        </CustomerPageShell>
      );
    }
    notFound();
  }

  const staff = (usersResult.data?.items ?? []).map((user) => ({
    id: user.id,
    name: user.name,
    email: user.email,
    groupId: user.group_id,
    groupName: user.group_name,
  }));

  const { country, digits } = splitPhone(customer.phone);

  const initialValues: TenantCustomerEditFormValues = {
    assigned_to: customer.assigned_to.map(String),
    primary_rm: customer.primary_rm.map(String),
    joined_date: customer.joined_date ?? "",
    first_name: customer.first_name ?? "",
    last_name: customer.last_name ?? "",
    phone_country: country,
    phone: digits,
    email: customer.email ?? "",
    confirm_email: customer.email ?? "",
    password: "",
    con_password: "",
    timezone: customer.timezone ?? "UTC",
    company_name: customer.company_name ?? "",
    registration_number: customer.registration_number ?? "",
    company_address: customer.company_address ?? "",
    send_credential: false,
  };

  const accountInitialValues: TenantCustomerAccountFormValues = {
    ucap_unique_client_number: customer.ucap_unique_client_number ?? "",
    client_type: customer.client_type ?? "",
    client_residency: customer.client_residency ?? "",
    client_status: customer.client_status ?? "",
    pep: customer.pep ?? "",
    relationship_type: customer.relationship_type ?? "",
    investment_risk_profile: customer.investment_risk_profile ?? "",
    risk_tolerance: customer.risk_tolerance ?? "",
    risk_ability: customer.risk_ability ?? "",
    risk_profile: customer.risk_profile ?? "",
    level_of_due_diligence: customer.level_of_due_diligence ?? "",
    date_of_last_review: normalizeFormDate(customer.date_of_last_review),
    date_of_next_review: normalizeFormDate(customer.date_of_next_review),
    manager_id: customer.manager_id != null ? String(customer.manager_id) : "",
    relationship_manager_name: customer.relationship_manager_name ?? "",
    advisory_fee: customer.advisory_fee ?? "",
    business_introducer_name: customer.business_introducer_name ?? "",
    business_introducer_fee: customer.business_introducer_fee ?? "",
  };

  return (
    <CustomerPageShell>
      <Tabs defaultValue="login" className="gap-5">
        <TabsList>
          <TabsTrigger value="login">Login Information</TabsTrigger>
          <TabsTrigger value="account">Account Information</TabsTrigger>
        </TabsList>

        <TabsContent value="login">
          <TenantCustomerEditForm
            tenant={tenant}
            customerId={customerId}
            accountId={customer.subdomain ?? ""}
            initialValues={initialValues}
            staff={staff}
            groups={customersResult.data?.groups ?? usersResult.data?.groups ?? []}
            initialErrorMessage={usersResult.errorMessage ?? customersResult.errorMessage}
          />
        </TabsContent>

        <TabsContent value="account">
          <TenantCustomerAccountForm
            tenant={tenant}
            customerId={customerId}
            initialValues={accountInitialValues}
            staff={staff.map((member) => ({
              id: member.id,
              name: member.name,
              email: member.email,
            }))}
            documents={{
              passport_copy: customer.passport_copy,
              second_id_copy: customer.second_id_copy,
              residence_proof_copy: customer.residence_proof_copy,
            }}
          />
        </TabsContent>
      </Tabs>
    </CustomerPageShell>
  );
}

function TenantCustomerEditFormFallbackError({ message }: { message: string }) {
  return (
    <div className="rounded-lg border border-destructive/40 bg-destructive/5 p-4 text-sm text-destructive">
      {message}
    </div>
  );
}
