'use client';

/**
 * 작업실적 조회 - UniversalListPage 마이그레이션
 *
 * 기존 IntegratedListTemplateV2 → UniversalListPage config 기반으로 변환
 * - 서버 사이드 페이지네이션 (getWorkResults API)
 * - 통계 카드 (getWorkResultStats API)
 * - 기본 리스트 (탭 없음)
 */

import { useState, useEffect, useMemo, useCallback } from 'react';
import {
  BarChart3,
  Package,
  CheckCircle2,
  XCircle,
  Percent,
  CheckCircle,
} from 'lucide-react';
import type { ExcelColumn } from '@/lib/utils/excel-download';
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,
} from '@/components/templates/UniversalListPage';
import { ListMobileCard, InfoField } from '@/components/organisms/MobileCard';
import { getWorkResults, getWorkResultStats } from './actions';
import type { WorkResult, WorkResultStats } from './types';
import { isNextRedirectError } from '@/lib/utils/redirect-error';
import { formatNumber } from '@/lib/utils/amount';

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

export function WorkResultList() {
  // ===== 통계 데이터 (외부 관리 - 별도 API) =====
  const [statsData, setStatsData] = useState<WorkResultStats>({
    totalProduction: 0,
    totalGood: 0,
    totalDefect: 0,
    defectRate: 0,
  });

  // 통계 데이터 로드 (초기 1회)
  useEffect(() => {
    const loadStats = async () => {
      try {
        const result = await getWorkResultStats();
        if (result.success && result.data) {
          setStatsData(result.data);
        }
      } catch (error) {
        if (isNextRedirectError(error)) throw error;
        console.error('[WorkResultList] loadStats error:', error);
      }
    };
    loadStats();
  }, []);

  // ===== 상세 보기 핸들러 =====
  const handleView = useCallback((_item: WorkResult) => {
    // TODO: 상세 보기 기능 구현
  }, []);

  // ===== 엑셀 컬럼 정의 =====
  const excelColumns: ExcelColumn<WorkResult>[] = useMemo(() => [
    { header: '로트번호', key: 'lotNo' },
    { header: '작업일', key: 'workDate' },
    { header: '작업지시번호', key: 'workOrderNo' },
    { header: '공정', key: 'processName' },
    { header: '품목명', key: 'productName' },
    { header: '규격', key: 'specification' },
    { header: '생산수량', key: 'productionQty' },
    { header: '양품수량', key: 'goodQty' },
    { header: '불량수량', key: 'defectQty' },
    { header: '불량률(%)', key: 'defectRate' },
    { header: '검사', key: 'inspection', transform: (value): string => value ? '완료' : '대기' },
    { header: '포장', key: 'packaging', transform: (value): string => value ? '완료' : '대기' },
    { header: '작업자', key: 'workerName', transform: (value): string => (value as string) || '-' },
  ], []);

  // ===== API 응답 매핑 함수 =====
  const mapWorkResultResponse = useCallback((result: unknown): WorkResult[] => {
    const data = result as { data?: { data?: Record<string, unknown>[] } };
    const rawItems = data.data?.data ?? [];
    return rawItems.map((api: Record<string, unknown>) => {
      const options = api.options as { result?: Record<string, unknown> } | null;
      const apiResult = options?.result;
      const goodQty = Number(apiResult?.good_qty ?? 0);
      const defectQty = Number(apiResult?.defect_qty ?? 0);
      const workOrder = api.work_order as Record<string, unknown> | undefined;
      const process = workOrder?.process as Record<string, unknown> | undefined;

      return {
        id: String(api.id ?? ''),
        workOrderId: Number(api.work_order_id ?? 0),
        lotNo: (apiResult?.lot_no as string) || '-',
        workDate: (apiResult?.completed_at as string) || (api.updated_at as string) || '',
        workOrderNo: (workOrder?.work_order_no as string) || '-',
        projectName: (workOrder?.project_name as string) || '-',
        processName: (process?.process_name as string) || '-',
        processCode: (process?.process_code as string) || '-',
        productName: (api.item_name as string) || '',
        specification: (api.specification as string) || '-',
        quantity: parseFloat(String(api.quantity)) || 0,
        productionQty: goodQty + defectQty,
        goodQty,
        defectQty,
        defectRate: Number(apiResult?.defect_rate ?? 0),
        inspection: Boolean(apiResult?.is_inspected),
        packaging: Boolean(apiResult?.is_packaged),
        workerId: (apiResult?.worker_id as number) ?? null,
        workerName: (api.worker_name as string) ?? null,
        memo: (apiResult?.memo as string) ?? null,
      };
    });
  }, []);

  // ===== 통계 카드 =====
  const stats: StatCard[] = useMemo(
    () => [
      {
        label: '총 생산수량',
        value: `${formatNumber(statsData.totalProduction)}개`,
        icon: Package,
        iconColor: 'text-gray-600',
      },
      {
        label: '양품수량',
        value: `${formatNumber(statsData.totalGood)}개`,
        icon: CheckCircle2,
        iconColor: 'text-green-600',
      },
      {
        label: '불량수량',
        value: `${formatNumber(statsData.totalDefect)}개`,
        icon: XCircle,
        iconColor: 'text-red-600',
      },
      {
        label: '불량률',
        value: `${statsData.defectRate.toFixed(1)}%`,
        icon: Percent,
        iconColor: 'text-orange-600',
      },
    ],
    [statsData]
  );

  // ===== UniversalListPage Config =====
  const config: UniversalListConfig<WorkResult> = useMemo(
    () => ({
      // 페이지 기본 정보
      title: '작업실적 조회',
      description: '생산 작업실적 조회',
      icon: BarChart3,
      basePath: '/production/work-results',

      // ID 추출
      idField: 'id',

      // API 액션 (서버 사이드 페이지네이션)
      actions: {
        getList: async (params?: ListParams) => {
          try {
            const result = await getWorkResults({
              page: params?.page || 1,
              size: params?.pageSize || ITEMS_PER_PAGE,
              q: params?.search || undefined,
            });

            if (result.success) {
              // 통계도 다시 로드
              const statsResult = await getWorkResultStats();
              if (statsResult.success && statsResult.data) {
                setStatsData(statsResult.data);
              }

              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: 'lotNo', label: '로트번호', className: 'min-w-[150px]', copyable: true },
        { key: 'workDate', label: '작업일', className: 'w-[100px]', copyable: true },
        { key: 'workOrderNo', label: '작업지시번호', className: 'min-w-[140px]', copyable: true },
        { key: 'processName', label: '공정', className: 'w-[80px]', copyable: true },
        { key: 'productName', label: '품목명', className: 'min-w-[180px]', copyable: true },
        { key: 'specification', label: '규격', className: 'w-[100px]', copyable: true },
        { key: 'productionQty', label: '생산수량', className: 'w-[80px] text-center', copyable: true },
        { key: 'goodQty', label: '양품수량', className: 'w-[80px] text-center', copyable: true },
        { key: 'defectQty', label: '불량수량', className: 'w-[80px] text-center', copyable: true },
        { key: 'defectRate', label: '불량률', className: 'w-[80px] text-center', copyable: true },
        { key: 'inspection', label: '검사', className: 'w-[60px] text-center' },
        { key: 'packaging', label: '포장', className: 'w-[60px] text-center' },
        { key: 'workerName', label: '작업자', className: 'w-[80px]', copyable: true },
      ],

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

      // 검색
      searchPlaceholder: '로트번호, 작업지시번호, 품목명 검색...',
      searchFilter: (item: WorkResult, search: string) => {
        const s = search.toLowerCase();
        return (
          item.lotNo?.toLowerCase().includes(s) ||
          item.workOrderNo?.toLowerCase().includes(s) ||
          item.productName?.toLowerCase().includes(s) ||
          false
        );
      },

      // 통계 카드
      stats,

      // 엑셀 다운로드 설정
      excelDownload: {
        columns: excelColumns,
        filename: '작업실적',
        sheetName: '작업실적',
        fetchAllUrl: '/api/proxy/work-results',
        fetchAllParams: ({ searchValue }) => {
          const params: Record<string, string> = {};
          if (searchValue) {
            params.q = searchValue;
          }
          return params;
        },
        mapResponse: mapWorkResultResponse,
      },

      // 테이블 행 렌더링
      renderTableRow: (
        item: WorkResult,
        index: number,
        globalIndex: number,
        handlers: SelectionHandlers & RowClickHandlers<WorkResult>
      ) => {
        return (
          <TableRow
            key={item.id}
            className={`cursor-pointer hover:bg-muted/50 ${handlers.isSelected ? 'bg-blue-50' : ''}`}
            onClick={() => handleView(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.lotNo}</TableCell>
            <TableCell>{item.workDate}</TableCell>
            <TableCell>{item.workOrderNo}</TableCell>
            <TableCell>
              <Badge variant="outline" className="text-xs">
                {item.processName}
              </Badge>
            </TableCell>
            <TableCell className="max-w-[200px] truncate">{item.productName}</TableCell>
            <TableCell>{item.specification}</TableCell>
            <TableCell className="text-center">{item.productionQty}</TableCell>
            <TableCell className="text-center">{item.goodQty}</TableCell>
            <TableCell className="text-center">
              <span className={item.defectQty > 0 ? 'text-red-600 font-medium' : ''}>
                {item.defectQty}
              </span>
            </TableCell>
            <TableCell className="text-center">
              <span className={item.defectRate > 0 ? 'text-red-600 font-medium' : ''}>
                {item.defectRate}%
              </span>
            </TableCell>
            <TableCell className="text-center">
              {item.inspection ? (
                <CheckCircle className="w-4 h-4 text-green-600 mx-auto" />
              ) : (
                <span className="text-muted-foreground">-</span>
              )}
            </TableCell>
            <TableCell className="text-center">
              {item.packaging ? (
                <CheckCircle className="w-4 h-4 text-green-600 mx-auto" />
              ) : (
                <span className="text-muted-foreground">-</span>
              )}
            </TableCell>
            <TableCell>{item.workerName}</TableCell>
          </TableRow>
        );
      },

      // 모바일 카드 렌더링
      renderMobileCard: (
        item: WorkResult,
        index: number,
        globalIndex: number,
        handlers: SelectionHandlers & RowClickHandlers<WorkResult>
      ) => {
        return (
          <ListMobileCard
            key={item.id}
            id={item.id}
            isSelected={handlers.isSelected}
            onToggleSelection={handlers.onToggle}
            onClick={() => handleView(item)}
            headerBadges={
              <>
                <Badge variant="outline" className="text-xs">
                  {globalIndex}
                </Badge>
                <Badge variant="outline" className="text-xs">
                  {item.lotNo}
                </Badge>
              </>
            }
            title={item.productName}
            statusBadge={
              <Badge variant="outline" className="text-xs">
                {item.processName}
              </Badge>
            }
            infoGrid={
              <div className="grid grid-cols-2 gap-x-4 gap-y-3">
                <InfoField label="작업일" value={item.workDate} />
                <InfoField label="작업지시번호" value={item.workOrderNo} />
                <InfoField label="규격" value={item.specification} />
                <InfoField label="작업자" value={item.workerName} />
                <InfoField label="생산수량" value={`${item.productionQty}개`} />
                <InfoField label="양품수량" value={`${item.goodQty}개`} />
                <InfoField
                  label="불량수량"
                  value={`${item.defectQty}개`}
                  className={item.defectQty > 0 ? 'text-red-600' : ''}
                />
                <InfoField
                  label="불량률"
                  value={`${item.defectRate}%`}
                  className={item.defectRate > 0 ? 'text-red-600' : ''}
                />
              </div>
            }
          />
        );
      },
    }),
    [stats, handleView, excelColumns, mapWorkResultResponse]
  );

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