import { cookies } from "next/headers";
import Link from "next/link";

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 { Button } from "@/components/ui/button";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";

import {
  editCustomerCookieName,
  parseEditCustomerId,
} from "../_lib/edit-customer-cookie";
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 }>;
};

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, "") };
}

/** Edit customer — id is selected via POST /edit/select (cookie), not the page URL. */
export default async function CustomerAdminEditCustomerPage({ params }: Readonly<PageProps>) {
  const { tenant } = await params;
  const listHref = `/customer/${tenant}/admin/customers`;

  const cookieStore = await cookies();
  const customerId = parseEditCustomerId(
    cookieStore.get(editCustomerCookieName(tenant))?.value,
  );

  if (!customerId) {
    return (
      <CustomerPageShell>
        <div className="space-y-4 rounded-lg border border-destructive/40 bg-destructive/5 p-4 text-sm text-destructive">
          <p>No customer selected for editing. Open Edit from the customers list.</p>
          <Button asChild type="button" variant="outline" size="sm">
            <Link href={listHref}>Back to customers</Link>
          </Button>
        </div>
      </CustomerPageShell>
    );
  }

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

  const customer = detailResult.customer;
  if (!customer) {
    return (
      <CustomerPageShell>
        <div className="space-y-4 rounded-lg border border-destructive/40 bg-destructive/5 p-4 text-sm text-destructive">
          <p>{detailResult.errorMessage ?? "Customer not found."}</p>
          <Button asChild type="button" variant="outline" size="sm">
            <Link href={listHref}>Back to customers</Link>
          </Button>
        </div>
      </CustomerPageShell>
    );
  }

  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 ?? "",
    short_name: customer.short_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,
    is_mandate_customer: Boolean(customer.is_mandate_customer),
  };

  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>
  );
}
