'use client';

/**
 * 출하 목록 - UniversalListPage 마이그레이션
 *
 * 기존 IntegratedListTemplateV2 → UniversalListPage config 기반으로 변환
 * - 서버 사이드 페이지네이션 (getShipments API)
 * - 통계 카드 (getShipmentStats API)
 * - 상태별 탭 필터 (getShipmentStatsByStatus API)
 * - 경고 배너 (출고불가 건수)
 */

import { useState, useEffect, useMemo, useCallback } from 'react';
import { useRouter } from 'next/navigation';
import {
  Truck,
  Package,
  Clock,
  AlertTriangle,
  Eye,
  Plus,
  Check,
  X,
} from 'lucide-react';
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 { Alert, AlertDescription } from '@/components/ui/alert';
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 { getShipments, getShipmentStats, getShipmentStatsByStatus } from './actions';
import {
  SHIPMENT_STATUS_LABELS,
  SHIPMENT_STATUS_STYLES,
} from './types';
import type { ShipmentItem, ShipmentStatus, ShipmentStats, ShipmentStatusStats } from './types';
import { isNextRedirectError } from '@/lib/utils/redirect-error';

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

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

  // ===== 통계 및 상태별 통계 (외부 관리) =====
  const [shipmentStats, setShipmentStats] = useState<ShipmentStats | null>(null);
  const [statusStats, setStatusStats] = useState<ShipmentStatusStats>({});
  const [cannotShipCount, setCannotShipCount] = useState(0);

  // 초기 통계 로드
  useEffect(() => {
    const loadStats = async () => {
      try {
        const [statsResult, statusStatsResult] = await Promise.all([
          getShipmentStats(),
          getShipmentStatsByStatus(),
        ]);
        if (statsResult.success && statsResult.data) {
          setShipmentStats(statsResult.data);
        }
        if (statusStatsResult.success && statusStatsResult.data) {
          setStatusStats(statusStatsResult.data);
        }
      } catch (error) {
        if (isNextRedirectError(error)) throw error;
        console.error('[ShipmentList] loadStats error:', error);
      }
    };
    loadStats();
  }, []);

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

  // ===== 등록 핸들러 =====
  const handleCreate = useCallback(() => {
    router.push('/ko/outbound/shipments?mode=new');
  }, [router]);

  // ===== 통계 카드 =====
  const stats: StatCard[] = useMemo(
    () => [
      {
        label: '당일 출하',
        value: `${shipmentStats?.todayShipmentCount || 0}건`,
        icon: Package,
        iconColor: 'text-green-600',
      },
      {
        label: '출고 대기',
        value: `${shipmentStats?.scheduledCount || 0}건`,
        icon: Clock,
        iconColor: 'text-yellow-600',
      },
      {
        label: '배송중',
        value: `${shipmentStats?.shippingCount || 0}건`,
        icon: Truck,
        iconColor: 'text-blue-600',
      },
      {
        label: '긴급 출하',
        value: `${shipmentStats?.urgentCount || 0}건`,
        icon: AlertTriangle,
        iconColor: 'text-red-600',
      },
    ],
    [shipmentStats]
  );

  // ===== 탭 옵션 (기본 탭 + 상태별 통계) =====
  const tabs: TabOption[] = useMemo(() => {
    // 기본 탭 정의 (API 데이터 없어도 항상 표시)
    const defaultTabs: { value: string; label: string }[] = [
      { value: 'all', label: '전체' },
      { value: 'scheduled', label: '출고예정' },
      { value: 'ready', label: '출하대기' },
      { value: 'shipping', label: '배송중' },
      { value: 'delivered', label: '배송완료' },
    ];

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

  // ===== 경고 배너 =====
  const alertBanner = useMemo(() => {
    if (cannotShipCount <= 0) return undefined;
    return (
      <Alert className="mb-4 bg-orange-50 border-orange-200">
        <AlertTriangle className="h-4 w-4 text-orange-600" />
        <AlertDescription className="text-orange-800">
          출고불가 {cannotShipCount}건 - 입금확인 및 세금계산서 발행 완료 후 출고 진행이 가능합니다.
        </AlertDescription>
      </Alert>
    );
  }, [cannotShipCount]);

  // ===== UniversalListPage Config =====
  const config: UniversalListConfig<ShipmentItem> = useMemo(
    () => ({
      // 페이지 기본 정보
      title: '출하 목록',
      description: '출하 관리',
      icon: Truck,
      basePath: '/outbound/shipments',

      // ID 추출
      idField: 'id',

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

            if (result.success) {
              // 통계 및 상태별 통계 다시 로드
              const [statsResult, statusStatsResult] = await Promise.all([
                getShipmentStats(),
                getShipmentStatsByStatus(),
              ]);
              if (statsResult.success && statsResult.data) {
                setShipmentStats(statsResult.data);
              }
              if (statusStatsResult.success && statusStatsResult.data) {
                setStatusStats(statusStatsResult.data);
              }

              // 출고불가 건수 계산
              const cannotShip = result.data.filter((item) => !item.canShip).length;
              setCannotShipCount(cannotShip);

              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: 'shipmentNo', label: '출고번호', className: 'min-w-[130px]' },
        { key: 'lotNo', label: '로트번호', className: 'min-w-[150px]' },
        { key: 'scheduledDate', label: '출고예정일', className: 'w-[120px] text-center' },
        { key: 'status', label: '상태', className: 'w-[100px] text-center' },
        { key: 'canShip', label: '출하가능', className: 'w-[80px] text-center' },
        { key: 'deliveryMethod', label: '배송', className: 'w-[100px] text-center' },
        { key: 'customerName', label: '발주처', className: 'min-w-[120px]' },
        { key: 'siteName', label: '현장명', className: 'min-w-[120px]' },
        { key: 'manager', label: '담당', className: 'w-[80px] text-center' },
        { key: 'deliveryTime', label: '납기(수배시간)', className: 'w-[120px] text-center' },
      ],

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

      // 검색
      searchPlaceholder: '출고번호, 로트번호, 발주처, 현장명 검색...',
      searchFilter: (item: ShipmentItem, search: string) => {
        const s = search.toLowerCase();
        return (
          item.shipmentNo?.toLowerCase().includes(s) ||
          item.lotNo?.toLowerCase().includes(s) ||
          item.customerName?.toLowerCase().includes(s) ||
          item.siteName?.toLowerCase().includes(s) ||
          false
        );
      },

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

      // 통계 카드
      stats,

      // 경고 배너
      alertBanner,

      // 헤더 액션 (출하 등록)
      headerActions: () => (
        <Button onClick={handleCreate}>
          <Plus className="w-4 h-4 mr-2" />
          출하 등록
        </Button>
      ),

      // 테이블 행 렌더링
      renderTableRow: (
        item: ShipmentItem,
        index: number,
        globalIndex: number,
        handlers: SelectionHandlers & RowClickHandlers<ShipmentItem>
      ) => {
        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.shipmentNo}</TableCell>
            <TableCell>{item.lotNo}</TableCell>
            <TableCell className="text-center">{item.scheduledDate}</TableCell>
            <TableCell className="text-center">
              <Badge className={`text-xs ${SHIPMENT_STATUS_STYLES[item.status]}`}>
                {SHIPMENT_STATUS_LABELS[item.status]}
              </Badge>
            </TableCell>
            <TableCell className="text-center">
              {item.canShip ? (
                <Check className="w-4 h-4 mx-auto text-green-600" />
              ) : (
                <X className="w-4 h-4 mx-auto text-red-600" />
              )}
            </TableCell>
            <TableCell className="text-center">{item.deliveryMethodLabel}</TableCell>
            <TableCell>{item.customerName}</TableCell>
            <TableCell className="max-w-[120px] truncate">{item.siteName}</TableCell>
            <TableCell className="text-center">{item.manager || '-'}</TableCell>
            <TableCell className="text-center">{item.deliveryTime || '-'}</TableCell>
          </TableRow>
        );
      },

      // 모바일 카드 렌더링
      renderMobileCard: (
        item: ShipmentItem,
        index: number,
        globalIndex: number,
        handlers: SelectionHandlers & RowClickHandlers<ShipmentItem>
      ) => {
        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.shipmentNo}
                </Badge>
              </>
            }
            title={item.siteName}
            statusBadge={
              <Badge className={`text-xs ${SHIPMENT_STATUS_STYLES[item.status]}`}>
                {SHIPMENT_STATUS_LABELS[item.status]}
              </Badge>
            }
            infoGrid={
              <div className="grid grid-cols-2 gap-x-4 gap-y-3">
                <InfoField label="로트번호" value={item.lotNo} />
                <InfoField label="발주처" value={item.customerName} />
                <InfoField label="출고예정일" value={item.scheduledDate} />
                <InfoField label="배송방식" value={item.deliveryMethodLabel} />
                <InfoField label="출하가능" value={item.canShip ? '가능' : '불가'} />
              </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, alertBanner, handleRowClick, handleCreate]
  );

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