'use client';

/**
 * 입고 목록 - 기획서 기준 마이그레이션
 *
 * 기획서 기준:
 * - 날짜 범위 필터
 * - 상태 셀렉트 필터 (전체, 입고대기, 입고완료, 검사완료)
 * - 통계 카드 (입고대기, 입고완료, 검사 중, 검사완료)
 * - 입고 등록 버튼
 * - 테이블 헤더: 체크박스, 번호, 로트번호, 수입검사, 검사일, 발주처, 품목코드, 품목명, 규격, 단위, 입고수량, 입고일, 작성자, 상태
 */

import { useState, useEffect, useMemo, useCallback } from 'react';
import { useRouter } from 'next/navigation';
import { getLocalDateString } from '@/lib/utils/date';
import {
  Package,
  CheckCircle2,
  Clock,
  ClipboardCheck,
  Plus,
  Eye,
  Settings2,
} 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 {
  UniversalListPage,
  type UniversalListConfig,
  type SelectionHandlers,
  type RowClickHandlers,
  type StatCard,
  type ListParams,
  type FilterFieldConfig,
} from '@/components/templates/UniversalListPage';
import { ListMobileCard, InfoField } from '@/components/organisms/MobileCard';
import { getReceivings, getReceivingStats, deleteReceiving } from './actions';
import {
  RECEIVING_STATUS_LABELS,
  RECEIVING_STATUS_STYLES,
  INSPECTION_STATUS_LABELS,
  INSPECTION_STATUS_STYLES,
  type InspectionDisplayStatus,
} from './types';
import { isNextRedirectError } from '@/lib/utils/redirect-error';
import type { ReceivingItem, ReceivingStats } from './types';

/**
 * 수입검사 표시 상태 결정
 * - 수입검사 템플릿이 연결되지 않으면 → none (수입검사 대상 아님)
 * - 검사결과가 '합격'이면 → passed
 * - 검사결과가 '불합격'이면 → failed
 * - 그 외 (템플릿 연결되어 있고 검사결과 없음) → waiting (대기)
 */
function getInspectionDisplayStatus(item: ReceivingItem): InspectionDisplayStatus {
  // 수입검사 템플릿이 연결되지 않은 경우 수입검사 대상 아님
  if (!item.hasInspectionTemplate) {
    return 'none';
  }

  // 검사결과에 따른 상태
  if (item.inspectionResult === '합격') {
    return 'passed';
  }
  if (item.inspectionResult === '불합격') {
    return 'failed';
  }

  // 템플릿이 연결되어 있지만 검사결과가 없으면 대기 상태
  return 'waiting';
}

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

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

  // ===== 통계 데이터 (외부 관리) =====
  const [stats, setStats] = useState<ReceivingStats | null>(null);
  const [totalItems, setTotalItems] = useState(0);

  // ===== 날짜 범위 상태 (최근 30일) =====
  const today = new Date();
  const thirtyDaysAgo = new Date(today.getTime() - 30 * 24 * 60 * 60 * 1000);
  const [startDate, setStartDate] = useState<string>(getLocalDateString(thirtyDaysAgo));
  const [endDate, setEndDate] = useState<string>(getLocalDateString(today));

  // ===== 필터 상태 =====
  const [filterValues, setFilterValues] = useState<Record<string, string | string[]>>({
    status: 'all',
  });

  // 초기 통계 로드
  useEffect(() => {
    const loadStats = async () => {
      try {
        const result = await getReceivingStats();
        if (result.success && result.data) {
          setStats(result.data);
        }
      } catch (error) {
        if (isNextRedirectError(error)) throw error;
        console.error('[ReceivingList] loadStats error:', error);
      }
    };
    loadStats();
  }, []);

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

  // ===== 입고 등록 핸들러 =====
  const handleRegister = useCallback(() => {
    router.push('/ko/material/receiving-management/new?mode=new');
  }, [router]);

  // ===== 통계 카드 =====
  const statCards: StatCard[] = useMemo(
    () => [
      {
        label: '입고대기',
        value: `${stats?.receivingPendingCount ?? 0}`,
        icon: Clock,
        iconColor: 'text-yellow-600',
      },
      {
        label: '입고완료',
        value: `${stats?.receivingCompletedCount ?? 0}`,
        icon: CheckCircle2,
        iconColor: 'text-green-600',
      },
      {
        label: '검사 중',
        value: `${stats?.inspectionPendingCount ?? 0}`,
        icon: ClipboardCheck,
        iconColor: 'text-orange-600',
      },
      {
        label: '검사완료',
        value: `${stats?.inspectionCompletedCount ?? 0}`,
        icon: CheckCircle2,
        iconColor: 'text-blue-600',
      },
    ],
    [stats]
  );

  // ===== 필터 설정 =====
  const filterConfig: FilterFieldConfig[] = [
    {
      key: 'status',
      label: '상태',
      type: 'single',
      options: [
        { value: 'receiving_pending', label: '입고대기' },
        { value: 'completed', label: '입고완료' },
        { value: 'inspection_completed', label: '검사완료' },
      ],
    },
  ];

  // ===== 테이블 푸터 =====
  const tableFooter = useMemo(
    () => (
      <TableRow className="bg-gray-50 hover:bg-gray-50">
        <TableCell colSpan={18} className="py-3">
          <span className="text-sm text-muted-foreground">
            총 {totalItems}건
          </span>
        </TableCell>
      </TableRow>
    ),
    [totalItems]
  );

  // ===== UniversalListPage Config =====
  const config: UniversalListConfig<ReceivingItem> = useMemo(
    () => ({
      // 페이지 기본 정보
      title: '입고 목록',
      description: '입고를 관리합니다',
      icon: Package,
      basePath: '/material/receiving-management',

      // ID 추출
      idField: 'id',

      // API 액션 (서버 사이드 페이지네이션)
      actions: {
        deleteItem: async (id: string) => {
          const result = await deleteReceiving(id);
          if (result.success) {
            const statsResult = await getReceivingStats();
            if (statsResult.success && statsResult.data) {
              setStats(statsResult.data);
            }
          }
          return { success: result.success, error: result.error };
        },
        getList: async (params?: ListParams) => {
          try {
            const statusFilter = params?.filters?.status as string;
            const result = await getReceivings({
              page: params?.page || 1,
              perPage: params?.pageSize || ITEMS_PER_PAGE,
              status: statusFilter !== 'all' ? statusFilter : undefined,
              search: params?.search || undefined,
              startDate,
              endDate,
            });

            if (result.success) {
              // 통계 다시 로드
              const statsResult = await getReceivingStats();
              if (statsResult.success && statsResult.data) {
                setStats(statsResult.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: 'No.', className: 'w-[50px] text-center' },
        { key: 'materialNo', label: '입고번호', className: 'w-[130px]', copyable: true },
        { key: 'lotNo', label: '원자재로트', className: 'w-[120px]', copyable: true },
        { key: 'inspectionStatus', label: '수입검사', className: 'w-[70px] text-center' },
        { key: 'status', label: '상태', className: 'w-[80px] text-center' },
        { key: 'inspectionDate', label: '검사일', className: 'w-[90px] text-center', copyable: true },
        { key: 'supplier', label: '발주처', className: 'min-w-[100px]', copyable: true },
        { key: 'manufacturer', label: '제조사', className: 'min-w-[100px]', copyable: true },
        { key: 'itemCode', label: '품목코드', className: 'min-w-[100px]', copyable: true },
        { key: 'itemName', label: '품목명', className: 'min-w-[130px]', copyable: true },
        { key: 'specification', label: '규격', className: 'w-[90px]', copyable: true },
        { key: 'unit', label: '단위', className: 'w-[50px] text-center', copyable: true },
        { key: 'receivingQty', label: '수량', className: 'w-[60px] text-center', copyable: true },
        { key: 'receivingDate', label: '입고변경일', className: 'w-[100px] text-center', copyable: true },
        { key: 'createdBy', label: '작성자', className: 'w-[70px] text-center', copyable: true },
        { key: 'itemType', label: '품목유형', className: 'w-[80px] text-center' },
      ],

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

      // 검색
      searchPlaceholder: '로트번호, 품목코드, 품목명 검색...',
      searchFilter: (item: ReceivingItem, search: string) => {
        const s = search.toLowerCase();
        return (
          item.lotNo?.toLowerCase().includes(s) ||
          item.itemCode?.toLowerCase().includes(s) ||
          item.itemName?.toLowerCase().includes(s) ||
          false
        );
      },

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

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

      // 통계 카드
      stats: statCards,

      // 헤더 액션 (입고 등록 버튼)
      headerActions: () => (
        <div className="flex items-center gap-2">
          <Button
            variant="default"
            size="sm"
            className="bg-gray-900 text-white hover:bg-gray-800"
            onClick={handleRegister}
          >
            <Plus className="w-4 h-4 mr-1" />
            입고 등록
          </Button>
        </div>
      ),

      // 테이블 푸터
      tableFooter,

      // 테이블 행 렌더링
      renderTableRow: (
        item: ReceivingItem,
        index: number,
        globalIndex: number,
        handlers: SelectionHandlers & RowClickHandlers<ReceivingItem>
      ) => {
        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>{item.materialNo || '-'}</TableCell>
            <TableCell className="font-medium">{item.lotNo || '-'}</TableCell>
            <TableCell className="text-center">
              {(() => {
                const status = getInspectionDisplayStatus(item);
                if (status === 'none') return '-';
                return (
                  <Badge className={`text-xs ${INSPECTION_STATUS_STYLES[status]}`}>
                    {INSPECTION_STATUS_LABELS[status]}
                  </Badge>
                );
              })()}
            </TableCell>
            <TableCell className="text-center">
              <Badge className={`text-xs ${RECEIVING_STATUS_STYLES[item.status]}`}>
                {RECEIVING_STATUS_LABELS[item.status]}
              </Badge>
            </TableCell>
            <TableCell className="text-center">{item.inspectionDate || '-'}</TableCell>
            <TableCell>{item.supplier}</TableCell>
            <TableCell>{item.manufacturer || '-'}</TableCell>
            <TableCell>{item.itemCode}</TableCell>
            <TableCell className="max-w-[130px] truncate">{item.itemName}</TableCell>
            <TableCell>{item.specification || '-'}</TableCell>
            <TableCell className="text-center">{item.unit}</TableCell>
            <TableCell className="text-center">
              {item.receivingQty !== undefined ? item.receivingQty : '-'}
            </TableCell>
            <TableCell className="text-center">{item.receivingDate || '-'}</TableCell>
            <TableCell className="text-center">{item.createdBy || '-'}</TableCell>
            <TableCell className="text-center">{item.itemType || '-'}</TableCell>
          </TableRow>
        );
      },

      // 모바일 카드 렌더링
      renderMobileCard: (
        item: ReceivingItem,
        index: number,
        globalIndex: number,
        handlers: SelectionHandlers & RowClickHandlers<ReceivingItem>
      ) => {
        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>
                {item.lotNo && (
                  <Badge variant="outline" className="text-xs">
                    {item.lotNo}
                  </Badge>
                )}
              </>
            }
            title={item.itemName}
            statusBadge={
              <Badge className={`text-xs ${RECEIVING_STATUS_STYLES[item.status]}`}>
                {RECEIVING_STATUS_LABELS[item.status]}
              </Badge>
            }
            infoGrid={
              <div className="grid grid-cols-2 gap-x-4 gap-y-3">
                <InfoField label="품목코드" value={item.itemCode || '-'} />
                <InfoField label="품목유형" value={item.itemType || '-'} />
                <InfoField label="발주처" value={item.supplier} />
                <InfoField label="제조사" value={item.manufacturer || '-'} />
                <InfoField
                  label="수입검사"
                  value={(() => {
                    const status = getInspectionDisplayStatus(item);
                    if (status === 'none') return '-';
                    return (
                      <Badge className={`text-xs ${INSPECTION_STATUS_STYLES[status]}`}>
                        {INSPECTION_STATUS_LABELS[status]}
                      </Badge>
                    );
                  })()}
                />
                <InfoField label="수량" value={item.receivingQty !== undefined ? `${item.receivingQty}` : '-'} />
                <InfoField label="입고변경일" value={item.receivingDate || '-'} />
              </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>
              )
            }
          />
        );
      },
    }),
    [statCards, filterConfig, filterValues, tableFooter, handleRowClick, handleRegister, startDate, endDate]
  );

  return (
    <UniversalListPage
      config={config}
      onFilterChange={(newFilters) => setFilterValues(newFilters)}
    />
  );
}
