'use client';

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

import { useState, useEffect, useMemo, useCallback } from 'react';
import { useRouter } from 'next/navigation';
import {
  Package,
  CheckCircle2,
  Clock,
  AlertCircle,
  Eye,
} 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 TabOption,
  type StatCard,
  type ListParams,
} from '@/components/templates/UniversalListPage';
import { ListMobileCard, InfoField } from '@/components/organisms/MobileCard';
import { getStocks, getStockStats, getStockStatsByType } from './actions';
import { ITEM_TYPE_LABELS, ITEM_TYPE_STYLES, STOCK_STATUS_LABELS } from './types';
import { isNextRedirectError } from '@/lib/utils/redirect-error';
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 [typeStats, setTypeStats] = useState<Record<string, { label: string; count: number; total_qty: number | string }>>({});
  const [totalItems, setTotalItems] = useState(0);

  // 초기 통계 로드
  useEffect(() => {
    const loadStats = async () => {
      try {
        const [statsResult, typeStatsResult] = await Promise.all([
          getStockStats(),
          getStockStatsByType(),
        ]);
        if (statsResult.success && statsResult.data) {
          setStockStats(statsResult.data);
        }
        if (typeStatsResult.success && typeStatsResult.data) {
          setTypeStats(typeStatsResult.data);
        }
      } catch (error) {
        if (isNextRedirectError(error)) throw error;
        console.error('[StockStatusList] loadStats error:', error);
      }
    };
    loadStats();
  }, []);

  // ===== 행 클릭 핸들러 =====
  const handleRowClick = useCallback(
    (item: StockItem) => {
      router.push(`/ko/material/stock-status/${item.id}?mode=view`);
    },
    [router]
  );

  // ===== 엑셀 컬럼 정의 =====
  const excelColumns: ExcelColumn<StockItem>[] = useMemo(() => [
    { header: '품목코드', key: 'itemCode' },
    { header: '품목명', key: 'itemName' },
    { header: '품목유형', key: 'itemType', transform: (value) => ITEM_TYPE_LABELS[value as ItemType] || String(value) },
    { header: '단위', key: 'unit' },
    { header: '재고량', key: 'stockQty' },
    { header: '안전재고', key: 'safetyStock' },
    { header: 'LOT수', key: 'lotCount' },
    { header: 'LOT경과일', key: 'lotDaysElapsed' },
    { header: '상태', key: 'status', transform: (value) => value ? STOCK_STATUS_LABELS[value as StockStatusType] : '-' },
    { header: '위치', key: 'location' },
  ], []);

  // ===== API 응답 매핑 함수 =====
  const mapStockResponse = useCallback((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,
        unit: (item.unit ?? 'EA') as string,
        stockQty: hasStock ? (parseFloat(String(stock?.stock_qty)) || 0) : 0,
        safetyStock: hasStock ? (parseFloat(String(stock?.safety_stock)) || 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,
        location: hasStock ? ((stock?.location as string) || '-') : '-',
        hasStock,
      };
    });
  }, []);

  // ===== 통계 카드 =====
  const stats: StatCard[] = useMemo(
    () => [
      {
        label: '전체 품목',
        value: `${stockStats?.totalItems || 0}종`,
        icon: Package,
        iconColor: 'text-gray-600',
      },
      {
        label: '정상 재고',
        value: `${stockStats?.normalCount || 0}종`,
        icon: CheckCircle2,
        iconColor: 'text-green-600',
      },
      {
        label: '재고 부족',
        value: `${stockStats?.lowCount || 0}종`,
        icon: Clock,
        iconColor: 'text-orange-600',
      },
      {
        label: '재고 없음',
        value: `${stockStats?.outCount || 0}종`,
        icon: AlertCircle,
        iconColor: 'text-red-600',
      },
    ],
    [stockStats]
  );

  // ===== 탭 옵션 (기본 탭 + 품목유형별 통계) =====
  const tabs: TabOption[] = useMemo(() => {
    // 기본 탭 정의 (Item 모델의 MATERIAL_TYPES: RM, SM, CS)
    const defaultTabs: { value: string; label: string }[] = [
      { value: 'all', label: '전체' },
      { value: 'RM', label: '원자재' },
      { value: 'SM', label: '부자재' },
      { value: 'CS', label: '소모품' },
    ];

    return defaultTabs.map((tab) => {
      if (tab.value === 'all') {
        return { ...tab, count: stockStats?.totalItems || 0 };
      }
      const stat = typeStats[tab.value];
      const count = typeof stat?.count === 'number' ? stat.count : 0;
      return { ...tab, count };
    });
  }, [typeStats, stockStats?.totalItems]);

  // ===== 테이블 푸터 =====
  const tableFooter = useMemo(() => {
    const lowStockCount = stockStats?.lowCount || 0;
    return (
      <TableRow className="bg-gray-50 hover:bg-gray-50">
        <TableCell colSpan={12} className="py-3">
          <span className="text-sm text-muted-foreground">
            총 {totalItems}종 / 재고부족 {lowStockCount}종
          </span>
        </TableCell>
      </TableRow>
    );
  }, [totalItems, stockStats?.lowCount]);

  // ===== UniversalListPage Config =====
  const config: UniversalListConfig<StockItem> = useMemo(
    () => ({
      // 페이지 기본 정보
      title: '재고 목록',
      description: '재고현황 관리',
      icon: Package,
      basePath: '/material/stock-status',

      // ID 추출
      idField: 'id',

      // API 액션 (서버 사이드 페이지네이션)
      actions: {
        getList: async (params?: ListParams) => {
          try {
            const result = await getStocks({
              page: params?.page || 1,
              perPage: params?.pageSize || ITEMS_PER_PAGE,
              itemType: params?.tab !== 'all' ? (params?.tab as ItemType) : undefined,
              search: params?.search || undefined,
            });

            if (result.success) {
              // 통계 및 품목유형별 통계 다시 로드
              const [statsResult, typeStatsResult] = await Promise.all([
                getStockStats(),
                getStockStatsByType(),
              ]);
              if (statsResult.success && statsResult.data) {
                setStockStats(statsResult.data);
              }
              if (typeStatsResult.success && typeStatsResult.data) {
                setTypeStats(typeStatsResult.data);
              }

              // totalItems 업데이트 (푸터용)
              setTotalItems(result.pagination.total);

              return {
                success: true,
                data: result.data,
                totalCount: result.pagination.total,
                totalPages: result.pagination.lastPage,
              };
            }
            return { success: false, error: result.error };
          } catch (error) {
            if (isNextRedirectError(error)) throw error;
            return { success: false, error: '데이터 로드 중 오류가 발생했습니다.' };
          }
        },
      },

      // 테이블 컬럼
      columns: [
        { key: 'no', label: '번호', className: 'w-[60px] text-center' },
        { key: 'itemCode', label: '품목코드', className: 'min-w-[120px]' },
        { key: 'itemName', label: '품목명', className: 'min-w-[200px]' },
        { key: 'itemType', label: '품목유형', className: 'w-[100px]' },
        { key: 'unit', label: '단위', className: 'w-[60px] text-center' },
        { key: 'stockQty', label: '재고량', className: 'w-[80px] text-center' },
        { key: 'safetyStock', label: '안전재고', className: 'w-[80px] text-center' },
        { key: 'lot', label: 'LOT', className: 'w-[100px] text-center' },
        { key: 'status', label: '상태', className: 'w-[60px] text-center' },
        { key: 'location', label: '위치', className: 'w-[60px] text-center' },
      ],

      // 서버 사이드 페이지네이션
      clientSideFiltering: false,
      itemsPerPage: ITEMS_PER_PAGE,

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

      // 탭 설정
      tabs,
      defaultTab: 'all',

      // 통계 카드
      stats,

      // 테이블 푸터
      tableFooter,

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

      // 테이블 행 렌더링
      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={() => handleRowClick(item)}
          >
            <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 className="max-w-[200px] truncate">{item.itemName}</TableCell>
            <TableCell>
              <Badge className={`text-xs ${ITEM_TYPE_STYLES[item.itemType]}`}>
                {ITEM_TYPE_LABELS[item.itemType]}
              </Badge>
            </TableCell>
            <TableCell className="text-center">{item.unit}</TableCell>
            <TableCell className="text-center">{item.stockQty}</TableCell>
            <TableCell className="text-center">{item.safetyStock}</TableCell>
            <TableCell className="text-center">
              <div className="flex flex-col items-center">
                <span>{item.lotCount}개</span>
                {item.lotDaysElapsed > 0 && (
                  <span className="text-xs text-muted-foreground">
                    {item.lotDaysElapsed}일 경과
                  </span>
                )}
              </div>
            </TableCell>
            <TableCell className="text-center">
              {item.status ? (
                <span className={item.status === 'low' ? 'text-orange-600 font-medium' : ''}>
                  {STOCK_STATUS_LABELS[item.status]}
                </span>
              ) : (
                <span className="text-gray-400">-</span>
              )}
            </TableCell>
            <TableCell className="text-center">{item.location}</TableCell>
          </TableRow>
        );
      },

      // 모바일 카드 렌더링
      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>
                <Badge variant="outline" className="text-xs">{item.itemCode}</Badge>
              </>
            }
            title={item.itemName}
            statusBadge={
              <Badge className={`text-xs ${ITEM_TYPE_STYLES[item.itemType]}`}>
                {ITEM_TYPE_LABELS[item.itemType]}
              </Badge>
            }
            infoGrid={
              <div className="grid grid-cols-2 gap-x-4 gap-y-3">
                <InfoField label="단위" value={item.unit} />
                <InfoField label="위치" value={item.location} />
                <InfoField label="재고량" value={`${item.stockQty}`} />
                <InfoField label="안전재고" value={`${item.safetyStock}`} />
                <InfoField
                  label="LOT"
                  value={`${item.lotCount}개${item.lotDaysElapsed > 0 ? ` (${item.lotDaysElapsed}일 경과)` : ''}`}
                />
                <InfoField
                  label="상태"
                  value={item.status ? STOCK_STATUS_LABELS[item.status] : '-'}
                  className={item.status === 'low' ? 'text-orange-600' : ''}
                />
              </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>
              )
            }
          />
        );
      },
    }),
    [tabs, stats, tableFooter, handleRowClick, excelColumns, mapStockResponse]
  );

  return <UniversalListPage config={config} />;
}