'use client';

import type { ActionDef, BulkActionDef, ColumnDef } from '@/components/ui/domain/admin/AdminTable';
import type { AdminFilterSelect, FilterChip } from '@/components/ui/domain/admin/AdminFilterBar';
import { Button } from '@/components/ui/primitives/Button';
import { Pill } from '@/components/ui/primitives/Pill';
import { StatusBadge } from '@/components/ui/domain/StatusBadge/StatusBadge';
import { cn } from '@/lib/cn';
import { formatDate } from '@/lib/format';
import type { Locale, StringBundle } from '@/lib/i18n';
import type { UserRow, UserMatchKind } from './UsersMgmt';
import type { UsersMgmtSegment } from './UsersMgmtFilterBar';
import {
  ACCOUNT_STATE_STATUS_MAP,
  PAGE_LIMIT,
  SELECT_ALL,
  isoDaysAgo,
  userDisplayLabel,
} from './usersMgmt.shared';
import { interpolate } from '@/lib/i18n/interpolate';

type AdminUsersKey = keyof StringBundle['admin_users'];
type AdminListKey = keyof StringBundle['admin_list'];

interface ConfigDeps {
  t: (key: AdminUsersKey) => string;
  tList: (key: AdminListKey) => string;
  locale: Locale;
  cityOptions: { value: string; label: string }[];
  copyToClipboard: (text: string, ariaLabel: string) => void | Promise<void>;
  openDrawer: (user: UserRow) => void;
  openQuickFreeze: (user: UserRow) => void;
  unfreezeUser: (userId: string) => void | Promise<void>;
  selectedIds: string[];
  openBulkFreeze: () => void;
}

export function createUsersMgmtSegments(t: (key: AdminUsersKey) => string): UsersMgmtSegment[] {
  return [
    { key: 'frozen', label: t('seg_frozen'), params: { states: 'FROZEN', sort: 'joined_desc' } },
    {
      key: 'new7d',
      label: t('seg_new7d'),
      params: { joinedFrom: isoDaysAgo(7), sort: 'joined_desc' },
    },
    {
      key: 'pending',
      label: t('seg_pending'),
      params: { states: 'DELETED_PENDING', sort: 'joined_desc' },
    },
    {
      key: 'affiliates',
      label: t('seg_affiliates'),
      params: { roles: 'affiliate', sort: 'name_asc' },
    },
    { key: 'vendors', label: t('seg_vendors'), params: { roles: 'vendor', sort: 'name_asc' } },
  ];
}

export function createUsersMgmtChips(t: (key: AdminUsersKey) => string): {
  stateMultiChips: FilterChip[];
  activityChips: FilterChip[];
  completenessChips: FilterChip[];
} {
  return {
    stateMultiChips: [
      { key: 'states', value: 'ACTIVE', label: t('state_active'), groupLabel: t('filter_state') },
      { key: 'states', value: 'FROZEN', label: t('state_frozen'), groupLabel: t('filter_state') },
      {
        key: 'states',
        value: 'DELETED_PENDING',
        label: t('state_deleted_pending'),
        groupLabel: t('filter_state'),
      },
      { key: 'states', value: 'DELETED', label: t('state_deleted'), groupLabel: t('filter_state') },
    ],
    activityChips: [
      {
        key: 'purchaseActivity',
        value: 'has',
        label: t('activity_has'),
        groupLabel: t('filter_activity'),
      },
      {
        key: 'purchaseActivity',
        value: 'none',
        label: t('activity_none'),
        groupLabel: t('filter_activity'),
      },
    ],
    completenessChips: [
      {
        key: 'hasEmail',
        value: 'true',
        label: t('filter_has_email'),
        groupLabel: t('filter_has_email'),
      },
      {
        key: 'emailVerified',
        value: 'true',
        label: t('filter_email_verified'),
        groupLabel: t('filter_email_verified'),
      },
      {
        key: 'hasShippingAddress',
        value: 'true',
        label: t('filter_has_address'),
        groupLabel: t('filter_has_address'),
      },
    ],
  };
}

export function createUsersMgmtFilterSelects(
  t: (key: AdminUsersKey) => string,
  cityOptions: { value: string; label: string }[],
): AdminFilterSelect[] {
  return [
    {
      key: 'roles',
      label: t('filter_role'),
      options: [
        { value: SELECT_ALL, label: t('filter_all') },
        { value: 'admin', label: t('role_admin') },
        { value: 'vendor', label: t('role_vendor') },
        { value: 'affiliate', label: t('role_affiliate') },
        { value: 'customer', label: t('role_customer') },
      ],
    },
    {
      key: 'cityCode',
      label: t('filter_city'),
      options:
        cityOptions.length > 0 ? cityOptions : [{ value: SELECT_ALL, label: t('filter_all') }],
    },
    {
      key: 'sort',
      label: t('sort_label'),
      options: [
        { value: 'joined_desc', label: t('sort_joined_desc') },
        { value: 'joined_asc', label: t('sort_joined_asc') },
        { value: 'purchases_desc', label: t('sort_purchases_desc') },
        { value: 'name_asc', label: t('sort_name_asc') },
      ],
    },
  ];
}

export function createUsersMgmtColumns({
  t,
  locale,
  copyToClipboard,
}: Pick<ConfigDeps, 't' | 'locale' | 'copyToClipboard'>): ColumnDef<UserRow>[] {
  return [
    {
      key: 'displayName',
      label: t('col_display'),
      render: (r) => <span className="text-text-primary font-medium">{userDisplayLabel(r)}</span>,
    },
    { key: 'realName', label: t('col_real_name'), render: (r) => r.realName || null },
    { key: 'defaultCity', label: t('col_city'), render: (r) => r.defaultCity || null },
    {
      key: 'email',
      label: t('col_email'),
      render: (r) =>
        r.email ? (
          <Button
            type="button"
            variant="ghost"
            size="sm"
            onClick={(e) => {
              e.stopPropagation();
              void copyToClipboard(r.email!, t('copy_email'));
            }}
            className={cn(
              'inline-flex items-center gap-1 rounded-md px-2 py-0.5 text-sm',
              'bg-surface-raised text-text-secondary border-border-default border',
            )}
            aria-label={t('copy_email')}
          >
            <span dir="ltr">{r.email}</span>
            <span className="text-text-muted text-xs">{t('copy')}</span>
          </Button>
        ) : null,
    },
    {
      key: 'accountState',
      label: t('filter_state'),
      render: (r) => (
        <StatusBadge
          state={r.accountState}
          map={ACCOUNT_STATE_STATUS_MAP}
          ns="admin_users"
          size="sm"
        />
      ),
    },
    {
      key: 'purchaseCount',
      label: t('col_purchases'),
      align: 'end',
      render: (r) => String(r.purchaseCount),
    },
    {
      key: 'isAdmin',
      label: t('admin_badge'),
      align: 'center',
      render: (r) =>
        r.isAdmin ? (
          <Pill tone="info" size="sm">
            {t('admin_badge')}
          </Pill>
        ) : null,
    },
    {
      key: 'createdAt',
      label: t('joined_label'),
      render: (r) => formatDate(r.createdAt, locale),
    },
  ];
}

export function createUsersMgmtActions({
  t,
  copyToClipboard,
  openQuickFreeze,
  unfreezeUser,
  openDrawer,
}: Pick<
  ConfigDeps,
  't' | 'copyToClipboard' | 'openQuickFreeze' | 'unfreezeUser' | 'openDrawer'
>): ActionDef<UserRow>[] {
  return [
    {
      key: 'copy-phone',
      label: t('copy_phone'),
      hidden: (r) => !r.phoneHint,
      onAction: (r) => {
        if (r.phoneHint) void copyToClipboard(r.phoneHint, t('copy_phone'));
      },
    },
    {
      key: 'copy-email',
      label: t('copy_email'),
      hidden: (r) => !r.email,
      onAction: (r) => {
        if (r.email) void copyToClipboard(r.email, t('copy_email'));
      },
    },
    {
      key: 'copy-id',
      label: t('copy_id'),
      onAction: (r) => void copyToClipboard(r.id, t('copy_id')),
    },
    {
      key: 'freeze',
      label: t('freeze'),
      variant: 'danger',
      hidden: (r) => r.accountState === 'FROZEN',
      onAction: openQuickFreeze,
    },
    {
      key: 'unfreeze',
      label: t('unfreeze'),
      hidden: (r) => r.accountState !== 'FROZEN',
      onAction: (r) => void unfreezeUser(r.id),
    },
    { key: 'more', label: t('more_actions'), onAction: openDrawer },
  ];
}

export function createUsersMgmtBulkActions({
  t,
  selectedIds,
  openBulkFreeze,
}: Pick<ConfigDeps, 't' | 'selectedIds' | 'openBulkFreeze'>): BulkActionDef[] {
  if (selectedIds.length === 0) return [];
  return [
    {
      key: 'bulk-freeze',
      label: t('bulk_freeze'),
      variant: 'danger',
      onClick: openBulkFreeze,
    },
  ];
}

export function createUsersMgmtSuggestions(data: UserRow[]) {
  return data.slice(0, 8).map((r) => ({ id: r.id, label: userDisplayLabel(r) }));
}

export function createUsersMgmtSubtitle(
  t: (key: AdminUsersKey) => string,
  matchKind: UserMatchKind | null,
  total: number,
) {
  const matchLabel = matchKind
    ? `${t('matched_by')} ${t(`match_${matchKind}` as Extract<AdminUsersKey, `match_${UserMatchKind}`>)}`
    : null;
  return matchLabel
    ? `${t('total_label')}: ${total} · ${matchLabel}`
    : `${t('total_label')}: ${total}`;
}

export function createUsersMgmtRangeLabel(
  tList: (key: AdminListKey) => string,
  page: number,
  total: number,
) {
  if (total <= 0) return null;
  const rangeFrom = (page - 1) * PAGE_LIMIT + 1;
  const rangeTo = Math.min(page * PAGE_LIMIT, total);
  return interpolate(tList('showing_x_of_y'), { from: rangeFrom, to: rangeTo, total });
}
