'use client'

import { use, useEffect, useState } from "react"
import { useRouter } from "next/navigation"
import { PageHeader } from "@/components/ui/page-header"
import { SectionCard } from "@/components/ui/section-card"
import { StatusBadge } from "@/components/ui/status-badge"
import { KpiCard } from "@/components/ui/kpi-card"
import { CustomerTabs } from "@/components/customer/customer-tabs"
import { CustomerWizard } from "@/components/customer/customer-wizard"
import { branchDisplayName, printCustomerProfilePdf } from "@/components/customer/customer-profile-pdf"
import { Modal } from "@/components/ui/modal"
import {
  Building2,
  Mail,
  Phone,
  Calendar,
  Lock,
  TrendingUp,
  Snowflake,
  Wallet,
  Coins,
  Activity,
  ShieldCheck,
  Pencil,
  CheckCircle,
  Ban,
  Download,
  KeyRound,
  ArrowUpCircle,
} from "lucide-react"
import { formatMoney, formatNumber, formatDateTime } from "@/lib/format"
import { useCustomers } from "@/hooks/useCustomers"
import { api } from "@/lib/api"
import { ENDPOINTS } from "@/constants/endpoints"
import { uploadCustomerKycDocuments } from "@/lib/kyc-documents"
import i18n from "@/lib/i18n";

const KYC_LEVEL_LABEL: Record<string, { label: string; tone: "success" | "pending" | "danger" | "warning" | "info" | "neutral" }> = {
  basic: { label: i18n.t('app.admin.customers.page.text_58'), tone: "info" },
  intermediate: { label: i18n.t('app.admin.customers.page.text_59'), tone: "warning" },
  premium: { label: i18n.t('app.admin.customers.page.text_60'), tone: "success" },
}

const STATUS_LABEL: Record<string, { label: string; tone: "success" | "pending" | "warning" | "danger" | "neutral" }> = {
  draft: { label: "Draft", tone: "neutral" },
  pending_kyc: { label: i18n.t('app.admin.customers.[id].page.text_12'), tone: "pending" },
  active: { label: i18n.t('app.admin.customers.[id].page.text_7'), tone: "success" },
  suspended: { label: i18n.t('app.admin.customers.[id].page.text_8'), tone: "danger" },
  rejected: { label: "Rejected", tone: "danger" },
  closed: { label: i18n.t('app.admin.customers.page.text_62'), tone: "neutral" },
  blocked: { label: i18n.t('app.admin.customers.[id].page.text_10'), tone: "danger" },
  pending: { label: i18n.t('app.admin.customers.[id].page.text_12'), tone: "pending" },
  archived: { label: i18n.t('app.admin.customers.page.text_62'), tone: "neutral" },
}

const TIER_LABEL: Record<string, string> = {
  retail: i18n.t('app.admin.customers.[id].page.text_13'),
  premium: i18n.t('app.admin.customers.[id].page.text_14'),
  institutional: i18n.t('app.admin.customers.[id].page.text_15'),
}

export default function CustomerProfilePage({
  params,
  searchParams,
}: {
  params: Promise<{ id: string }>
  searchParams: Promise<{ tab?: string }>
}) {
  const resolvedParams = use(params)
  const resolvedSearchParams = use(searchParams)
  const router = useRouter()
  
  const currentTab = resolvedSearchParams.tab ?? "overview"
  const { selectedItem: customer, fetchItemById, updateItem, loadingSingle, error } = useCustomers()
  
  const [cashWallet, setCashWallet] = useState<any>(null)
  const [goldWallet, setGoldWallet] = useState<any>(null)
  const [orders] = useState<any[]>([])
  const [transfers] = useState<any[]>([])
  const [redemptions] = useState<any[]>([])
  const [kyc, setKyc] = useState<any[]>([])
  const [audits, setAudits] = useState<any[]>([])
  const [notes] = useState<any[]>([])
  const [alerts] = useState<any[]>([])
  const [movements] = useState<any[]>([])
  const [statement, setStatement] = useState<any | null>(null)
  const [branchLookup, setBranchLookup] = useState<Record<string, string>>({})
  const [branchOptions, setBranchOptions] = useState<{ label: string; value: string }[]>([])
  const [countryOptions, setCountryOptions] = useState<{ label: string; value: string }[]>([])

  const [isChangingStatus, setIsChangingStatus] = useState(false)
  const [statusDialog, setStatusDialog] = useState<{ open: boolean; action: 'activate' | 'suspend' | 'block' | null }>({ open: false, action: null });
  const [actionReason, setActionReason] = useState("");
  const [quickAction, setQuickAction] = useState<{ open: boolean; action: 'raiseLimit' | 'resetSecurity' | 'freeze' | 'unfreeze' | 'close' | 'reopen' | null }>({ open: false, action: null })
  const [isQuickActionRunning, setIsQuickActionRunning] = useState(false)
  const [quickReason, setQuickReason] = useState("")
  const [editOpen, setEditOpen] = useState(false)
  const [isSavingEdit, setIsSavingEdit] = useState(false)
  const [limitForm, setLimitForm] = useState({
    limitType: "DAILY_BUY_LIMIT",
    currentLimit: "",
    requestedLimit: "",
    currency: "USD",
    durationType: "TEMPORARY",
  })

  useEffect(() => {
    fetchItemById(resolvedParams.id)
  }, [fetchItemById, resolvedParams.id])

  useEffect(() => {
    const fetchBranches = async () => {
      try {
        const res = await api.get(ENDPOINTS.BRANCHES.LIST, { params: { page: 1, page_size: 500 } })
        const raw = res.data?.items ?? res.items ?? res.data ?? res ?? []
        const branches = Array.isArray(raw) ? raw : []
        const lookup: Record<string, string> = {}
        branches.forEach((branch: any) => {
          if (!branch?.id) return
          lookup[branch.id] = i18n.language?.startsWith("ar")
            ? branch.name_ar || branch.name || branch.name_en || branch.code || branch.id
            : branch.name_en || branch.name || branch.name_ar || branch.code || branch.id
        })
        setBranchLookup(lookup)
        setBranchOptions(branches.map((branch: any) => ({
          value: branch.id,
          label: lookup[branch.id] || branch.code || branch.id,
        })))
      } catch (err) {
        console.error("Failed to fetch branches for export:", err)
      }
    }
    fetchBranches()
    api.get(ENDPOINTS.COUNTRIES.LIST, { params: { limit: 300 } }).then((res: any) => {
      const raw = res?.data?.data ?? res?.data?.items ?? res?.data ?? res?.items ?? res ?? []
      const countries = Array.isArray(raw) ? raw : []
      setCountryOptions(countries.map((country: any) => ({
        value: country.id,
        label: i18n.language?.startsWith('ar') ? country.name_ar || country.name_en : country.name_en || country.name_ar,
      })))
    }).catch(() => setCountryOptions([]))
  }, [])

  useEffect(() => {
    if (customer) {
      if ((customer as any).cash_wallets && (customer as any).cash_wallets.length > 0) {
        setCashWallet((customer as any).cash_wallets[0])
      }
      if ((customer as any).gold_wallets && (customer as any).gold_wallets.length > 0) {
        setGoldWallet((customer as any).gold_wallets[0])
      }

      const fetchRelatedData = async () => {
        try {
          const res = await api.get(`/audit/logs?entity_id=${customer.id}`)
          setAudits(res.data?.items ?? res.data ?? res.items ?? res ?? [])
        } catch (err) {
          console.error("Failed to fetch audits:", err)
        }

        try {
          const res = await api.get(ENDPOINTS.KYC.LIST, { params: { limit: 100 } })
          const apps = res.data ?? res.items ?? res ?? []
          setKyc(Array.isArray(apps) ? apps.filter((app: any) => app.user_id === customer.user_id) : [])
        } catch (err) {
          console.error("Failed to fetch KYC applications:", err)
          setKyc([])
        }

        try {
          const to = new Date()
          const from = new Date()
          from.setDate(to.getDate() - 30)
          const res = await api.get(ENDPOINTS.CUSTOMERS.STATEMENT(customer.id), {
            params: {
              from_date: from.toISOString().slice(0, 10),
              to_date: to.toISOString().slice(0, 10),
            },
          })
          setStatement(res.data ?? res)
        } catch (err) {
          console.error("Failed to fetch customer statement:", err)
          setStatement(null)
        }
      }
      fetchRelatedData()
    }
  }, [customer])

  const confirmStatusChange = (action: 'activate' | 'suspend' | 'block') => {
    if (action === 'activate') {
      executeStatusChange(action);
    } else {
      setStatusDialog({ open: true, action });
      setActionReason("");
    }
  };

  const executeStatusChange = async (action: 'activate' | 'suspend' | 'block', reason?: string) => {
    if (!customer) return;
    setIsChangingStatus(true)
    try {
      let endpoint = '';
      if (action === 'activate') endpoint = ENDPOINTS.CUSTOMERS.ACTIVATE(customer.id);
      else if (action === 'suspend') endpoint = ENDPOINTS.CUSTOMERS.SUSPEND(customer.id);
      else if (action === 'block') endpoint = ENDPOINTS.CUSTOMERS.BLOCK(customer.id);

      if (action === 'activate') {
        await api.post(endpoint)
      } else {
        await api.post(endpoint, { reason: reason || i18n.t('app.admin.customers.[id].page.text_16') })
      }
      await fetchItemById(resolvedParams.id)
      setStatusDialog({ open: false, action: null });
    } catch (err: any) {
      alert(err.response?.data?.detail || i18n.t('app.admin.customers.[id].page.text_17'))
    } finally {
      setIsChangingStatus(false)
    }
  }

  const exportProfile = async () => {
    if (!customer) return
    try {
      const payload = await api.post(ENDPOINTS.CUSTOMERS.EXPORT_PROFILE(customer.id))
      const exportedCustomer = payload?.customer ?? customer
      printCustomerProfilePdf({
        customer: exportedCustomer,
        cashWallet,
        goldWallet,
        statusLabel: STATUS_LABEL[exportedCustomer.status]?.label ?? exportedCustomer.status ?? "-",
        kycLabel: KYC_LEVEL_LABEL[exportedCustomer.kyc_level]?.label ?? exportedCustomer.kyc_level ?? "-",
        primaryBranchName: branchDisplayName(exportedCustomer.primary_branch_id, branchLookup),
        registeredBranchName: branchDisplayName(exportedCustomer.registered_at_branch_id, branchLookup),
        language: i18n.language || "ar",
        labels: {
          title: i18n.t('app.admin.customers.id.export.title'),
          generated: i18n.t('app.admin.customers.id.export.generated'),
          subtitle: i18n.t('app.admin.customers.id.export.subtitle'),
          profileInformation: i18n.t('app.admin.customers.id.export.profile_information'),
          customerCode: i18n.t('app.admin.customers.id.export.customer_code'),
          fullName: i18n.t('app.admin.customers.id.export.full_name'),
          email: i18n.t('app.admin.customers.id.export.email'),
          phone: i18n.t('app.admin.customers.id.export.phone'),
          status: i18n.t('app.admin.customers.id.export.status'),
          kycLevel: i18n.t('app.admin.customers.id.export.kyc_level'),
          identityType: i18n.t('app.admin.customers.id.export.identity_type'),
          identityNumber: i18n.t('app.admin.customers.id.export.identity_number'),
          identityExpiry: i18n.t('app.admin.customers.id.export.identity_expiry'),
          primaryBranch: i18n.t('app.admin.customers.id.export.primary_branch'),
          registeredBranch: i18n.t('app.admin.customers.id.export.registered_branch'),
          createdAt: i18n.t('app.admin.customers.id.export.created_at'),
          lastLogin: i18n.t('app.admin.customers.id.export.last_login'),
          cashAvailable: i18n.t('app.admin.customers.id.export.cash_available'),
          cashReserved: i18n.t('app.admin.customers.id.export.cash_reserved'),
          goldAvailable: i18n.t('app.admin.customers.id.export.gold_available'),
          goldReserved: i18n.t('app.admin.customers.id.export.gold_reserved'),
          goldUnit: i18n.t('app.admin.customers.id.export.gold_unit'),
          dashboard: i18n.t('app.admin.customers.id.export.dashboard'),
          confidential: i18n.t('app.admin.customers.id.export.confidential'),
        },
      }, `${exportedCustomer.customer_code || exportedCustomer.id}-profile.pdf`)
    } catch (err: any) {
      alert(err.response?.data?.detail || i18n.t('app.admin.customers.[id].page.text_17'))
    }
  }

  const openQuickAction = (action: 'raiseLimit' | 'resetSecurity' | 'freeze' | 'unfreeze' | 'close' | 'reopen') => {
    setQuickAction({ open: true, action })
    setQuickReason("")
  }

  const openEditModal = () => setEditOpen(true)

  const submitEdit = async (data: any) => {
    if (!customer) return
    setIsSavingEdit(true)
    try {
      const ok = await updateItem(customer.id, {
        full_name_ar: data.full_name_ar || null,
        email: data.email || null,
        phone: data.phone || null,
        kyc_level: data.kyc_level as any,
        identity_expiry_date: data.identity_expiry_date || null,
        primary_branch_id: data.primary_branch_id || null,
      })
      if (!ok) return
      await uploadCustomerKycDocuments(customer.id, data.kyc_documents)
      await fetchItemById(resolvedParams.id)
      setEditOpen(false)
      window.dispatchEvent(new Event("kyc-applications-updated"))
    } catch (err: any) {
      alert(err?.response?.data?.detail || err?.message || 'Failed to update customer')
    } finally {
      setIsSavingEdit(false)
    }
  }

  const executeQuickAction = async () => {
    if (!customer || !quickAction.action) return
    setIsQuickActionRunning(true)
    try {
      if (quickAction.action === "raiseLimit") {
        await api.post(ENDPOINTS.CUSTOMERS.LIMIT_CHANGE_REQUESTS(customer.id), {
          limit_type: limitForm.limitType,
          current_limit: limitForm.currentLimit || null,
          requested_limit: limitForm.requestedLimit,
          currency: limitForm.currency || null,
          duration_type: limitForm.durationType,
          reason: quickReason,
          attachments: [],
        })
      } else if (quickAction.action === "resetSecurity") {
        await api.post(ENDPOINTS.CUSTOMERS.FORCE_PASSWORD_RESET(customer.id))
      } else if (quickAction.action === "freeze") {
        await api.post(ENDPOINTS.CUSTOMERS.FREEZE(customer.id), {
          freeze_type: "FULL_ACCOUNT",
          reason_code: "ADMIN_REVIEW",
          reason_text: quickReason,
          notify_customer: true,
          duration_until: null,
          attachments: [],
        })
      } else if (quickAction.action === "unfreeze") {
        await api.post(ENDPOINTS.CUSTOMERS.UNFREEZE(customer.id), { reason: quickReason })
      } else if (quickAction.action === "close") {
        await api.post(ENDPOINTS.CUSTOMERS.CLOSE(customer.id), { reason: quickReason })
      } else if (quickAction.action === "reopen") {
        await api.post(ENDPOINTS.CUSTOMERS.REOPEN(customer.id))
      }
      await fetchItemById(resolvedParams.id)
      setQuickAction({ open: false, action: null })
    } catch (err: any) {
      alert(err.response?.data?.detail || i18n.t('app.admin.customers.[id].page.text_17'))
    } finally {
      setIsQuickActionRunning(false)
    }
  }

  if (loadingSingle && !customer) {
    return (
      <div className="flex items-center justify-center py-20">
        <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary"></div>
      </div>
    )
  }

  if (error || !customer) {
    return (
      <div className="flex items-center justify-center py-20">
        <p className="text-[14px] text-red-600">{error || i18n.t('app.admin.customers.[id].page.text_18')}</p>
      </div>
    )
  }

  const status = STATUS_LABEL[customer.status] ?? { label: customer.status, tone: "neutral" as const }
  const kycBadge = KYC_LEVEL_LABEL[customer.kyc_level] ?? { label: customer.kyc_level, tone: "neutral" as const }
  const displayName = customer.name || customer.email || customer.phone || customer.user_id.slice(0, 8)

  return (
    <>
      <PageHeader
        breadcrumbs={[
          { label: i18n.t('app.admin.customers.[id].page.text_19'), href: "/" },
          { label: i18n.t('app.admin.customers.[id].page.text_20'), href: "/customers" },
          { label: (customer as any).customer_code || i18n.t('app.admin.customers.[id].page.text_21') },
        ]}
        title={displayName}
        description={i18n.t('app.admin.customers.[id].page.text_22')}
        badge={
          <div className="flex items-center gap-1.5">
            <StatusBadge tone={status.tone}>{status.label}</StatusBadge>
            <StatusBadge tone="gold">{TIER_LABEL[(customer as any).tier] ?? (customer as any).tier ?? customer.identity_type}</StatusBadge>
            <StatusBadge tone={kycBadge.tone} dot={false}>
              {kycBadge.label}
            </StatusBadge>
          </div>
        }
        actions={
          <>
            <button onClick={exportProfile} className="h-9 px-3 rounded-lg border border-border bg-card text-[12.5px] font-medium hover:bg-muted transition inline-flex items-center gap-1.5">
              <Download className="h-3.5 w-3.5" />
              {i18n.t('app.admin.customers.id.page.text_export')}
            </button>
            <button onClick={() => openQuickAction("raiseLimit")} className="h-9 px-3 rounded-lg border border-border bg-card text-[12.5px] font-medium hover:bg-muted transition inline-flex items-center gap-1.5">
              <ArrowUpCircle className="h-3.5 w-3.5" />
              {i18n.t('app.admin.customers.id.page.text_raise_limit')}
            </button>
            <button onClick={() => openQuickAction("resetSecurity")} className="h-9 px-3 rounded-lg border border-border bg-card text-[12.5px] font-medium hover:bg-muted transition inline-flex items-center gap-1.5">
              <KeyRound className="h-3.5 w-3.5" />
              {i18n.t('app.admin.customers.id.page.text_reset_security')}
            </button>
            <button onClick={openEditModal} className="h-9 px-3 rounded-lg border border-border bg-card text-[12.5px] font-medium hover:bg-muted transition inline-flex items-center gap-1.5">
              <Pencil className="h-3.5 w-3.5" />
              {i18n.t('app.admin.customers.[id].page.text_41')}</button>
            {customer.status === 'active' ? (
              <>
                <button
                  onClick={() => openQuickAction('freeze')}
                  disabled={isQuickActionRunning}
                  className="h-9 px-3 rounded-lg border border-red-200 bg-red-50 text-[12.5px] font-semibold text-red-700 hover:bg-red-100 transition inline-flex items-center gap-1.5 disabled:opacity-50"
                >
                  <Snowflake className="h-3.5 w-3.5" />
                  {i18n.t('app.admin.customers.id.page.text_freeze')}</button>
                <button
                  onClick={() => confirmStatusChange('suspend')}
                  disabled={isChangingStatus}
                  className="h-9 px-3 rounded-lg border border-red-200 bg-red-50 text-[12.5px] font-semibold text-red-700 hover:bg-red-100 transition inline-flex items-center gap-1.5 disabled:opacity-50"
                >
                  <Snowflake className="h-3.5 w-3.5" />
                  {i18n.t('app.admin.customers.[id].page.text_42')}</button>
                <button
                  onClick={() => confirmStatusChange('block')}
                  disabled={isChangingStatus}
                  className="h-9 px-3 rounded-lg border border-red-800 bg-red-100 text-[12.5px] font-semibold text-red-900 hover:bg-red-200 transition inline-flex items-center gap-1.5 disabled:opacity-50"
                >
                  <Ban className="h-3.5 w-3.5" />
                  {i18n.t('app.admin.customers.[id].page.text_43')}</button>
                <button
                  onClick={() => openQuickAction('close')}
                  disabled={isQuickActionRunning}
                  className="h-9 px-3 rounded-lg border border-border bg-card text-[12.5px] font-semibold text-foreground hover:bg-muted transition inline-flex items-center gap-1.5 disabled:opacity-50"
                >
                  <Ban className="h-3.5 w-3.5" />
                  {i18n.t('app.admin.customers.id.page.text_close')}</button>
              </>
            ) : customer.status === 'suspended' || customer.status === 'blocked' ? (
              <button
                onClick={() => openQuickAction('unfreeze')}
                disabled={isQuickActionRunning}
                className="h-9 px-3 rounded-lg border border-green-200 bg-green-50 text-[12.5px] font-semibold text-green-700 hover:bg-green-100 transition inline-flex items-center gap-1.5 disabled:opacity-50"
              >
                <CheckCircle className="h-3.5 w-3.5" />
                {i18n.t('app.admin.customers.id.page.text_unfreeze')}</button>
            ) : customer.status === 'closed' || customer.status === 'archived' ? (
              <button
                onClick={() => openQuickAction('reopen')}
                disabled={isQuickActionRunning}
                className="h-9 px-3 rounded-lg border border-green-200 bg-green-50 text-[12.5px] font-semibold text-green-700 hover:bg-green-100 transition inline-flex items-center gap-1.5 disabled:opacity-50"
              >
                <CheckCircle className="h-3.5 w-3.5" />
                {i18n.t('app.admin.customers.id.page.text_reopen')}</button>
            ) : customer.status === 'pending_kyc' || customer.status === 'pending' ? (
              <button
                onClick={() => router.push(`/kyc?customer=${customer.id}`)}
                className="h-9 px-3 rounded-lg border border-green-200 bg-green-50 text-[12.5px] font-semibold text-green-700 hover:bg-green-100 transition inline-flex items-center gap-1.5 disabled:opacity-50"
              >
                <ShieldCheck className="h-3.5 w-3.5" />
                {i18n.language?.startsWith('ar') ? 'مراجعة التحقق' : 'Review KYC'}</button>
            ) : (
              <button
                onClick={() => confirmStatusChange('activate')}
                disabled={isChangingStatus}
                className="h-9 px-3 rounded-lg border border-green-200 bg-green-50 text-[12.5px] font-semibold text-green-700 hover:bg-green-100 transition inline-flex items-center gap-1.5 disabled:opacity-50"
              >
                <CheckCircle className="h-3.5 w-3.5" />
                {i18n.t('app.admin.customers.[id].page.text_44')}</button>
            )}
            
            <button className="h-9 px-3 rounded-lg bg-gold-500 hover:bg-gold-600 text-white text-[12.5px] font-semibold inline-flex items-center gap-1.5 transition">
              <TrendingUp className="h-3.5 w-3.5" />
              {i18n.t('app.admin.customers.[id].page.text_45')}</button>
          </>
        }
      />

      {/* Balance KPIs */}
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-3 mb-4">
        <KpiCard
          label={i18n.t('app.admin.customers.[id].page.text_23')}
          value={formatMoney(cashWallet?.available_balance ?? 0)}
          icon={Wallet}
          tone="info"
          hint={cashWallet ? i18n.t('app.admin.page.text_held', { amount: formatMoney(cashWallet.reserved_balance ?? 0) }) : i18n.t('app.admin.customers.[id].page.text_24')}
          accent
        />
        <KpiCard
          label={i18n.t('app.admin.customers.[id].page.text_25')}
          value={formatNumber(goldWallet?.available_grams ?? 0, 2)}
          unit="g"
          icon={Coins}
          tone="gold"
          hint={goldWallet ? i18n.t('app.admin.customers.id.page.text_held_grams', { amount: formatNumber(goldWallet.reserved_grams ?? 0, 2) }) : i18n.t('app.admin.customers.[id].page.text_26')}
          accent
        />
        <KpiCard
          label={i18n.t('app.admin.customers.[id].page.text_27')}
          value={formatNumber(orders.length, 0)}
          icon={Activity}
          tone="default"
          hint={i18n.t('app.admin.customers.id.page.text_txs', { transfers: transfers.length, redemptions: redemptions.length })}
        />
        <KpiCard
          label={i18n.t('app.admin.customers.[id].page.text_28')}
          value={formatNumber((customer as any).risk_score ?? 0, 0)}
          unit="/ 100"
          icon={ShieldCheck}
          tone={(customer as any).risk_score >= 70 ? "danger" : (customer as any).risk_score >= 40 ? "warning" : "success"}
          hint={alerts.length ? i18n.t('app.admin.customers.id.page.text_alerts', { count: alerts.length }) : i18n.t('app.admin.customers.[id].page.text_29')}
        />
      </div>

      <div className="grid grid-cols-1 xl:grid-cols-3 gap-4 mb-4">
        <SectionCard
          title={i18n.t('app.admin.customers.[id].page.text_30')}
          icon={<Building2 className="h-5 w-5 text-gold-600" />}
          className="xl:col-span-2"
        >
          <div className="grid grid-cols-1 md:grid-cols-2 gap-5">
            <div className="space-y-3">
              <Row label={i18n.t('app.admin.customers.[id].page.text_31')} value={(customer as any).customer_code} />
              <Row label={i18n.t('app.admin.customers.[id].page.text_32')} value={displayName} />
              <Row label={i18n.t('app.admin.customers.[id].page.text_49')} value={customer.identity_number} />
              <Row label={i18n.t('app.admin.customers.[id].page.text_34')} value={TIER_LABEL[(customer as any).tier] ?? (customer as any).tier ?? customer.identity_type} />
              <Row label={i18n.t('app.admin.customers.[id].page.text_35')} value={(customer as any).two_factor_enabled ? i18n.t('app.admin.customers.[id].page.text_36') : i18n.t('app.admin.customers.[id].page.text_37')} />
              <Row label={i18n.t('app.admin.customers.[id].page.text_38')} value={formatNumber((customer as any).linked_devices ?? 0, 0)} />
            </div>
            <div className="space-y-3 md:border-r md:border-border md:pr-5">
              <div className="flex items-center gap-2.5 text-[13px]">
                <Mail className="h-4 w-4 text-gold-600 shrink-0" />
                <span className="text-foreground truncate">{customer.email ?? "—"}</span>
              </div>
              <div className="flex items-center gap-2.5 text-[13px]">
                <Phone className="h-4 w-4 text-gold-600 shrink-0" />
                <span className="text-foreground tabular-nums">{customer.phone ?? "—"}</span>
              </div>
              <div className="flex items-center gap-2.5 text-[13px]">
                <Calendar className="h-4 w-4 text-gold-600 shrink-0" />
                <span className="text-foreground">
                  {i18n.t('app.admin.customers.[id].page.text_46')}{formatDateTime((customer as any).registered_at || customer.created_at)}
                </span>
              </div>
              <div className="flex items-center gap-2.5 text-[13px]">
                <Lock className="h-4 w-4 text-gold-600 shrink-0" />
                <span className="text-foreground">
                  {i18n.t('app.admin.customers.[id].page.text_47')}{(customer as any).last_login_at ? formatDateTime((customer as any).last_login_at) : '—'}
                  {(customer as any).last_login_ip ? i18n.t('app.admin.customers.id.page.text_from_ip', { ip: (customer as any).last_login_ip }) : ""}
                </span>
              </div>
            </div>
          </div>
        </SectionCard>


      </div>

      <Modal
        open={statusDialog.open}
        onClose={() => setStatusDialog({ open: false, action: null })}
        title={i18n.t('app.admin.customers.id.page.text_confirm_action')}
        description={i18n.t('app.admin.customers.id.page.text_provide_reason')}
      >
        <div className="space-y-4 pt-2">
          <label className="block text-[12.5px] font-medium text-foreground">
            {i18n.t('app.admin.customers.id.page.text_reason')} <span className="text-red-500">*</span>
          </label>
          <textarea
            value={actionReason}
            onChange={(e) => setActionReason(e.target.value)}
            className="w-full px-3 py-2 border border-border rounded-lg text-sm bg-background"
            rows={3}
            placeholder={i18n.t('app.admin.customers.id.page.text_reason_placeholder')}
          />
          <div className="flex justify-end gap-2 pt-4">
            <button
              onClick={() => setStatusDialog({ open: false, action: null })}
              className="px-4 py-2 border border-border rounded-lg text-sm font-medium hover:bg-muted"
            >
              {i18n.t('app.admin.customers.id.page.text_cancel')}
            </button>
            <button
              onClick={() => {
                if (statusDialog.action && actionReason.trim()) {
                  executeStatusChange(statusDialog.action, actionReason);
                }
              }}
              disabled={!actionReason.trim() || isChangingStatus}
              className="px-4 py-2 bg-red-600 text-white rounded-lg text-sm font-medium hover:bg-red-700 disabled:opacity-50"
            >
              {i18n.t('app.admin.customers.id.page.text_confirm')}
            </button>
          </div>
        </div>
      </Modal>

      <Modal
        open={quickAction.open}
        onClose={() => setQuickAction({ open: false, action: null })}
        title={
          quickAction.action === "raiseLimit"
            ? i18n.t('app.admin.customers.id.page.text_raise_limit')
            : quickAction.action === "resetSecurity"
              ? i18n.t('app.admin.customers.id.page.text_reset_security')
              : i18n.t('app.admin.customers.id.page.text_confirm_action')
        }
        description={
          quickAction.action === "resetSecurity"
            ? i18n.t('app.admin.customers.id.page.text_reset_security_desc')
            : i18n.t('app.admin.customers.id.page.text_provide_reason')
        }
      >
        <div className="space-y-4 pt-2">
          {quickAction.action === "raiseLimit" && (
            <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
              <label className="block text-[12.5px] font-medium text-foreground">
                {i18n.t('app.admin.customers.id.page.text_limit_type')}
                <select
                  value={limitForm.limitType}
                  onChange={(e) => setLimitForm((prev) => ({ ...prev, limitType: e.target.value }))}
                  className="mt-1 w-full px-3 py-2 border border-border rounded-lg text-sm bg-background"
                >
                  <option value="DAILY_BUY_LIMIT">{i18n.t('app.admin.customers.id.page.limit_daily_buy')}</option>
                  <option value="DAILY_SELL_LIMIT">{i18n.t('app.admin.customers.id.page.limit_daily_sell')}</option>
                  <option value="DAILY_TRANSFER_LIMIT">{i18n.t('app.admin.customers.id.page.limit_daily_transfer')}</option>
                  <option value="SINGLE_TRANSACTION_LIMIT">{i18n.t('app.admin.customers.id.page.limit_single_transaction')}</option>
                  <option value="DAILY_REDEMPTION_LIMIT">{i18n.t('app.admin.customers.id.page.limit_daily_redemption')}</option>
                </select>
              </label>
              <label className="block text-[12.5px] font-medium text-foreground">
                {i18n.t('app.admin.customers.id.page.text_currency')}
                <input
                  value={limitForm.currency}
                  onChange={(e) => setLimitForm((prev) => ({ ...prev, currency: e.target.value }))}
                  className="mt-1 w-full px-3 py-2 border border-border rounded-lg text-sm bg-background"
                />
              </label>
              <label className="block text-[12.5px] font-medium text-foreground">
                {i18n.t('app.admin.customers.id.page.text_current_limit')}
                <input
                  value={limitForm.currentLimit}
                  onChange={(e) => setLimitForm((prev) => ({ ...prev, currentLimit: e.target.value }))}
                  className="mt-1 w-full px-3 py-2 border border-border rounded-lg text-sm bg-background"
                  inputMode="decimal"
                />
              </label>
              <label className="block text-[12.5px] font-medium text-foreground">
                {i18n.t('app.admin.customers.id.page.text_requested_limit')} <span className="text-red-500">*</span>
                <input
                  value={limitForm.requestedLimit}
                  onChange={(e) => setLimitForm((prev) => ({ ...prev, requestedLimit: e.target.value }))}
                  className="mt-1 w-full px-3 py-2 border border-border rounded-lg text-sm bg-background"
                  inputMode="decimal"
                />
              </label>
            </div>
          )}
          {quickAction.action !== "resetSecurity" && quickAction.action !== "reopen" && (
            <>
              <label className="block text-[12.5px] font-medium text-foreground">
                {i18n.t('app.admin.customers.id.page.text_reason')} <span className="text-red-500">*</span>
              </label>
              <textarea
                value={quickReason}
                onChange={(e) => setQuickReason(e.target.value)}
                className="w-full px-3 py-2 border border-border rounded-lg text-sm bg-background"
                rows={3}
                placeholder={i18n.t('app.admin.customers.id.page.text_reason_placeholder')}
              />
            </>
          )}
          <div className="flex justify-end gap-2 pt-4">
            <button
              onClick={() => setQuickAction({ open: false, action: null })}
              className="px-4 py-2 border border-border rounded-lg text-sm font-medium hover:bg-muted"
            >
              {i18n.t('app.admin.customers.id.page.text_cancel')}
            </button>
            <button
              onClick={executeQuickAction}
              disabled={
                isQuickActionRunning ||
                (quickAction.action === "raiseLimit" && (!limitForm.requestedLimit.trim() || !quickReason.trim())) ||
                (quickAction.action !== "raiseLimit" && quickAction.action !== "resetSecurity" && quickAction.action !== "reopen" && !quickReason.trim())
              }
              className="px-4 py-2 bg-gold-600 text-white rounded-lg text-sm font-medium hover:bg-gold-700 disabled:opacity-50"
            >
              {i18n.t('app.admin.customers.id.page.text_confirm')}
            </button>
          </div>
        </div>
      </Modal>

      <CustomerWizard
        open={editOpen}
        onClose={() => setEditOpen(false)}
        onSubmit={submitEdit}
        initialData={customer}
        branches={branchOptions}
        countries={countryOptions}
        isLoading={isSavingEdit}
      />

      <CustomerTabs
        current={currentTab}
        customer={customer}
        cashWallet={cashWallet}
        goldWallet={goldWallet}
        orders={orders}
        transfers={transfers}
        redemptions={redemptions}
        kyc={kyc}
        audits={audits}
        notes={notes}
        alerts={alerts}
        movements={movements}
        statement={statement}
      />
    </>
  )
}

function Row({ label, value }: { label: string; value: string | null | undefined }) {
  return (
    <div className="flex items-start justify-between gap-3">
      <span className="text-[12.5px] text-muted-foreground">{label}</span>
      <span className="text-[12.5px] font-semibold text-foreground text-left tabular-nums">
        {value ?? "—"}
      </span>
    </div>
  )
}
