'use client';

import React, {
  useCallback,
  useEffect,
  useMemo,
  useRef,
  useState,
} from 'react';
import { useRouter, useSearchParams } from 'next/navigation';
import api from '@/api';
import AdminDateRangeFilter from '@/app/admin/components/AdminDateRangeFilter';
import AdminFilter from '@/app/admin/components/AdminFilter';
import AdminTableShell from '@/app/admin/components/AdminTableShell';
import { formatAdminUtcDateTime } from '@/app/admin/lib/dateTime';
import {
  ADMIN_TABLE_HEADER_CELL_CLASS,
  ADMIN_TABLE_HEADER_LAST_CELL_CLASS,
  ADMIN_TABLE_RESIZE_HANDLE_CLASS,
  getAdminStickyRightCellClass,
  getAdminStickyRightHeaderClass,
} from '@/app/admin/components/adminTableStyles';
import { useAdminResizableColumns } from '@/app/admin/hooks/useAdminResizableColumns';
import { useTranslation } from 'react-i18next';
import { useUserStore } from '@/store';
import { ErrorWithCode } from '@/lib/request';
import ErrorDisplay from '@/components/ErrorDisplay';
import Loading from '@/components/loading';
import { Button } from '@/components/ui/Button';
import {
  Popover,
  PopoverContent,
  PopoverTrigger,
} from '@/components/ui/Popover';
import { ScrollArea } from '@/components/ui/ScrollArea';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/Select';
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/Table';
import OrderDetailSheet from '@/components/order/OrderDetailSheet';
import ImportActivationDialog from '@/components/order/ImportActivationDialog';
import { cn } from '@/lib/utils';
import { resolveContactMode } from '@/lib/resolve-contact-mode';
import { ArchiveRestore, Check, ChevronDown } from 'lucide-react';
import type { OrderSummary } from '@/components/order/order-types';
import type { Shifu } from '@/types/shifu';
import { useEnvStore } from '@/c-store';
import type { EnvStoreState } from '@/c-types/store';
import AdminTooltipText from '@/app/admin/components/AdminTooltipText';
import AdminBreadcrumb from '@/app/admin/components/AdminBreadcrumb';
import AdminTitle from '@/app/admin/components/AdminTitle';
import { ClearableTextInput } from '@/app/admin/operations/orders/orderUiShared';

type OrderListResponse = {
  items: OrderSummary[];
  page: number;
  page_count: number;
  page_size: number;
  total: number;
};

type OrderFilters = {
  order_bid: string;
  user_bid: string;
  shifu_bids: string[];
  status: string;
  payment_channel: string;
  start_time: string;
  end_time: string;
};

const PAGE_SIZE = 20;
const DEFAULT_ORDER_STATUS = '502';
const QUERY_STATUS_KEY = 'status';
const QUERY_SHIFU_BID_KEY = 'shifu_bid';
const COLUMN_MIN_WIDTH = 80;
const COLUMN_MAX_WIDTH = 360;
const COLUMN_WIDTH_STORAGE_KEY = 'adminOrdersColumnWidths';

const DEFAULT_COLUMN_WIDTHS = {
  shifu: 120,
  user: 160,
  status: 110,
  paidAmount: 110,
  discountInfo: 120,
  payment: 90,
  createdAt: 170,
  orderId: 220,
  action: 100,
};

type ColumnKey = keyof typeof DEFAULT_COLUMN_WIDTHS;
type ColumnWidthState = Record<ColumnKey, number>;
const COLUMN_KEYS = Object.keys(DEFAULT_COLUMN_WIDTHS) as ColumnKey[];
type SearchParamsLike = Pick<
  URLSearchParams,
  'get' | 'has' | 'toString'
> | null;

const SINGLE_SELECT_ITEM_CLASS =
  'pl-3 data-[state=checked]:bg-muted data-[state=checked]:text-foreground [&>span:first-child]:hidden';

const createDefaultFilters = (): OrderFilters => ({
  order_bid: '',
  user_bid: '',
  shifu_bids: [],
  status: DEFAULT_ORDER_STATUS,
  payment_channel: '',
  start_time: '',
  end_time: '',
});

const parseShifuBidQuery = (value: string | null): string[] =>
  Array.from(
    new Set(
      (value || '')
        .split(',')
        .map(item => item.trim())
        .filter(Boolean),
    ),
  );

const serializeShifuBidQuery = (value: string[]): string =>
  parseShifuBidQuery(value.join(',')).join(',');

const createFiltersFromSearchParams = (
  searchParams: SearchParamsLike,
): OrderFilters => ({
  ...createDefaultFilters(),
  shifu_bids: parseShifuBidQuery(
    searchParams?.get(QUERY_SHIFU_BID_KEY) || null,
  ),
  status: searchParams?.has(QUERY_STATUS_KEY)
    ? searchParams.get(QUERY_STATUS_KEY) || ''
    : DEFAULT_ORDER_STATUS,
});

const OrdersPage = () => {
  const { t, i18n } = useTranslation();
  const router = useRouter();
  const searchParams = useSearchParams();
  const searchParamsString = searchParams?.toString() || '';
  const hasStatusQuery = useMemo(
    () => new URLSearchParams(searchParamsString).has(QUERY_STATUS_KEY),
    [searchParamsString],
  );
  const isInitialized = useUserStore(state => state.isInitialized);
  const isGuest = useUserStore(state => state.isGuest);
  const loginMethodsEnabled = useEnvStore(
    (state: EnvStoreState) => state.loginMethodsEnabled,
  );
  const defaultLoginMethod = useEnvStore(
    (state: EnvStoreState) => state.defaultLoginMethod,
  );
  const currencySymbol = useEnvStore(
    (state: EnvStoreState) => state.currencySymbol,
  );
  const payOrderExpireSeconds = useEnvStore(
    (state: EnvStoreState) => state.payOrderExpireSeconds,
  );
  const initialFilters = useMemo(
    () =>
      createFiltersFromSearchParams(new URLSearchParams(searchParamsString)),
    [searchParamsString],
  );
  const [orders, setOrders] = useState<OrderSummary[]>([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<{ message: string; code?: number } | null>(
    null,
  );
  const [pageIndex, setPageIndex] = useState(1);
  const [pageCount, setPageCount] = useState(1);
  const [total, setTotal] = useState(0);
  const [selectedOrder, setSelectedOrder] = useState<OrderSummary | null>(null);
  const [detailOpen, setDetailOpen] = useState(false);
  const [importOpen, setImportOpen] = useState(false);
  const [courses, setCourses] = useState<Shifu[]>([]);
  const [coursesLoading, setCoursesLoading] = useState(false);
  const [coursesError, setCoursesError] = useState<string | null>(null);
  const [courseSearch, setCourseSearch] = useState('');
  const [filters, setFilters] = useState<OrderFilters>(() => initialFilters);
  const filtersRef = useRef<OrderFilters>(initialFilters);
  const [expanded, setExpanded] = useState(false);

  const {
    setColumnWidths,
    getColumnStyle,
    getResizeHandleProps,
    isManualColumn,
    clampWidth,
  } = useAdminResizableColumns<ColumnKey>({
    storageKey: COLUMN_WIDTH_STORAGE_KEY,
    defaultWidths: DEFAULT_COLUMN_WIDTHS,
    minWidth: COLUMN_MIN_WIDTH,
    maxWidth: COLUMN_MAX_WIDTH,
  });

  const ALL_OPTION_VALUE = '__all__';

  const payOrderExpireMinutes = useMemo(() => {
    if (!Number.isFinite(payOrderExpireSeconds) || payOrderExpireSeconds <= 0) {
      return 0;
    }
    return Math.ceil(payOrderExpireSeconds / 60);
  }, [payOrderExpireSeconds]);

  const formatMoney = useCallback(
    (value?: string) => {
      const normalized = value && value.trim().length > 0 ? value : '0';
      const symbol = currencySymbol || '';
      return `${symbol}${normalized}`;
    },
    [currencySymbol],
  );

  const statusOptions = useMemo(
    () => [
      { value: '', label: t('module.order.filters.all') },
      { value: '501', label: t('server.order.orderStatusInit') },
      { value: '504', label: t('server.order.orderStatusToBePaid') },
      { value: '502', label: t('server.order.orderStatusSuccess') },
      { value: '503', label: t('server.order.orderStatusRefund') },
      {
        value: '505',
        label:
          payOrderExpireMinutes > 0
            ? t('module.order.statusLabels.timeout', {
                minutes: payOrderExpireMinutes,
              })
            : t('server.order.orderStatusTimeout'),
      },
    ],
    [payOrderExpireMinutes, t],
  );

  const channelOptions = useMemo(
    () => [
      { value: '', label: t('module.order.filters.all') },
      { value: 'pingxx', label: t('module.order.paymentChannel.pingxx') },
      { value: 'stripe', label: t('module.order.paymentChannel.stripe') },
      { value: 'alipay', label: t('module.order.paymentChannel.alipay') },
      { value: 'wechatpay', label: t('module.order.paymentChannel.wechatpay') },
      { value: 'manual', label: t('module.order.paymentChannel.manual') },
      { value: 'open_api', label: t('module.order.paymentChannel.open_api') },
    ],
    [t],
  );

  const defaultUserName = useMemo(() => t('module.user.defaultUserName'), [t]);
  const locale = i18n?.language || 'en-US';
  const filterControlClassName = cn(
    'min-w-0 flex-1',
    !locale.startsWith('zh') && 'xl:max-w-[220px]',
  );
  const filterLabelClassName = locale.startsWith('zh')
    ? 'w-16 text-right'
    : 'w-24 text-right';

  const contactType = useMemo(
    () => resolveContactMode(loginMethodsEnabled, defaultLoginMethod),
    [defaultLoginMethod, loginMethodsEnabled],
  );
  const isEmailMode = contactType === 'email';

  const userBidPlaceholder = useMemo(() => {
    if (isEmailMode) {
      return t('module.order.filters.userBidEmail');
    }
    const methods = loginMethodsEnabled || [];
    const hasPhone = methods.includes('phone');
    const hasEmail = methods.includes('email');
    if (hasPhone && !hasEmail) {
      return t('module.order.filters.userBidPhone');
    }
    if (hasEmail && !hasPhone) {
      return t('module.order.filters.userBidEmail');
    }
    return t('module.order.filters.userBid');
  }, [isEmailMode, loginMethodsEnabled, t]);

  const displayStatusValue = filters.status || ALL_OPTION_VALUE;
  const displayChannelValue = filters.payment_channel || ALL_OPTION_VALUE;

  const courseNameMap = useMemo(() => {
    const map = new Map<string, string>();
    courses.forEach(course => {
      if (!course.bid) {
        return;
      }
      map.set(course.bid, course.name || course.bid);
    });
    return map;
  }, [courses]);

  const selectedCourseNames = useMemo(
    () => filters.shifu_bids.map(bid => courseNameMap.get(bid) || bid),
    [courseNameMap, filters.shifu_bids],
  );

  const selectedCourseLabel = useMemo(() => {
    if (selectedCourseNames.length === 0) {
      return t('module.order.filters.shifuBid');
    }
    if (selectedCourseNames.length <= 2) {
      return selectedCourseNames.join(', ');
    }
    const shortList = selectedCourseNames.slice(0, 2).join(', ');
    return `${shortList} +${selectedCourseNames.length - 2}`;
  }, [selectedCourseNames, t]);

  const filteredCourses = useMemo(() => {
    const keyword = courseSearch.trim().toLowerCase();
    if (!keyword) {
      return courses;
    }
    return courses.filter(course => {
      const name = (course.name || '').toLowerCase();
      const bid = (course.bid || '').toLowerCase();
      const matchesName = name.includes(keyword);
      const matchesBid = Boolean(bid && bid === keyword);
      return matchesName || matchesBid;
    });
  }, [courseSearch, courses]);

  useEffect(() => {
    filtersRef.current = filters;
  }, [filters]);

  useEffect(() => {
    setFilters(prev => {
      const hasSameCourseFilters =
        prev.shifu_bids.length === initialFilters.shifu_bids.length &&
        prev.shifu_bids.every(
          (bid, index) => bid === initialFilters.shifu_bids[index],
        );
      if (
        prev.order_bid === initialFilters.order_bid &&
        prev.user_bid === initialFilters.user_bid &&
        prev.status === initialFilters.status &&
        prev.payment_channel === initialFilters.payment_channel &&
        prev.start_time === initialFilters.start_time &&
        prev.end_time === initialFilters.end_time &&
        hasSameCourseFilters
      ) {
        return prev;
      }
      return initialFilters;
    });
  }, [initialFilters]);

  const syncJumpFiltersQuery = useCallback(
    (nextFilters: Pick<OrderFilters, 'shifu_bids' | 'status'>) => {
      const nextSearchParams = new URLSearchParams(searchParamsString);
      const serializedShifuBid = serializeShifuBidQuery(nextFilters.shifu_bids);
      const normalizedStatus = nextFilters.status.trim();

      if (serializedShifuBid) {
        nextSearchParams.set(QUERY_SHIFU_BID_KEY, serializedShifuBid);
      } else {
        nextSearchParams.delete(QUERY_SHIFU_BID_KEY);
      }

      nextSearchParams.set(QUERY_STATUS_KEY, normalizedStatus);

      const query = nextSearchParams.toString();
      router.replace(query ? `/admin/orders?${query}` : '/admin/orders');
    },
    [router, searchParamsString],
  );

  const estimateWidth = (text: string, multiplier = 7) => {
    if (!text) {
      return COLUMN_MIN_WIDTH;
    }
    const approx = text.length * multiplier + 16;
    return approx;
  };

  const resolveStatusLabel = useCallback(
    (order: OrderSummary) => {
      if (order.status === 505 && payOrderExpireMinutes > 0) {
        return t('module.order.statusLabels.timeout', {
          minutes: payOrderExpireMinutes,
        });
      }
      return t(order.status_key);
    },
    [payOrderExpireMinutes, t],
  );

  const autoAdjustColumns = useCallback(
    (items: OrderSummary[]) => {
      if (!items || items.length === 0) {
        setColumnWidths(prev => {
          const next = { ...prev };
          COLUMN_KEYS.forEach(key => {
            if (!isManualColumn(key)) {
              next[key] = DEFAULT_COLUMN_WIDTHS[key];
            }
          });
          return next;
        });
        return;
      }

      const nextWidths: Partial<ColumnWidthState> = {};
      const columnValueExtractors: Record<
        ColumnKey,
        (order: OrderSummary) => string[]
      > = {
        shifu: order => [order.shifu_name || order.shifu_bid],
        user: order => [
          (isEmailMode ? order.user_email : order.user_mobile) ||
            order.user_bid,
          order.user_nickname || defaultUserName,
        ],
        status: order => [resolveStatusLabel(order)],
        paidAmount: order => [formatMoney(order.paid_price)],
        discountInfo: order => [
          order.discount_amount && order.discount_amount !== '0'
            ? formatMoney(order.discount_amount)
            : '-',
        ],
        payment: order => [t(order.payment_channel_key)],
        createdAt: order => [order.created_at],
        orderId: order => [order.order_bid],
        action: () => [t('module.order.table.view')],
      };

      items.forEach(order => {
        COLUMN_KEYS.forEach(key => {
          const texts = columnValueExtractors[key](order).filter(Boolean);
          if (texts.length === 0) {
            return;
          }
          const multiplierMap: Partial<Record<ColumnKey, number>> = {
            shifu: 4.4,
            user: 4.6,
            status: 4.4,
            paidAmount: 4.4,
            discountInfo: 4.8,
            payment: 4.4,
            createdAt: 4.8,
            orderId: 5,
            action: 4.4,
          };
          const multiplier = multiplierMap[key] ?? 7;
          const required = texts.reduce(
            (maxWidth, text) =>
              Math.max(maxWidth, estimateWidth(text, multiplier)),
            DEFAULT_COLUMN_WIDTHS[key],
          );
          if (
            !nextWidths[key] ||
            required > (nextWidths[key] ?? COLUMN_MIN_WIDTH)
          ) {
            nextWidths[key] = required;
          }
        });
      });

      setColumnWidths(prev => {
        const updated = { ...prev };
        COLUMN_KEYS.forEach(key => {
          if (isManualColumn(key)) {
            return;
          }
          const fallback = DEFAULT_COLUMN_WIDTHS[key];
          const calculated = nextWidths[key] ?? fallback;
          updated[key] = clampWidth(calculated);
        });
        return updated;
      });
    },
    [
      clampWidth,
      defaultUserName,
      formatMoney,
      isEmailMode,
      isManualColumn,
      resolveStatusLabel,
      setColumnWidths,
      t,
    ],
  );

  const renderResizeHandle = (key: ColumnKey) => (
    <span
      className={ADMIN_TABLE_RESIZE_HANDLE_CLASS}
      {...getResizeHandleProps(key)}
    />
  );

  const renderTooltipText = (text?: string, className?: string) => {
    return (
      <AdminTooltipText
        text={text}
        emptyValue='-'
        forceTooltip
        className={cn('block w-full min-w-0 truncate', className)}
      />
    );
  };

  const renderPlainTableText = (text?: string, className?: string) => {
    const value = text?.trim() || '-';
    return (
      <span className={cn('block w-full min-w-0 truncate', className)}>
        {value}
      </span>
    );
  };

  useEffect(() => {
    if (!isInitialized || isGuest) {
      setCourses([]);
      setCoursesLoading(false);
      setCoursesError(null);
      return;
    }

    let canceled = false;
    const loadCourses = async () => {
      setCoursesLoading(true);
      setCoursesError(null);
      try {
        const pageSize = 100;
        let pageIndex = 1;
        const collected: Shifu[] = [];
        const seen = new Set<string>();

        while (true) {
          const { items } = await api.getAdminOrderShifus({
            page_index: pageIndex,
            page_size: pageSize,
          });
          const pageItems = (items || []) as Shifu[];
          pageItems.forEach(item => {
            if (item?.bid && !seen.has(item.bid)) {
              seen.add(item.bid);
              collected.push(item);
            }
          });
          if (pageItems.length < pageSize) {
            break;
          }
          pageIndex += 1;
        }

        if (!canceled) {
          setCourses(collected);
        }
      } catch {
        if (!canceled) {
          setCourses([]);
          setCoursesError(t('common.core.networkError'));
        }
      } finally {
        if (!canceled) {
          setCoursesLoading(false);
        }
      }
    };

    loadCourses();

    return () => {
      canceled = true;
    };
  }, [isInitialized, isGuest, t]);

  const fetchOrders = useCallback(
    async (targetPage: number, nextFilters?: OrderFilters) => {
      const resolvedFilters = nextFilters ?? filtersRef.current;
      const shifuBidValue = resolvedFilters.shifu_bids
        .map(bid => bid.trim())
        .filter(Boolean)
        .join(',');
      setLoading(true);
      setError(null);
      try {
        const response = (await api.getAdminOrders({
          page_index: targetPage,
          page_size: PAGE_SIZE,
          order_bid: resolvedFilters.order_bid.trim(),
          user_bid: resolvedFilters.user_bid.trim(),
          shifu_bid: shifuBidValue,
          status: resolvedFilters.status,
          payment_channel: resolvedFilters.payment_channel,
          start_time: resolvedFilters.start_time,
          end_time: resolvedFilters.end_time,
        })) as OrderListResponse;

        const list = response.items || [];
        setOrders(list);
        autoAdjustColumns(list);
        setPageIndex(response.page || targetPage);
        setPageCount(response.page_count || 1);
        setTotal(response.total || 0);
      } catch (err) {
        if (err instanceof ErrorWithCode) {
          setError({ message: err.message, code: err.code });
        } else if (err instanceof Error) {
          setError({ message: err.message });
        } else {
          setError({ message: t('common.core.unknownError') });
        }
      } finally {
        setLoading(false);
      }
    },
    [autoAdjustColumns, t],
  );

  useEffect(() => {
    if (isInitialized && !isGuest) {
      fetchOrders(1);
    }
  }, [fetchOrders, i18n.language, isGuest, isInitialized]);

  useEffect(() => {
    if (!isInitialized) return;
    if (isGuest) {
      const currentPath = encodeURIComponent(
        window.location.pathname + window.location.search,
      );
      window.location.href = `/login?redirect=${currentPath}`;
    }
  }, [isInitialized, isGuest]);

  useEffect(() => {
    if (!isInitialized || isGuest || hasStatusQuery) {
      return;
    }
    syncJumpFiltersQuery(initialFilters);
  }, [
    hasStatusQuery,
    initialFilters,
    isGuest,
    isInitialized,
    syncJumpFiltersQuery,
  ]);
  const handleFilterChange = (
    key: Exclude<keyof OrderFilters, 'shifu_bids'>,
    value: string,
  ) => {
    setFilters(prev => ({ ...prev, [key]: value }));
  };

  const handleCourseToggle = (courseBid: string) => {
    setFilters(prev => {
      const exists = prev.shifu_bids.includes(courseBid);
      const nextBids = exists
        ? prev.shifu_bids.filter(bid => bid !== courseBid)
        : [...prev.shifu_bids, courseBid];
      return { ...prev, shifu_bids: nextBids };
    });
  };

  const handleSearch = () => {
    syncJumpFiltersQuery(filters);
    fetchOrders(1, filters);
  };

  const handleReset = () => {
    const cleared = createDefaultFilters();
    setFilters(cleared);
    setCourseSearch('');
    syncJumpFiltersQuery(cleared);
    fetchOrders(1, cleared);
  };

  const handlePageChange = (nextPage: number) => {
    if (nextPage < 1 || nextPage > pageCount || nextPage === pageIndex) {
      return;
    }
    fetchOrders(nextPage);
  };

  const handleViewDetail = (order: OrderSummary) => {
    setSelectedOrder(order);
    setDetailOpen(true);
  };

  const filterItems = [
    {
      key: 'user_bid',
      label: userBidPlaceholder,
      component: (
        <ClearableTextInput
          value={filters.user_bid}
          onChange={value => handleFilterChange('user_bid', value)}
          placeholder={userBidPlaceholder}
          clearLabel={t('common.core.close')}
        />
      ),
    },
    {
      key: 'shifu_bids',
      label: t('module.order.filters.shifuBid'),
      component: (
        <Popover>
          <PopoverTrigger asChild>
            <Button
              size='sm'
              variant='outline'
              type='button'
              className='h-9 w-full justify-between font-normal'
              title={selectedCourseNames.join(', ')}
            >
              <span
                className={cn(
                  'flex-1 truncate text-left',
                  filters.shifu_bids.length === 0
                    ? 'text-muted-foreground'
                    : 'text-foreground',
                )}
              >
                {selectedCourseLabel}
              </span>
              <ChevronDown className='h-4 w-4 text-muted-foreground' />
            </Button>
          </PopoverTrigger>
          <PopoverContent
            align='start'
            className='p-3'
            style={{
              width: 'var(--radix-popover-trigger-width)',
              maxWidth: 'var(--radix-popover-trigger-width)',
            }}
          >
            <ClearableTextInput
              value={courseSearch}
              onChange={setCourseSearch}
              placeholder={t('module.order.filters.searchCourseOrId')}
              clearLabel={t('common.core.close')}
            />
            <ScrollArea className='mt-3 h-48'>
              {coursesLoading ? (
                <div className='flex items-center justify-center py-4'>
                  <Loading className='h-5 w-5' />
                </div>
              ) : coursesError ? (
                <div className='px-2 py-3 text-xs text-destructive'>
                  {coursesError}
                </div>
              ) : filteredCourses.length === 0 ? (
                <div className='px-2 py-3 text-xs text-muted-foreground'>
                  {t('common.core.noShifus')}
                </div>
              ) : (
                <div className='space-y-1'>
                  {filteredCourses.map(course => {
                    const isSelected = filters.shifu_bids.includes(course.bid);
                    const courseName = course.name || course.bid;
                    return (
                      <button
                        key={course.bid}
                        type='button'
                        onClick={() => handleCourseToggle(course.bid)}
                        className='flex w-full items-start gap-2 rounded-md px-2 py-1.5 text-left text-sm hover:bg-accent'
                        aria-pressed={isSelected}
                      >
                        <span
                          className={cn(
                            'mt-0.5 flex h-4 w-4 items-center justify-center rounded border',
                            isSelected
                              ? 'border-primary bg-primary text-primary-foreground'
                              : 'border-muted-foreground/40 text-transparent',
                          )}
                        >
                          <Check className='h-3 w-3' />
                        </span>
                        <span className='flex flex-col min-w-0'>
                          <span className='text-sm text-foreground truncate'>
                            {courseName}
                          </span>
                        </span>
                      </button>
                    );
                  })}
                </div>
              )}
            </ScrollArea>
          </PopoverContent>
        </Popover>
      ),
    },
    {
      key: 'status',
      label: t('module.order.filters.status'),
      component: (
        <Select
          value={displayStatusValue}
          onValueChange={value =>
            handleFilterChange(
              'status',
              value === ALL_OPTION_VALUE ? '' : value,
            )
          }
        >
          <SelectTrigger className='h-9'>
            <SelectValue placeholder={t('module.order.filters.status')} />
          </SelectTrigger>
          <SelectContent>
            {statusOptions.map(option => (
              <SelectItem
                key={option.value || 'all'}
                value={option.value || ALL_OPTION_VALUE}
                className={SINGLE_SELECT_ITEM_CLASS}
              >
                {option.label}
              </SelectItem>
            ))}
          </SelectContent>
        </Select>
      ),
    },
    {
      key: 'payment_channel',
      label: t('module.order.filters.channel'),
      component: (
        <Select
          value={displayChannelValue}
          onValueChange={value =>
            handleFilterChange(
              'payment_channel',
              value === ALL_OPTION_VALUE ? '' : value,
            )
          }
        >
          <SelectTrigger className='h-9'>
            <SelectValue placeholder={t('module.order.filters.channel')} />
          </SelectTrigger>
          <SelectContent>
            {channelOptions.map(option => (
              <SelectItem
                key={option.value || 'all'}
                value={option.value || ALL_OPTION_VALUE}
                className={SINGLE_SELECT_ITEM_CLASS}
              >
                {option.label}
              </SelectItem>
            ))}
          </SelectContent>
        </Select>
      ),
    },
    {
      key: 'date_range',
      label: t('module.order.table.createdAt'),
      component: (
        <AdminDateRangeFilter
          startValue={filters.start_time}
          endValue={filters.end_time}
          onChange={range => {
            handleFilterChange('start_time', range.start);
            handleFilterChange('end_time', range.end);
          }}
          placeholder={`${t('module.order.filters.startTime')} ~ ${t(
            'module.order.filters.endTime',
          )}`}
          resetLabel={t('module.order.filters.reset')}
          clearLabel={t('common.core.close')}
        />
      ),
    },
    {
      key: 'order_bid',
      label: t('module.order.filters.orderBid'),
      component: (
        <ClearableTextInput
          value={filters.order_bid}
          onChange={value => handleFilterChange('order_bid', value)}
          placeholder={t('module.order.filters.orderBid')}
          clearLabel={t('common.core.close')}
        />
      ),
    },
  ];
  if (error) {
    return (
      <div className='h-full p-0'>
        <ErrorDisplay
          errorCode={error.code || 0}
          errorMessage={error.message}
          onRetry={() => fetchOrders(pageIndex)}
        />
      </div>
    );
  }

  return (
    <div className='h-full p-0'>
      <div className='mx-auto flex h-full max-w-7xl flex-col overflow-hidden'>
        <AdminBreadcrumb items={[{ label: t('module.order.title') }]} />
        <AdminTitle
          title={t('module.order.title')}
          actions={
            <div className='flex items-center gap-3 lg:justify-end'>
              <Button
                variant='ghost'
                className='h-9 gap-1.5 px-0 text-[length:var(--text-sm-font-size,14px)] font-[var(--font-weight-medium,500)] leading-[var(--text-sm-line-height,20px)] text-[var(--base-foreground,#0A0A0A)] hover:bg-transparent hover:text-[var(--base-foreground,#0A0A0A)]'
                onClick={() => setImportOpen(true)}
              >
                <ArchiveRestore className='h-4 w-4' />
                {t('module.order.importActivation.action')}
              </Button>
            </div>
          }
        />

        <div className='min-h-0 flex-1 overflow-hidden pr-1'>
          <div className='flex h-full min-h-0 flex-col gap-5 pb-6'>
            <AdminFilter
              items={filterItems}
              expanded={expanded}
              onExpandedChange={setExpanded}
              onReset={handleReset}
              onSearch={handleSearch}
              resetLabel={t('module.order.filters.reset')}
              searchLabel={t('module.order.filters.search')}
              expandLabel={t('common.core.expand')}
              collapseLabel={t('common.core.collapse')}
              collapsedCount={3}
              contentClassName={filterControlClassName}
              expandedLabelClassName={filterLabelClassName}
            />

            <AdminTableShell
              loading={loading}
              isEmpty={orders.length === 0}
              emptyContent={t('module.order.emptyList')}
              emptyColSpan={9}
              withTooltipProvider
              tableWrapperClassName='max-h-[calc(100vh-20rem)] overflow-auto'
              footnote={t('module.order.totalCount', { count: total })}
              pagination={{
                pageIndex,
                pageCount,
                onPageChange: handlePageChange,
                prevLabel: t('module.order.paginationPrev'),
                nextLabel: t('module.order.paginationNext'),
                prevAriaLabel: t('module.order.paginationPrevAriaLabel'),
                nextAriaLabel: t('module.order.paginationNextAriaLabel'),
              }}
              table={emptyRow => (
                <Table className='table-auto'>
                  <TableHeader>
                    <TableRow>
                      <TableHead
                        className={cn(
                          ADMIN_TABLE_HEADER_CELL_CLASS,
                          'h-10 whitespace-nowrap text-center text-xs',
                        )}
                        style={getColumnStyle('shifu')}
                      >
                        {t('module.order.table.shifu')}
                        {renderResizeHandle('shifu')}
                      </TableHead>
                      <TableHead
                        className={cn(
                          ADMIN_TABLE_HEADER_CELL_CLASS,
                          'h-10 whitespace-nowrap text-center text-xs',
                        )}
                        style={getColumnStyle('user')}
                      >
                        {t('module.order.table.user')}
                        {renderResizeHandle('user')}
                      </TableHead>
                      <TableHead
                        className={cn(
                          ADMIN_TABLE_HEADER_CELL_CLASS,
                          'h-10 whitespace-nowrap text-center text-xs',
                        )}
                        style={getColumnStyle('status')}
                      >
                        {t('module.order.table.status')}
                        {renderResizeHandle('status')}
                      </TableHead>
                      <TableHead
                        className={cn(
                          ADMIN_TABLE_HEADER_CELL_CLASS,
                          'h-10 whitespace-nowrap text-center text-xs',
                        )}
                        style={getColumnStyle('paidAmount')}
                      >
                        {t('module.order.fields.paid')}
                        {renderResizeHandle('paidAmount')}
                      </TableHead>
                      <TableHead
                        className={cn(
                          ADMIN_TABLE_HEADER_CELL_CLASS,
                          'h-10 whitespace-nowrap text-center text-xs',
                        )}
                        style={getColumnStyle('discountInfo')}
                      >
                        {t('module.order.fields.discount')}
                        {renderResizeHandle('discountInfo')}
                      </TableHead>
                      <TableHead
                        className={cn(
                          ADMIN_TABLE_HEADER_CELL_CLASS,
                          'h-10 whitespace-nowrap text-center text-xs',
                        )}
                        style={getColumnStyle('payment')}
                      >
                        {t('module.order.table.payment')}
                        {renderResizeHandle('payment')}
                      </TableHead>
                      <TableHead
                        className={cn(
                          ADMIN_TABLE_HEADER_CELL_CLASS,
                          'h-10 whitespace-nowrap text-center text-xs',
                        )}
                        style={getColumnStyle('createdAt')}
                      >
                        {t('module.order.table.createdAt')}
                        {renderResizeHandle('createdAt')}
                      </TableHead>
                      <TableHead
                        className={cn(
                          ADMIN_TABLE_HEADER_LAST_CELL_CLASS,
                          'h-10 whitespace-nowrap text-center text-xs',
                        )}
                        style={getColumnStyle('orderId')}
                      >
                        {t('module.order.table.orderId')}
                        {renderResizeHandle('orderId')}
                      </TableHead>
                      <TableHead
                        className={getAdminStickyRightHeaderClass(
                          'h-10 whitespace-nowrap text-center text-xs',
                        )}
                        style={getColumnStyle('action')}
                      >
                        {t('module.order.table.action')}
                        {renderResizeHandle('action')}
                      </TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {emptyRow}
                    {orders.map(order => {
                      const userContact =
                        (isEmailMode ? order.user_email : order.user_mobile) ||
                        order.user_bid ||
                        '-';
                      const userName = order.user_nickname || defaultUserName;

                      return (
                        <TableRow key={order.order_bid}>
                          <TableCell
                            className='overflow-hidden whitespace-nowrap border-r border-border px-3 py-2 text-center text-ellipsis'
                            style={getColumnStyle('shifu')}
                          >
                            {renderTooltipText(
                              order.shifu_name || order.shifu_bid,
                              'text-foreground',
                            )}
                          </TableCell>
                          <TableCell
                            className='border-r border-border px-3 py-2 align-middle'
                            style={getColumnStyle('user')}
                          >
                            <div className='space-y-1'>
                              {renderTooltipText(
                                userContact,
                                'text-sm font-medium text-foreground',
                              )}
                              {renderTooltipText(
                                userName,
                                'block text-xs text-muted-foreground',
                              )}
                            </div>
                          </TableCell>
                          <TableCell
                            className='overflow-hidden whitespace-nowrap border-r border-border px-3 py-2 text-center text-ellipsis'
                            style={getColumnStyle('status')}
                          >
                            {renderPlainTableText(resolveStatusLabel(order))}
                          </TableCell>
                          <TableCell
                            className='border-r border-border px-3 py-2 align-middle'
                            style={getColumnStyle('paidAmount')}
                          >
                            <div className='text-center'>
                              {renderPlainTableText(
                                formatMoney(order.paid_price),
                                'text-foreground',
                              )}
                            </div>
                          </TableCell>
                          <TableCell
                            className='border-r border-border px-3 py-2 align-middle'
                            style={getColumnStyle('discountInfo')}
                          >
                            <div className='text-center'>
                              {renderPlainTableText(
                                order.discount_amount &&
                                  order.discount_amount !== '0'
                                  ? formatMoney(order.discount_amount)
                                  : '-',
                                'text-foreground',
                              )}
                            </div>
                          </TableCell>
                          <TableCell
                            className='overflow-hidden whitespace-nowrap border-r border-border px-3 py-2 text-center text-ellipsis'
                            style={getColumnStyle('payment')}
                          >
                            <div className='text-sm text-foreground'>
                              {renderPlainTableText(
                                t(order.payment_channel_key),
                                'text-sm',
                              )}
                            </div>
                          </TableCell>
                          <TableCell
                            className='overflow-hidden whitespace-nowrap px-3 py-2 text-center text-ellipsis'
                            style={getColumnStyle('createdAt')}
                          >
                            {renderPlainTableText(
                              formatAdminUtcDateTime(order.created_at),
                            )}
                          </TableCell>
                          <TableCell
                            className='overflow-hidden whitespace-nowrap px-3 py-2 text-center text-ellipsis'
                            style={getColumnStyle('orderId')}
                          >
                            {renderTooltipText(order.order_bid)}
                          </TableCell>
                          <TableCell
                            className={getAdminStickyRightCellClass(
                              'whitespace-nowrap px-3 py-2 text-center',
                            )}
                            style={getColumnStyle('action')}
                          >
                            <Button
                              size='sm'
                              variant='ghost'
                              className='h-auto justify-start rounded-none p-0 text-primary hover:bg-transparent hover:text-primary'
                              onClick={() => handleViewDetail(order)}
                            >
                              {t('module.order.table.view')}
                            </Button>
                          </TableCell>
                        </TableRow>
                      );
                    })}
                  </TableBody>
                </Table>
              )}
            />
          </div>
        </div>
        <OrderDetailSheet
          open={detailOpen}
          orderBid={selectedOrder?.order_bid}
          onOpenChange={open => {
            setDetailOpen(open);
            if (!open) {
              setSelectedOrder(null);
            }
          }}
        />

        <ImportActivationDialog
          open={importOpen}
          onOpenChange={setImportOpen}
          onSuccess={() => fetchOrders(1)}
        />
      </div>
    </div>
  );
};

export default OrdersPage;
