'use client';

/**
 * 검사 목록 페이지
 * IntegratedListTemplateV2 패턴 적용
 */

import { useState, useMemo, useCallback } from 'react';
import { useRouter } from 'next/navigation';
import { Plus, ClipboardCheck, Clock, PlayCircle, CheckCircle2, AlertTriangle } 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,
  TabOption,
  TableColumn,
  StatCard,
} from '@/components/templates/IntegratedListTemplateV2';
import { ListMobileCard, InfoField } from '@/components/organisms/ListMobileCard';
import { mockInspections, mockStats, statusColorMap, inspectionTypeLabels } from './mockData';
import type { Inspection, InspectionStatus } from './types';

// 탭 필터 정의
type TabFilter = '전체' | InspectionStatus;

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

export function InspectionList() {
  const router = useRouter();
  const [searchTerm, setSearchTerm] = useState('');
  const [activeTab, setActiveTab] = useState<TabFilter>('전체');
  const [selectedItems, setSelectedItems] = useState<Set<string>>(new Set());
  const [currentPage, setCurrentPage] = useState(1);

  // 탭별 카운트 계산
  const tabCounts = useMemo(() => {
    return {
      전체: mockInspections.length,
      대기: mockInspections.filter((i) => i.status === '대기').length,
      진행중: mockInspections.filter((i) => i.status === '진행중').length,
      완료: mockInspections.filter((i) => i.status === '완료').length,
    };
  }, []);

  // 탭 옵션
  const tabs: TabOption[] = [
    { value: '전체', label: '전체', count: tabCounts.전체 },
    { value: '대기', label: '대기', count: tabCounts.대기, color: 'gray' },
    { value: '진행중', label: '진행중', count: tabCounts.진행중, color: 'blue' },
    { value: '완료', label: '완료', count: tabCounts.완료, color: 'green' },
  ];

  // 통계 카드
  const stats: StatCard[] = [
    {
      label: '금일 대기 건수',
      value: `${mockStats.waitingCount}건`,
      icon: Clock,
      iconColor: 'text-gray-600',
    },
    {
      label: '진행 중 검사',
      value: `${mockStats.inProgressCount}건`,
      icon: PlayCircle,
      iconColor: 'text-blue-600',
    },
    {
      label: '금일 완료 건수',
      value: `${mockStats.completedCount}건`,
      icon: CheckCircle2,
      iconColor: 'text-green-600',
    },
    {
      label: '불량 발생률',
      value: `${mockStats.defectRate}%`,
      icon: AlertTriangle,
      iconColor: mockStats.defectRate > 0 ? 'text-red-600' : 'text-gray-400',
    },
  ];

  // 테이블 컬럼
  const tableColumns: TableColumn[] = [
    { key: 'no', label: '번호', className: 'w-[60px] text-center' },
    { key: 'inspectionType', label: '검사유형', className: 'w-[80px]' },
    { key: 'requestDate', label: '요청일', className: 'w-[100px]' },
    { key: 'itemName', label: '품목명', className: 'min-w-[150px]' },
    { key: 'lotNo', label: 'LOT NO', className: 'min-w-[130px]' },
    { key: 'status', label: '상태', className: 'w-[80px]' },
    { key: 'inspector', label: '담당자', className: 'w-[80px]' },
  ];

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

    // 탭 필터
    if (activeTab !== '전체') {
      result = result.filter((i) => i.status === activeTab);
    }

    // 검색 필터
    if (searchTerm) {
      const term = searchTerm.toLowerCase();
      result = result.filter(
        (i) =>
          i.lotNo.toLowerCase().includes(term) ||
          i.itemName.toLowerCase().includes(term) ||
          i.processName.toLowerCase().includes(term)
      );
    }

    return result;
  }, [activeTab, searchTerm]);

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

  // 페이지네이션 설정
  const pagination = {
    currentPage,
    totalPages: Math.ceil(filteredInspections.length / ITEMS_PER_PAGE),
    totalItems: filteredInspections.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((i) => i.id)));
    }
  }, [paginatedData, selectedItems.size]);

  // 상세 페이지 이동
  const handleView = useCallback((id: string) => {
    router.push(`/quality/inspections/${id}`);
  }, [router]);

  // 등록 페이지 이동
  const handleCreate = () => {
    router.push('/quality/inspections/new');
  };

  // 탭 변경 시 페이지 리셋
  const handleTabChange = (value: string) => {
    setActiveTab(value as TabFilter);
    setCurrentPage(1);
    setSelectedItems(new Set());
  };

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

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

    return (
      <TableRow
        key={inspection.id}
        className={`cursor-pointer hover:bg-muted/50 ${isSelected ? 'bg-blue-50' : ''}`}
        onClick={() => handleView(inspection.id)}
      >
        <TableCell className="text-center" onClick={(e) => e.stopPropagation()}>
          <Checkbox
            checked={isSelected}
            onCheckedChange={() => handleToggleSelection(inspection.id)}
          />
        </TableCell>
        <TableCell className="text-center text-muted-foreground">{globalIndex}</TableCell>
        <TableCell>
          <Badge variant="outline" className="text-xs">
            {inspection.inspectionType}
          </Badge>
        </TableCell>
        <TableCell>{inspection.requestDate}</TableCell>
        <TableCell className="font-medium">{inspection.itemName}</TableCell>
        <TableCell>{inspection.lotNo}</TableCell>
        <TableCell>
          <Badge className={`${statusColorMap[inspection.status]} border-0`}>
            {inspection.status}
          </Badge>
        </TableCell>
        <TableCell>{inspection.inspector || '-'}</TableCell>
      </TableRow>
    );
  };

  // 모바일 카드 렌더링
  const renderMobileCard = (
    inspection: Inspection,
    index: number,
    globalIndex: number,
    isSelected: boolean,
    onToggle: () => void
  ) => {
    return (
      <ListMobileCard
        id={inspection.id}
        isSelected={isSelected}
        onToggleSelection={onToggle}
        onClick={() => handleView(inspection.id)}
        headerBadges={
          <>
            <Badge variant="outline" className="text-xs">#{globalIndex}</Badge>
            <Badge variant="outline" className="text-xs">{inspection.inspectionType}</Badge>
          </>
        }
        title={inspection.itemName}
        statusBadge={
          <Badge className={`${statusColorMap[inspection.status]} border-0`}>
            {inspection.status}
          </Badge>
        }
        infoGrid={
          <div className="grid grid-cols-2 gap-x-4 gap-y-3">
            <InfoField label="검사유형" value={inspectionTypeLabels[inspection.inspectionType]} />
            <InfoField label="LOT NO" value={inspection.lotNo} />
            <InfoField label="요청일" value={inspection.requestDate} />
            <InfoField label="담당자" value={inspection.inspector || '-'} />
            <InfoField label="공정명" value={inspection.processName} />
            <InfoField label="수량" value={`${inspection.quantity} ${inspection.unit}`} />
          </div>
        }
      />
    );
  };

  // 헤더 액션
  const headerActions = (
    <Button className="ml-auto" onClick={handleCreate}>
      <Plus className="w-4 h-4 mr-1.5" />
      검사 등록
    </Button>
  );

  return (
    <IntegratedListTemplateV2<Inspection>
      title="검사 목록"
      description="품질검사 관리"
      icon={ClipboardCheck}
      headerActions={headerActions}
      stats={stats}
      searchValue={searchTerm}
      onSearchChange={handleSearchChange}
      searchPlaceholder="LOT번호, 품목명, 공정명 검색..."
      tabs={tabs}
      activeTab={activeTab}
      onTabChange={handleTabChange}
      tableColumns={tableColumns}
      data={paginatedData}
      totalCount={filteredInspections.length}
      allData={filteredInspections}
      selectedItems={selectedItems}
      onToggleSelection={handleToggleSelection}
      onToggleSelectAll={handleToggleSelectAll}
      getItemId={(inspection) => inspection.id}
      renderTableRow={renderTableRow}
      renderMobileCard={renderMobileCard}
      pagination={pagination}
    />
  );
}