'use client';

/**
 * 작업실적 조회 목록 페이지
 * IntegratedListTemplateV2 패턴 적용
 */

import { useState, useMemo, useCallback } from 'react';
import {
  BarChart3,
  Package,
  CheckCircle2,
  XCircle,
  Percent,
  Download,
  CheckCircle,
} 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 {
  IntegratedListTemplateV2,
  TableColumn,
  StatCard,
} from '@/components/templates/IntegratedListTemplateV2';
import { ListMobileCard, InfoField } from '@/components/organisms/ListMobileCard';
import { mockWorkResults, mockStats } from './mockData';
import { PROCESS_TYPE_LABELS } from '../WorkOrders/types';
import type { WorkResult } from './types';

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

export function WorkResultList() {
  const [searchTerm, setSearchTerm] = useState('');
  const [selectedItems, setSelectedItems] = useState<Set<string>>(new Set());
  const [currentPage, setCurrentPage] = useState(1);

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

  // 테이블 컬럼
  const tableColumns: TableColumn[] = [
    { key: 'no', label: '번호', className: 'w-[60px] text-center' },
    { key: 'lotNo', label: '로트번호', className: 'min-w-[150px]' },
    { key: 'workDate', label: '작업일', className: 'w-[100px]' },
    { key: 'workOrderNo', label: '작업지시번호', className: 'min-w-[140px]' },
    { key: 'processType', label: '공정', className: 'w-[80px]' },
    { key: 'productName', label: '품목명', className: 'min-w-[180px]' },
    { key: 'specification', label: '규격', className: 'w-[100px]' },
    { key: 'productionQty', label: '생산수량', className: 'w-[80px] text-center' },
    { key: 'goodQty', label: '양품수량', className: 'w-[80px] text-center' },
    { key: 'defectQty', label: '불량수량', className: 'w-[80px] text-center' },
    { key: 'defectRate', label: '불량률', className: 'w-[80px] text-center' },
    { key: 'inspection', label: '검사', className: 'w-[60px] text-center' },
    { key: 'packaging', label: '포장', className: 'w-[60px] text-center' },
    { key: 'worker', label: '작업자', className: 'w-[80px]' },
  ];

  // 필터링된 데이터
  const filteredResults = useMemo(() => {
    let result = [...mockWorkResults];

    // 검색 필터
    if (searchTerm) {
      const term = searchTerm.toLowerCase();
      result = result.filter(
        (r) =>
          r.lotNo.toLowerCase().includes(term) ||
          r.workOrderNo.toLowerCase().includes(term) ||
          r.productName.toLowerCase().includes(term)
      );
    }

    return result;
  }, [searchTerm]);

  // 페이지네이션 데이터
  const paginatedData = useMemo(() => {
    const startIndex = (currentPage - 1) * ITEMS_PER_PAGE;
    return filteredResults.slice(startIndex, startIndex + ITEMS_PER_PAGE);
  }, [filteredResults, currentPage]);

  // 페이지네이션 설정
  const pagination = {
    currentPage,
    totalPages: Math.ceil(filteredResults.length / ITEMS_PER_PAGE),
    totalItems: filteredResults.length,
    itemsPerPage: ITEMS_PER_PAGE,
    onPageChange: setCurrentPage,
  };

  // 선택 핸들러
  const handleToggleSelection = useCallback((id: string) => {
    setSelectedItems((prev) => {
      const newSet = new Set(prev);
      if (newSet.has(id)) {
        newSet.delete(id);
      } else {
        newSet.add(id);
      }
      return newSet;
    });
  }, []);

  const handleToggleSelectAll = useCallback(() => {
    if (selectedItems.size === paginatedData.length) {
      setSelectedItems(new Set());
    } else {
      setSelectedItems(new Set(paginatedData.map((r) => r.id)));
    }
  }, [paginatedData, selectedItems.size]);

  // 검색 변경 시 페이지 리셋
  const handleSearchChange = (value: string) => {
    setSearchTerm(value);
    setCurrentPage(1);
  };

  // 엑셀 다운로드
  const handleExcelDownload = useCallback(() => {
    console.log('엑셀 다운로드:', filteredResults);
    // TODO: 엑셀 다운로드 기능 구현
  }, [filteredResults]);

  // 상세 보기
  const handleView = useCallback((id: string) => {
    console.log('상세 보기:', id);
    // TODO: 상세 보기 기능 구현
  }, []);

  // 테이블 행 렌더링
  const renderTableRow = (result: WorkResult, index: number, globalIndex: number) => {
    const isSelected = selectedItems.has(result.id);

    return (
      <TableRow
        key={result.id}
        className={`cursor-pointer hover:bg-muted/50 ${isSelected ? 'bg-blue-50' : ''}`}
        onClick={() => handleView(result.id)}
      >
        <TableCell className="text-center" onClick={(e) => e.stopPropagation()}>
          <Checkbox
            checked={isSelected}
            onCheckedChange={() => handleToggleSelection(result.id)}
          />
        </TableCell>
        <TableCell className="text-center text-muted-foreground">{globalIndex}</TableCell>
        <TableCell className="font-medium">{result.lotNo}</TableCell>
        <TableCell>{result.workDate}</TableCell>
        <TableCell>{result.workOrderNo}</TableCell>
        <TableCell>
          <Badge variant="outline" className="text-xs">
            {PROCESS_TYPE_LABELS[result.processType]}
          </Badge>
        </TableCell>
        <TableCell className="max-w-[200px] truncate">{result.productName}</TableCell>
        <TableCell>{result.specification}</TableCell>
        <TableCell className="text-center">{result.productionQty}</TableCell>
        <TableCell className="text-center">{result.goodQty}</TableCell>
        <TableCell className="text-center">
          <span className={result.defectQty > 0 ? 'text-red-600 font-medium' : ''}>
            {result.defectQty}
          </span>
        </TableCell>
        <TableCell className="text-center">
          <span className={result.defectRate > 0 ? 'text-red-600 font-medium' : ''}>
            {result.defectRate}%
          </span>
        </TableCell>
        <TableCell className="text-center">
          {result.inspection ? (
            <CheckCircle className="w-4 h-4 text-green-600 mx-auto" />
          ) : (
            <span className="text-muted-foreground">-</span>
          )}
        </TableCell>
        <TableCell className="text-center">
          {result.packaging ? (
            <CheckCircle className="w-4 h-4 text-green-600 mx-auto" />
          ) : (
            <span className="text-muted-foreground">-</span>
          )}
        </TableCell>
        <TableCell>{result.worker}</TableCell>
      </TableRow>
    );
  };

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

  // 헤더 액션
  const headerActions = (
    <Button variant="outline" onClick={handleExcelDownload}>
      <Download className="w-4 h-4 mr-1.5" />
      엑셀 다운로드
    </Button>
  );

  return (
    <IntegratedListTemplateV2<WorkResult>
      title="작업실적 조회"
      icon={BarChart3}
      headerActions={headerActions}
      stats={stats}
      searchValue={searchTerm}
      onSearchChange={handleSearchChange}
      searchPlaceholder="로트번호, 작업지시번호, 품목명 검색..."
      tableColumns={tableColumns}
      data={paginatedData}
      totalCount={filteredResults.length}
      allData={filteredResults}
      selectedItems={selectedItems}
      onToggleSelection={handleToggleSelection}
      onToggleSelectAll={handleToggleSelectAll}
      getItemId={(result) => result.id}
      renderTableRow={renderTableRow}
      renderMobileCard={renderMobileCard}
      pagination={pagination}
    />
  );
}