'use client';

/**
 * 재고현황 목록 - UniversalListPage 마이그레이션
 *
 * 기존 IntegratedListTemplateV2 → UniversalListPage config 기반으로 변환
 * - 서버 사이드 페이지네이션 (getStocks API)
 * - 통계 카드 (getStockStats API)
 * - 품목유형별 탭 필터 (getStockStatsByType API)
 * - 테이블 푸터 (요약 정보)
 */

import { useState, useEffect, useCallback, useMemo } from 'react';
import { useRouter } from 'next/navigation';
import {
  Package,
  CheckCircle2,
  AlertCircle,
  Eye,
  AlertTriangle,
} from 'lucide-react';
import type { ExcelColumn } from '@/lib/utils/excel-download';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { TableCell, TableRow } from '@/components/ui/table';
import { Checkbox } from '@/components/ui/checkbox';
import {
  UniversalListPage,
  type UniversalListConfig,
  type SelectionHandlers,
  type RowClickHandlers,
  type FilterFieldConfig,
} from '@/components/templates/UniversalListPage';
import { ListMobileCard, InfoField } from '@/components/organisms/MobileCard';
import { getStocks, getStockStats, getStockTransactions, type StockUsageData } from './actions';
import { USE_STATUS_LABELS, ITEM_TYPE_LABELS } from './types';
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog';
import { Loader2, History, ExternalLink } from 'lucide-react';
import { isNextRedirectError } from '@/lib/utils/redirect-error';
import { getLocalDateString } from '@/lib/utils/date';
import type { StockItem, StockStats, ItemType, StockStatusType } from './types';

// 페이지당 항목 수
const ITEMS_PER_PAGE = 20;

export function StockStatusList() {
  const router = useRouter();

  // ===== 통계 (외부 관리) =====
  const [stockStats, setStockStats] = useState<StockStats | null>(null);

  // ===== 날짜 범위 상태 =====
  const today = new Date();
  const firstDayOfMonth = new Date(today.getFullYear(), today.getMonth(), 1);
  const [startDate, setStartDate] = useState<string>(getLocalDateString(firstDayOfMonth));
  const [endDate, setEndDate] = useState<string>(getLocalDateString(today));

  // ===== 데이터 상태 (수주관리 패턴) =====
  const [stocks, setStocks] = useState<StockItem[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [, setTotalCount] = useState(0);

  // ===== 검색 및 필터 상태 =====
  const [searchTerm, setSearchTerm] = useState('');
  const [filterValues, setFilterValues] = useState<Record<string, string | string[]>>({
    itemCategory: 'all',
    itemTypeTab: 'all',
    wipStatus: 'all',
    useStatus: 'all',
  });

  // ===== 통계 카드 필터 상태 =====
  const [stockStatusFilter, setStockStatusFilter] = useState<'all' | 'low' | 'out'>('all');

  // 데이터 로드 함수
  const loadData = useCallback(async () => {
    try {
      setIsLoading(true);
      const itemCategory = filterValues.itemCategory as string;
      const [stocksResult, statsResult] = await Promise.all([
        getStocks({
          page: 1,
          perPage: 9999, // 전체 데이터 로드 (클라이언트 사이드 필터링)
          itemCategory: itemCategory !== 'all' ? itemCategory : undefined,
          startDate,
          endDate,
        }),
        getStockStats(),
      ]);

      if (stocksResult.success && stocksResult.data) {
        setStocks(stocksResult.data);
        setTotalCount(stocksResult.pagination.total);
      }

      if (statsResult.success && statsResult.data) {
        setStockStats(statsResult.data);
      }
    } catch (error) {
      if (isNextRedirectError(error)) throw error;
      console.error('[StockStatusList] loadData error:', error);
    } finally {
      setIsLoading(false);
    }
  }, [startDate, endDate, filterValues.itemCategory]);

  // 초기 데이터 로드 및 날짜 변경 시 재로드
  useEffect(() => {
    loadData();
  }, [loadData]);

  // 클라이언트 사이드 필터링
  const filteredStocks = stocks.filter((stock) => {
    // 검색 필터
    if (searchTerm) {
      const searchLower = searchTerm.toLowerCase();
      const matchesSearch =
        stock.itemCode.toLowerCase().includes(searchLower) ||
        stock.itemName.toLowerCase().includes(searchLower);
      if (!matchesSearch) return false;
    }

    // 품목유형 탭 필터
    const itemTypeTab = filterValues.itemTypeTab as string;
    if (itemTypeTab === 'wip') {
      // 재공품: PT 유형 + BD- 코드 (1차 가공품)
      if (stock.itemType !== 'PT' && !stock.itemCode.startsWith('BD-')) return false;
    } else if (itemTypeTab === 'RM') {
      if (stock.itemType !== 'RM') return false;
    } else if (itemTypeTab === 'SM') {
      if (stock.itemType !== 'SM') return false;
    } else if (itemTypeTab === 'CS') {
      if (stock.itemType !== 'CS') return false;
    }

    // 상태 필터
    const useStatusFilter = filterValues.useStatus as string;
    if (useStatusFilter && useStatusFilter !== 'all') {
      if (stock.useStatus !== useStatusFilter) return false;
    }

    // 통계 카드 재고상태 필터
    if (stockStatusFilter === 'low') {
      if (stock.status !== 'low') return false;
    } else if (stockStatusFilter === 'out') {
      if (stock.status !== 'out') return false;
    }

    return true;
  }).sort((a, b) => {
    // 최종 입출고 일자 내림차순 (최신 거래가 위)
    const dateA = a.lastTransactionDate === '-' ? '' : a.lastTransactionDate;
    const dateB = b.lastTransactionDate === '-' ? '' : b.lastTransactionDate;
    return dateB.localeCompare(dateA);
  });

  // ===== 행 클릭 → 플로팅 액션 메뉴 =====
  const [actionMenu, setActionMenu] = useState<{ item: StockItem; x: number; y: number } | null>(null);
  const [usageModalItem, setUsageModalItem] = useState<StockItem | null>(null);
  const [usageData, setUsageData] = useState<StockUsageData | null>(null);
  const [usageLoading, setUsageLoading] = useState(false);

  const handleRowClick = (item: StockItem, e?: React.MouseEvent) => {
    e?.stopPropagation();
    if (actionMenu?.item.id === item.id) {
      setActionMenu(null);
      return;
    }
    const x = e?.clientX ?? 200;
    const y = e?.clientY ?? 200;
    setActionMenu({ item, x, y });
  };

  // 외부 클릭 시 닫기
  useEffect(() => {
    if (!actionMenu) return;
    const close = () => setActionMenu(null);
    const timer = setTimeout(() => {
      window.addEventListener('click', close, { once: true });
    }, 0);
    return () => { clearTimeout(timer); window.removeEventListener('click', close); };
  }, [actionMenu]);

  const handleViewUsage = async (item: StockItem) => {
    setActionMenu(null);
    setUsageModalItem(item);
    setUsageLoading(true);
    const result = await getStockTransactions(item.id);
    if (result.success && result.data) setUsageData(result.data);
    setUsageLoading(false);
  };

  // ===== 엑셀 컬럼 정의 =====
  const excelColumns: ExcelColumn<StockItem>[] = [
    { header: '품목코드', key: 'itemCode' },
    { header: '품목유형', key: 'itemType', transform: (value) => ITEM_TYPE_LABELS[value as ItemType] || '-' },
    { header: '품목명', key: 'itemName' },
    { header: '규격', key: 'specification' },
    { header: '단위', key: 'unit' },
    { header: '재고량', key: 'calculatedQty' },
    { header: '안전재고', key: 'safetyStock' },
    { header: '최대재고', key: 'maxStock' },
    { header: '재공품', key: 'wipQty' },
    { header: '상태', key: 'useStatus', transform: (value) => USE_STATUS_LABELS[value as 'active' | 'inactive'] || '-' },
  ];

  // ===== API 응답 매핑 함수 =====
  const mapStockResponse = (result: unknown): StockItem[] => {
    const data = result as { data?: { data?: Record<string, unknown>[] } };
    const rawItems = data.data?.data ?? [];
    return rawItems.map((item: Record<string, unknown>) => {
      const stock = item.stock as Record<string, unknown> | null;
      const hasStock = !!stock;
      return {
        id: String(item.id ?? ''),
        itemCode: (item.code ?? '') as string,
        itemName: (item.name ?? '') as string,
        itemType: (item.item_type ?? 'RM') as ItemType,
        specification: (() => {
          if (item.attributes && typeof item.attributes === 'object') {
            const attrs = item.attributes as Record<string, unknown>;
            if (attrs.spec && String(attrs.spec).trim()) return String(attrs.spec).trim();
            const parts: string[] = [];
            if (attrs.thickness) parts.push(`${attrs.thickness}T`);
            if (attrs.width) parts.push(`${attrs.width}`);
            if (attrs.length) parts.push(`${attrs.length}`);
            if (parts.length > 0) return parts.join('×');
          }
          if (stock?.specification && String(stock.specification).trim()) return String(stock.specification).trim();
          return '';
        })(),
        unit: (item.unit ?? 'EA') as string,
        calculatedQty: hasStock ? (parseFloat(String(stock?.stock_qty)) || 0) : 0,
        actualQty: hasStock ? (parseFloat(String(stock?.stock_qty)) || 0) : 0,
        stockQty: hasStock ? (parseFloat(String(stock?.stock_qty)) || 0) : 0,
        safetyStock: hasStock ? (parseFloat(String(stock?.safety_stock)) || 0) : 0,
        maxStock: hasStock ? (parseFloat(String(stock?.max_stock)) || 0) : 0,
        wipQty: hasStock ? (parseFloat(String(stock?.wip_qty)) || 0) : 0,
        lotCount: hasStock ? (Number(stock?.lot_count) || 0) : 0,
        lotDaysElapsed: hasStock ? (Number(stock?.days_elapsed) || 0) : 0,
        status: hasStock ? (stock?.status as StockStatusType | null) : null,
        useStatus: (item.is_active === false || item.status === 'inactive') ? 'inactive' : 'active',
        location: hasStock ? ((stock?.location as string) || '-') : '-',
        lastTransactionDate: hasStock ? (String(stock?.last_transaction_date ?? '') || '') : '',
        hasStock,
      };
    });
  };

  // ===== 통계 카드 =====
  const stats = [
    {
      label: '전체 품목',
      value: `${stockStats?.totalItems || 0}`,
      icon: Package,
      iconColor: 'text-gray-600',
      onClick: () => setStockStatusFilter('all'),
      isActive: stockStatusFilter === 'all',
    },
    {
      label: '정상 재고',
      value: `${stockStats?.normalCount || 0}`,
      icon: CheckCircle2,
      iconColor: 'text-green-600',
    },
    {
      label: '재고 부족',
      value: `${stockStats?.lowCount || 0}`,
      icon: AlertCircle,
      iconColor: 'text-red-600',
      onClick: () => setStockStatusFilter(stockStatusFilter === 'low' ? 'all' : 'low'),
      isActive: stockStatusFilter === 'low',
      tooltip: '현재 재고량이 안전재고(최소) 미만인 품목입니다.\n발주를 검토하여 재고를 보충해야 합니다.\n클릭하면 해당 품목만 필터링됩니다.',
    },
    {
      label: '안전재고 미달',
      value: `${stockStats?.outCount || 0}`,
      icon: AlertTriangle,
      iconColor: 'text-orange-600',
      onClick: () => setStockStatusFilter(stockStatusFilter === 'out' ? 'all' : 'out'),
      isActive: stockStatusFilter === 'out',
      tooltip: '재고가 0인 품목입니다.\n긴급 발주가 필요할 수 있습니다.\n클릭하면 해당 품목만 필터링됩니다.',
    },
  ];

  // ===== 필터 설정 (품목유형, 카테고리, 상태) =====
  const filterConfig: FilterFieldConfig[] = [
    {
      key: 'itemTypeTab',
      label: '품목유형',
      type: 'single',
      options: [
        { value: 'wip', label: '재공품' },
        { value: 'RM', label: '원자재' },
        { value: 'SM', label: '부자재' },
        { value: 'CS', label: '소모품' },
      ],
    },
    {
      key: 'itemCategory',
      label: '품목분류',
      type: 'single',
      options: [
        { value: 'BENDING', label: '절곡품' },
        { value: 'SCREEN', label: '스크린' },
        { value: 'STEEL', label: '철재' },
        { value: 'ALUMINUM', label: '알루미늄' },
      ],
    },
    {
      key: 'useStatus',
      label: '상태',
      type: 'single',
      options: [
        { value: 'active', label: '사용' },
        { value: 'inactive', label: '미사용' },
      ],
    },
  ];

  // ===== 테이블 컬럼 =====
  const tableColumns = useMemo(() => [
    { key: 'no', label: 'No.', className: 'w-[60px] text-center' },
    { key: 'itemCode', label: '품목코드', className: 'w-[80px]', copyable: true },
    { key: 'itemType', label: '품목유형', className: 'w-[80px]' },
    { key: 'itemName', label: '품목명', className: 'min-w-[150px]', copyable: true },
    { key: 'specification', label: '규격', className: 'w-[100px]', copyable: true },
    { key: 'unit', label: '단위', className: 'w-[60px] text-center', copyable: true },
    { key: 'calculatedQty', label: '재고량', className: 'w-[80px] text-center', copyable: true },
    { key: 'safetyStock', label: '안전재고', className: 'w-[80px] text-center', copyable: true },
    { key: 'maxStock', label: '최대재고', className: 'w-[80px] text-center', copyable: true },
    { key: 'wipQty', label: '재공품', className: 'w-[80px] text-center', copyable: true },
    { key: 'lastTransactionDate', label: '최종 입출고', className: 'w-[100px] text-center', sortable: true, copyable: true },
    { key: 'useStatus', label: '상태', className: 'w-[80px] text-center' },
  ], []);

  // ===== 테이블 행 렌더링 =====
  const renderTableRow = (
    item: StockItem,
    index: number,
    globalIndex: number,
    handlers: SelectionHandlers & RowClickHandlers<StockItem>
  ) => {
    return (
      <TableRow
        key={item.id}
        className={`cursor-pointer hover:bg-muted/50 ${handlers.isSelected ? 'bg-blue-50' : ''}`}
        onClick={(e) => handleRowClick(item, e)}
      >
        <TableCell className="text-center" onClick={(e) => e.stopPropagation()}>
          <Checkbox
            checked={handlers.isSelected}
            onCheckedChange={handlers.onToggle}
          />
        </TableCell>
        <TableCell className="text-center text-muted-foreground">{globalIndex}</TableCell>
        <TableCell className="font-medium">{item.itemCode}</TableCell>
        <TableCell>{ITEM_TYPE_LABELS[item.itemType] || '-'}</TableCell>
        <TableCell className="max-w-[150px] truncate">{item.itemName}</TableCell>
        <TableCell>{item.specification || '-'}</TableCell>
        <TableCell className="text-center">{item.unit}</TableCell>
        <TableCell className="text-center">{item.calculatedQty}</TableCell>
        <TableCell className="text-center">{item.safetyStock}</TableCell>
        <TableCell className="text-center">{item.maxStock}</TableCell>
        <TableCell className="text-center">{item.wipQty}</TableCell>
        <TableCell className="text-center text-xs text-muted-foreground">{item.lastTransactionDate}</TableCell>
        <TableCell className="text-center">
          <span className={item.useStatus === 'inactive' ? 'text-gray-400' : ''}>
            {USE_STATUS_LABELS[item.useStatus]}
          </span>
        </TableCell>
      </TableRow>
    );
  };

  // ===== 모바일 카드 렌더링 =====
  const renderMobileCard = (
    item: StockItem,
    index: number,
    globalIndex: number,
    handlers: SelectionHandlers & RowClickHandlers<StockItem>
  ) => {
    return (
      <ListMobileCard
        key={item.id}
        id={item.id}
        isSelected={handlers.isSelected}
        onToggleSelection={handlers.onToggle}
        onClick={() => handleRowClick(item)}
        headerBadges={
          <>
            <Badge variant="outline" className="text-xs">{globalIndex}</Badge>
          </>
        }
        title={item.itemName}
        statusBadge={
          <Badge
            variant="outline"
            className={`text-xs ${item.useStatus === 'inactive' ? 'text-gray-400' : ''}`}
          >
            {USE_STATUS_LABELS[item.useStatus]}
          </Badge>
        }
        infoGrid={
          <div className="grid grid-cols-2 gap-x-4 gap-y-3">
            <InfoField label="품목코드" value={item.itemCode} />
            <InfoField label="품목유형" value={ITEM_TYPE_LABELS[item.itemType] || '-'} />
            <InfoField label="규격" value={item.specification || '-'} />
            <InfoField label="단위" value={item.unit} />
            <InfoField label="재고량" value={`${item.calculatedQty}`} />
            <InfoField label="안전재고" value={`${item.safetyStock}`} />
            <InfoField label="최대재고" value={`${item.maxStock}`} />
            <InfoField label="재공품" value={`${item.wipQty}`} />
          </div>
        }
        actions={
          handlers.isSelected && (
            <div className="flex items-center gap-2">
              <Button
                variant="outline"
                size="sm"
                className="flex-1"
                onClick={(e) => {
                  e.stopPropagation();
                  handleRowClick(item);
                }}
              >
                <Eye className="w-4 h-4 mr-1" />
                상세
              </Button>
            </div>
          )
        }
      />
    );
  };

  // ===== UniversalListPage Config (수주관리 패턴 - useMemo 없음) =====
  const config: UniversalListConfig<StockItem> = {
    title: '재고 목록',
    description: '재고를 관리합니다',
    icon: Package,
    basePath: '/material/stock-status',

    idField: 'id',

    // 클라이언트 사이드 필터링 (수주관리 패턴)
    actions: {
      getList: async () => ({
        success: true,
        data: filteredStocks,
        totalCount: filteredStocks.length,
      }),
    },

    columns: tableColumns,

    // 클라이언트 사이드 필터링
    clientSideFiltering: true,
    itemsPerPage: ITEMS_PER_PAGE,

    // 검색
    searchPlaceholder: '품목코드, 품목명 검색...',

    // 검색 필터 함수
    searchFilter: (stock, searchValue) => {
      const searchLower = searchValue.toLowerCase();
      return (
        stock.itemCode.toLowerCase().includes(searchLower) ||
        stock.itemName.toLowerCase().includes(searchLower)
      );
    },

    // 커스텀 필터 함수
    customFilterFn: (items, fv) => {
      if (!items || items.length === 0) return items;
      return items.filter((item) => {
        // 재공품 필터 (사용: wipQty > 0, 미사용: wipQty === 0)
        const wipStatusVal = fv.wipStatus as string;
        if (wipStatusVal && wipStatusVal !== 'all') {
          if (wipStatusVal === 'active' && item.wipQty === 0) return false;
          if (wipStatusVal === 'inactive' && item.wipQty > 0) return false;
        }
        // 상태 필터
        const useStatusVal = fv.useStatus as string;
        if (useStatusVal && useStatusVal !== 'all' && item.useStatus !== useStatusVal) {
          return false;
        }
        return true;
      });
    },

    // 날짜 범위 필터
    dateRangeSelector: {
      enabled: true,
      showPresets: true,
      startDate,
      endDate,
      onStartDateChange: setStartDate,
      onEndDateChange: setEndDate,
    },

    // 필터 설정
    filterConfig,
    initialFilters: filterValues,

    // 통계
    computeStats: () => stats,

    // 테이블 푸터
    tableFooter: (
      <TableRow className="bg-gray-50 hover:bg-gray-50">
        <TableCell colSpan={11} className="py-3">
          <span className="text-sm text-muted-foreground">
            총 {filteredStocks.length}건
          </span>
        </TableCell>
      </TableRow>
    ),

    // 엑셀 다운로드 설정
    excelDownload: {
      columns: excelColumns,
      filename: '재고현황',
      sheetName: '재고',
      fetchAllUrl: '/api/proxy/stocks',
      fetchAllParams: ({ searchValue, filters }) => {
        const params: Record<string, string> = {};
        if (filters?.useStatus && filters.useStatus !== 'all') {
          params.use_status = filters.useStatus as string;
        }
        if (searchValue) {
          params.search = searchValue;
        }
        params.start_date = startDate;
        params.end_date = endDate;
        return params;
      },
      mapResponse: mapStockResponse,
    },

    renderTableRow,
    renderMobileCard,
  };

  // 로딩 상태
  if (isLoading) {
    return (
      <div className="flex items-center justify-center min-h-[400px]">
        <div className="flex flex-col items-center gap-4">
          <div className="h-8 w-8 animate-spin rounded-full border-4 border-blue-600 border-t-transparent" />
          <p className="text-muted-foreground">재고 목록을 불러오는 중...</p>
        </div>
      </div>
    );
  }

  return (
    <>
      <UniversalListPage<StockItem>
        config={config}
        initialData={filteredStocks}
        initialTotalCount={filteredStocks.length}
        onFilterChange={(newFilters) => setFilterValues(newFilters)}
        onSearchChange={setSearchTerm}
      />

      {/* 플로팅 액션 메뉴 */}
      {actionMenu && (
        <div
          className="fixed z-50 bg-white rounded-lg shadow-xl border border-gray-200 py-1 min-w-[160px]"
          style={{
            left: Math.min(actionMenu.x, window.innerWidth - 180),
            top: Math.min(actionMenu.y, window.innerHeight - 100),
          }}
          onClick={(e) => e.stopPropagation()}
        >
          <button
            className="w-full flex items-center gap-2 px-4 py-2.5 text-sm text-gray-700 hover:bg-blue-50 hover:text-blue-700 transition-colors"
            onClick={() => handleViewUsage(actionMenu.item)}
          >
            <History className="h-4 w-4" />
            사용현황 보기
          </button>
          <button
            className="w-full flex items-center gap-2 px-4 py-2.5 text-sm text-gray-700 hover:bg-gray-50 transition-colors"
            onClick={() => { setActionMenu(null); router.push(`/ko/material/stock-status/${actionMenu.item.id}?mode=view`); }}
          >
            <ExternalLink className="h-4 w-4" />
            상세보기
          </button>
        </div>
      )}

      {/* 사용현황 모달 */}
      <Dialog open={!!usageModalItem} onOpenChange={(open) => { if (!open) { setUsageModalItem(null); setUsageData(null); } }}>
        <DialogContent className="!max-w-2xl max-h-[80vh] flex flex-col p-0 gap-0">
          <DialogHeader className="px-6 py-4 border-b shrink-0">
            <DialogTitle className="text-lg font-semibold flex items-center gap-2">
              <History className="h-5 w-5 text-blue-600" />
              사용현황
            </DialogTitle>
            {usageModalItem && (
              <div className="flex items-center gap-3 mt-1">
                <span className="text-sm font-medium text-gray-900">{usageModalItem.itemCode}</span>
                <span className="text-sm text-gray-500">{usageModalItem.itemName}</span>
                {usageData && (
                  <span className="text-xs px-2 py-0.5 rounded-full bg-blue-100 text-blue-700">
                    현재 재고: {usageData.availableQty} {usageModalItem.unit}
                  </span>
                )}
              </div>
            )}
          </DialogHeader>

          <div className="flex-1 min-h-0 overflow-y-auto px-6 py-4">
            {usageLoading ? (
              <div className="flex items-center justify-center h-40">
                <Loader2 className="h-6 w-6 animate-spin text-blue-600" />
              </div>
            ) : usageData?.transactions.length ? (
              <div className="space-y-2">
                {usageData.transactions.map((tx) => (
                  <div key={tx.id} className="flex items-start gap-3 p-3 rounded-lg border bg-white hover:bg-gray-50">
                    <div className={`shrink-0 mt-0.5 w-8 h-8 rounded-full flex items-center justify-center text-xs font-bold ${
                      tx.qty < 0 ? 'bg-red-100 text-red-600' : 'bg-green-100 text-green-600'
                    }`}>
                      {tx.qty < 0 ? '출' : '입'}
                    </div>
                    <div className="flex-1 min-w-0">
                      <div className="flex items-center justify-between">
                        <span className="text-sm font-medium text-gray-900">{tx.typeLabel}</span>
                        <span className={`text-sm font-bold ${tx.qty < 0 ? 'text-red-600' : 'text-green-600'}`}>
                          {tx.qty > 0 ? '+' : ''}{tx.qty} {usageModalItem?.unit}
                        </span>
                      </div>
                      <div className="flex items-center gap-2 mt-0.5 text-xs text-gray-500">
                        {tx.referenceNo && <span className="font-medium text-blue-600">{tx.referenceNo}</span>}
                        {tx.lotNo && <span>LOT: {tx.lotNo}</span>}
                        <span>{tx.createdAt}</span>
                      </div>
                      {tx.remark && <p className="text-xs text-gray-400 mt-0.5">{tx.remark}</p>}
                    </div>
                    <div className="shrink-0 text-right">
                      <div className="text-xs text-gray-400">잔량</div>
                      <div className="text-sm font-medium">{tx.balanceQty}</div>
                    </div>
                  </div>
                ))}
              </div>
            ) : (
              <div className="flex items-center justify-center h-40 text-gray-400">
                사용 이력이 없습니다
              </div>
            )}
          </div>
        </DialogContent>
      </Dialog>
    </>
  );
}