'use client';

/**
 * 입고 목록 페이지
 * IntegratedListTemplateV2 패턴 적용
 */

import { useState, useMemo, useCallback } from 'react';
import { useRouter } from 'next/navigation';
import {
  Package,
  Truck,
  ClipboardCheck,
  Calendar,
  Eye,
} 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 { mockReceivingItems, mockStats, mockFilterTabs } from './mockData';
import { RECEIVING_STATUS_LABELS, RECEIVING_STATUS_STYLES } from './types';
import type { ReceivingItem, ReceivingStatus } from './types';

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

export function ReceivingList() {
  const router = useRouter();
  const [searchTerm, setSearchTerm] = useState('');
  const [selectedItems, setSelectedItems] = useState<Set<string>>(new Set());
  const [currentPage, setCurrentPage] = useState(1);
  const [activeFilter, setActiveFilter] = useState<'all' | 'receiving_pending' | 'completed'>('all');

  // 통계 카드
  const stats: StatCard[] = [
    {
      label: '입고대기',
      value: `${mockStats.receivingPendingCount}건`,
      icon: Package,
      iconColor: 'text-yellow-600',
    },
    {
      label: '배송중',
      value: `${mockStats.shippingCount}건`,
      icon: Truck,
      iconColor: 'text-blue-600',
    },
    {
      label: '검사대기',
      value: `${mockStats.inspectionPendingCount}건`,
      icon: ClipboardCheck,
      iconColor: 'text-orange-600',
    },
    {
      label: '금일입고',
      value: `${mockStats.todayReceivingCount}건`,
      icon: Calendar,
      iconColor: 'text-green-600',
    },
  ];

  // 테이블 컬럼
  const tableColumns: TableColumn[] = [
    { key: 'no', label: '번호', className: 'w-[60px] text-center' },
    { key: 'orderNo', label: '발주번호', className: 'min-w-[150px]' },
    { key: 'itemCode', label: '품목코드', className: 'min-w-[130px]' },
    { key: 'itemName', label: '품목명', className: 'min-w-[150px]' },
    { key: 'supplier', label: '공급업체', className: 'min-w-[100px]' },
    { key: 'orderQty', label: '발주수량', className: 'w-[100px] text-center' },
    { key: 'receivingQty', label: '입고수량', className: 'w-[100px] text-center' },
    { key: 'lotNo', label: 'LOT번호', className: 'w-[120px] text-center' },
    { key: 'status', label: '상태', className: 'w-[100px] text-center' },
  ];

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

    // 탭 필터
    if (activeFilter === 'receiving_pending') {
      result = result.filter((item) =>
        ['receiving_pending', 'inspection_pending'].includes(item.status)
      );
    } else if (activeFilter === 'completed') {
      result = result.filter((item) => item.status === 'completed');
    }

    // 검색 필터
    if (searchTerm) {
      const term = searchTerm.toLowerCase();
      result = result.filter(
        (item) =>
          item.orderNo.toLowerCase().includes(term) ||
          item.itemCode.toLowerCase().includes(term) ||
          item.itemName.toLowerCase().includes(term) ||
          item.supplier.toLowerCase().includes(term)
      );
    }

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

  // 페이지네이션 데이터
  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((item) => item.id)));
    }
  }, [paginatedData, selectedItems.size]);

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

  // 탭 변경 시 페이지 리셋
  const handleTabChange = (value: string) => {
    setActiveFilter(value as 'all' | 'receiving_pending' | 'completed');
    setCurrentPage(1);
    setSelectedItems(new Set());
  };

  // 상세 보기
  const handleView = useCallback(
    (id: string) => {
      router.push(`/ko/material/receiving-management/${id}`);
    },
    [router]
  );

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

    return (
      <TableRow
        key={item.id}
        className={`cursor-pointer hover:bg-muted/50 ${isSelected ? 'bg-blue-50' : ''}`}
        onClick={() => handleView(item.id)}
      >
        <TableCell className="text-center" onClick={(e) => e.stopPropagation()}>
          <Checkbox
            checked={isSelected}
            onCheckedChange={() => handleToggleSelection(item.id)}
          />
        </TableCell>
        <TableCell className="text-center text-muted-foreground">{globalIndex}</TableCell>
        <TableCell className="font-medium">{item.orderNo}</TableCell>
        <TableCell>{item.itemCode}</TableCell>
        <TableCell className="max-w-[150px] truncate">{item.itemName}</TableCell>
        <TableCell>{item.supplier}</TableCell>
        <TableCell className="text-center">
          {item.orderQty} {item.orderUnit}
        </TableCell>
        <TableCell className="text-center">
          {item.receivingQty !== undefined ? item.receivingQty : '-'}
        </TableCell>
        <TableCell className="text-center">{item.lotNo || '-'}</TableCell>
        <TableCell className="text-center">
          <Badge className={`text-xs ${RECEIVING_STATUS_STYLES[item.status]}`}>
            {RECEIVING_STATUS_LABELS[item.status]}
          </Badge>
        </TableCell>
      </TableRow>
    );
  };

  // 모바일 카드 렌더링
  const renderMobileCard = (
    item: ReceivingItem,
    index: number,
    globalIndex: number,
    isSelected: boolean,
    onToggle: () => void
  ) => {
    return (
      <ListMobileCard
        id={item.id}
        isSelected={isSelected}
        onToggleSelection={onToggle}
        onClick={() => handleView(item.id)}
        headerBadges={
          <>
            <Badge variant="outline" className="text-xs">
              #{globalIndex}
            </Badge>
            <Badge variant="outline" className="text-xs">
              {item.orderNo}
            </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.supplier} />
            <InfoField label="발주수량" value={`${item.orderQty} ${item.orderUnit}`} />
            <InfoField
              label="입고수량"
              value={item.receivingQty !== undefined ? `${item.receivingQty}` : '-'}
            />
            <InfoField label="LOT번호" value={item.lotNo || '-'} />
          </div>
        }
        actions={
          isSelected && (
            <div className="flex items-center gap-2">
              <Button
                variant="outline"
                size="sm"
                className="flex-1"
                onClick={(e) => {
                  e.stopPropagation();
                  handleView(item.id);
                }}
              >
                <Eye className="w-4 h-4 mr-1" />
                상세
              </Button>
            </div>
          )
        }
      />
    );
  };

  // 탭 옵션
  const tabs: TabOption[] = mockFilterTabs.map((tab) => ({
    value: tab.key,
    label: tab.label,
    count: tab.count,
  }));

  // 하단 요약
  const tableFooter = (
    <TableRow className="bg-gray-50 hover:bg-gray-50">
      <TableCell colSpan={tableColumns.length + 1} className="py-3">
        <span className="text-sm text-muted-foreground">
          총 {filteredResults.length}건 / 입고대기 {mockStats.receivingPendingCount}건 / 검사대기{' '}
          {mockStats.inspectionPendingCount}건
        </span>
      </TableCell>
    </TableRow>
  );

  return (
    <IntegratedListTemplateV2<ReceivingItem>
      title="입고 목록"
      icon={Package}
      stats={stats}
      searchValue={searchTerm}
      onSearchChange={handleSearchChange}
      searchPlaceholder="발주번호, 품목코드, 품목명, 공급업체 검색..."
      tabs={tabs}
      activeTab={activeFilter}
      onTabChange={handleTabChange}
      tableColumns={tableColumns}
      data={paginatedData}
      totalCount={filteredResults.length}
      allData={filteredResults}
      selectedItems={selectedItems}
      onToggleSelection={handleToggleSelection}
      onToggleSelectAll={handleToggleSelectAll}
      getItemId={(item) => item.id}
      renderTableRow={renderTableRow}
      renderMobileCard={renderMobileCard}
      pagination={pagination}
      tableFooter={tableFooter}
    />
  );
}