'use client';

/**
 * 출하 목록 페이지
 * IntegratedListTemplateV2 패턴 적용
 */

import { useState, useMemo, useCallback } from 'react';
import { useRouter } from 'next/navigation';
import {
  Truck,
  Package,
  Clock,
  AlertTriangle,
  Eye,
  Plus,
  Check,
  X,
} 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 { Alert, AlertDescription } from '@/components/ui/alert';
import {
  IntegratedListTemplateV2,
  TabOption,
  TableColumn,
  StatCard,
} from '@/components/templates/IntegratedListTemplateV2';
import { ListMobileCard, InfoField } from '@/components/organisms/ListMobileCard';
import { mockShipmentItems, mockStats, mockFilterTabs } from './mockData';
import {
  SHIPMENT_STATUS_LABELS,
  SHIPMENT_STATUS_STYLES,
  PRIORITY_LABELS,
  PRIORITY_STYLES,
  DELIVERY_METHOD_LABELS,
} from './types';
import type { ShipmentItem, ShipmentStatus } from './types';

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

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

  // 출고 불가 건수 계산
  const cannotShipCount = useMemo(() => {
    return mockShipmentItems.filter(item => !item.canShip).length;
  }, []);

  // 통계 카드
  const stats: StatCard[] = [
    {
      label: '당일 출하',
      value: `${mockStats.todayShipmentCount}건`,
      icon: Package,
      iconColor: 'text-green-600',
    },
    {
      label: '출고 대기',
      value: `${mockStats.scheduledCount}건`,
      icon: Clock,
      iconColor: 'text-yellow-600',
    },
    {
      label: '배송중',
      value: `${mockStats.shippingCount}건`,
      icon: Truck,
      iconColor: 'text-blue-600',
    },
    {
      label: '긴급 출하',
      value: `${mockStats.urgentCount}건`,
      icon: AlertTriangle,
      iconColor: 'text-red-600',
    },
  ];

  // 테이블 컬럼
  const tableColumns: TableColumn[] = [
    { key: 'no', label: '번호', className: 'w-[60px] text-center' },
    { key: 'shipmentNo', label: '출고번호', className: 'min-w-[130px]' },
    { key: 'lotNo', label: '로트번호', className: 'min-w-[150px]' },
    { key: 'scheduledDate', label: '출고예정일', className: 'w-[120px] text-center' },
    { key: 'status', label: '상태', className: 'w-[100px] text-center' },
    { key: 'canShip', label: '출하가능', className: 'w-[80px] text-center' },
    { key: 'deliveryMethod', label: '배송', className: 'w-[100px] text-center' },
    { key: 'customerName', label: '발주처', className: 'min-w-[120px]' },
    { key: 'siteName', label: '현장명', className: 'min-w-[120px]' },
    { key: 'manager', label: '담당', className: 'w-[80px] text-center' },
    { key: 'deliveryTime', label: '납기(수배시간)', className: 'w-[120px] text-center' },
  ];

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

    // 탭 필터
    if (activeFilter !== 'all' && activeFilter !== 'calendar') {
      result = result.filter((item) => item.status === activeFilter);
    }

    // 검색 필터
    if (searchTerm) {
      const term = searchTerm.toLowerCase();
      result = result.filter(
        (item) =>
          item.shipmentNo.toLowerCase().includes(term) ||
          item.lotNo.toLowerCase().includes(term) ||
          item.customerName.toLowerCase().includes(term) ||
          item.siteName.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);
    setCurrentPage(1);
    setSelectedItems(new Set());
  };

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

  // 등록 페이지로 이동
  const handleCreate = () => {
    router.push('/ko/outbound/shipments/new');
  };

  // 테이블 행 렌더링
  const renderTableRow = (item: ShipmentItem, 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.shipmentNo}</TableCell>
        <TableCell>{item.lotNo}</TableCell>
        <TableCell className="text-center">{item.scheduledDate}</TableCell>
        <TableCell className="text-center">
          <Badge className={`text-xs ${SHIPMENT_STATUS_STYLES[item.status]}`}>
            {SHIPMENT_STATUS_LABELS[item.status]}
          </Badge>
        </TableCell>
        <TableCell className="text-center">
          {item.canShip ? (
            <Check className="w-4 h-4 mx-auto text-green-600" />
          ) : (
            <X className="w-4 h-4 mx-auto text-red-600" />
          )}
        </TableCell>
        <TableCell className="text-center">{DELIVERY_METHOD_LABELS[item.deliveryMethod]}</TableCell>
        <TableCell>{item.customerName}</TableCell>
        <TableCell className="max-w-[120px] truncate">{item.siteName}</TableCell>
        <TableCell className="text-center">{item.manager || '-'}</TableCell>
        <TableCell className="text-center">{item.deliveryTime || '-'}</TableCell>
      </TableRow>
    );
  };

  // 모바일 카드 렌더링
  const renderMobileCard = (
    item: ShipmentItem,
    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.shipmentNo}
            </Badge>
          </>
        }
        title={item.siteName}
        statusBadge={
          <Badge className={`text-xs ${SHIPMENT_STATUS_STYLES[item.status]}`}>
            {SHIPMENT_STATUS_LABELS[item.status]}
          </Badge>
        }
        infoGrid={
          <div className="grid grid-cols-2 gap-x-4 gap-y-3">
            <InfoField label="로트번호" value={item.lotNo} />
            <InfoField label="발주처" value={item.customerName} />
            <InfoField label="출고예정일" value={item.scheduledDate} />
            <InfoField label="배송방식" value={DELIVERY_METHOD_LABELS[item.deliveryMethod]} />
            <InfoField label="출하가능" value={item.canShip ? '가능' : '불가'} />
          </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 headerActions = (
    <Button className="ml-auto" onClick={handleCreate}>
      <Plus className="w-4 h-4 mr-2" />
      출하 등록
    </Button>
  );

  // 카드와 검색 영역 사이에 표시할 경고 알림
  const alertBanner = cannotShipCount > 0 && (
    <Alert className="mb-4 bg-orange-50 border-orange-200">
      <AlertTriangle className="h-4 w-4 text-orange-600" />
      <AlertDescription className="text-orange-800">
        출고불가 {cannotShipCount}건 - 입금확인 및 세금계산서 발행 완료 후 출고 진행이 가능합니다.
      </AlertDescription>
    </Alert>
  );

  return (
    <IntegratedListTemplateV2<ShipmentItem>
      title="출하 목록"
      icon={Truck}
      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}
      headerActions={headerActions}
      alertBanner={alertBanner}
    />
  );
}