/**
 * 품목관리 - IntegratedListTemplateV2 적용 예제
 * 
 * 기준정보 -> 디자인시스템관리 -> 템플릿의 IntegratedListTemplateV2를 적용한 품목 관리 페이지입니다.
 * - PageHeader, StatCards, SearchFilter, 체크박스
 * - 데스크톱: TabsList + DataTable
 * - 모바일: 커스텀 버튼 탭 + 카드
 * - 페이지네이션
 * 
 * 이 파일은 ItemManagement.tsx의 목록 뷰만을 IntegratedListTemplateV2로 구현한 예제입니다.
 */

import { useState, useMemo } from "react";
import { Package, Edit, Trash2, Search } from "lucide-react";
import { Button } from "./ui/button";
import { Badge } from "./ui/badge";
import { Checkbox } from "./ui/checkbox";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "./ui/select";
import { TableRow, TableCell } from "./ui/table";
import { IntegratedListTemplateV2, TabOption, TableColumn } from "./templates/IntegratedListTemplateV2";
import { ListActions } from "./organisms/ListActions";
import { TableActionButtons } from "./organisms/TableActionButtons";
import { useData, ItemMaster } from "./contexts/DataContext";
import { toast } from "sonner@2.0.3";
import { useVersionControl } from "./VersionControl";
import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle } from "./ui/alert-dialog";

export function ItemManagement_IntegratedListV2() {
  const { itemMasters, deleteItemMaster } = useData();

  // 버전 관리 Hook
  const { screenVersion } = useVersionControl("품목관리", "/components/ItemManagement_IntegratedListV2.tsx");

  const [searchTerm, setSearchTerm] = useState("");
  const [filterType, setFilterType] = useState<string>("all");
  const [currentPage, setCurrentPage] = useState(1);
  const [selectedItems, setSelectedItems] = useState<Set<string>>(new Set());
  const [isDeleteDialogOpen, setIsDeleteDialogOpen] = useState(false);
  const [itemToDelete, setItemToDelete] = useState<ItemMaster | null>(null);
  const [isBulkDeleteDialogOpen, setIsBulkDeleteDialogOpen] = useState(false);

  const itemsPerPage = 20;

  // 품목 코드 포맷팅 (조립 부품용)
  const formatItemCodeForAssembly = (item: ItemMaster): string => {
    if (item.itemType !== 'PT' || (item as any).partType !== 'ASSEMBLY') {
      return item.itemCode;
    }
    
    const installationType = (item as any).installationType;
    const itemName = (item as any).itemName || '';
    
    let typePrefix = '';
    if (installationType === 'wall') typePrefix = 'R';
    else if (installationType === 'side') typePrefix = 'S';
    else if (installationType === 'standard') typePrefix = 'C';
    else if (installationType === 'steel') typePrefix = 'B';
    else if (installationType === 'iron') typePrefix = 'T';
    
    const widthMatch = itemName.match(/W(\d+)/);
    const heightMatch = itemName.match(/H(\d+)/);
    const width = widthMatch ? widthMatch[1] : '';
    const height = heightMatch ? heightMatch[1] : '';
    
    if (width && height) {
      return `${typePrefix}${width}${height}`;
    }
    
    return item.itemCode;
  };

  // 품목 유형 뱃지
  const getItemTypeBadge = (type?: string) => {
    switch (type) {
      case "FG":
        return <Badge variant="outline" className="bg-purple-50 text-purple-700 border-purple-200">제품</Badge>;
      case "PT":
        return <Badge variant="outline" className="bg-orange-50 text-orange-700 border-orange-200">부품</Badge>;
      case "SM":
        return <Badge variant="outline" className="bg-green-50 text-green-700 border-green-200">부자재</Badge>;
      case "RM":
        return <Badge variant="outline" className="bg-blue-50 text-blue-700 border-blue-200">원자재</Badge>;
      case "CS":
        return <Badge variant="outline" className="bg-gray-50 dark:bg-gray-800 text-gray-700 dark:text-gray-300 border-gray-200 dark:border-gray-700">소모품</Badge>;
      default:
        return <Badge variant="outline">-</Badge>;
    }
  };

  // 필터링된 데이터
  const filteredItems = useMemo(() => {
    let filtered = itemMasters;

    // 유형 필터
    if (filterType !== "all") {
      filtered = filtered.filter(item => item.itemType === filterType);
    }

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

    return filtered;
  }, [itemMasters, filterType, searchTerm]);

  // 통계 데이터
  const stats = [
    {
      label: "전체 품목",
      value: itemMasters.length,
      icon: Package,
      iconColor: "text-blue-600"
    },
    {
      label: "제품",
      value: itemMasters.filter((i) => i.itemType === "FG").length,
      icon: Package,
      iconColor: "text-purple-600"
    },
    {
      label: "부품",
      value: itemMasters.filter((i) => i.itemType === "PT").length,
      icon: Package,
      iconColor: "text-orange-600"
    },
    {
      label: "부자재",
      value: itemMasters.filter((i) => i.itemType === "SM").length,
      icon: Package,
      iconColor: "text-green-600"
    },
    {
      label: "원자재",
      value: itemMasters.filter((i) => i.itemType === "RM").length,
      icon: Package,
      iconColor: "text-cyan-600"
    },
    {
      label: "소모품",
      value: itemMasters.filter((i) => i.itemType === "CS").length,
      icon: Package,
      iconColor: "text-gray-600"
    }
  ];

  // 탭 옵션
  const tabs: TabOption[] = [
    { value: "all", label: "전체", count: itemMasters.length },
    { value: "FG", label: "제품", count: itemMasters.filter(i => i.itemType === 'FG').length, color: "purple" },
    { value: "PT", label: "부품", count: itemMasters.filter(i => i.itemType === 'PT').length, color: "orange" },
    { value: "SM", label: "부자재", count: itemMasters.filter(i => i.itemType === 'SM').length, color: "cyan" },
    { value: "RM", label: "원자재", count: itemMasters.filter(i => i.itemType === 'RM').length, color: "green" },
    { value: "CS", label: "소모품", count: itemMasters.filter(i => i.itemType === 'CS').length, color: "gray" },
  ];

  // 테이블 컬럼
  const tableColumns: TableColumn[] = [
    { key: "no", label: "번호", className: "px-4", hideOnMobile: true },
    { key: "itemCode", label: "품목코드", className: "px-4" },
    { key: "itemType", label: "품목유형", className: "px-4" },
    { key: "itemName", label: "품목명", className: "px-4" },
    { key: "specification", label: "규격", className: "px-4", hideOnMobile: true },
    { key: "unit", label: "단위", className: "px-4", hideOnMobile: true },
    { key: "status", label: "품목 상태", className: "px-4", hideOnTablet: true },
    { key: "actions", label: "작업", className: "px-4 text-right" },
  ];

  // 페이지네이션 계산
  const totalPages = Math.ceil(filteredItems.length / itemsPerPage);
  const startIndex = (currentPage - 1) * itemsPerPage;
  const endIndex = startIndex + itemsPerPage;
  const paginatedItems = filteredItems.slice(startIndex, endIndex);

  // 체크박스 토글
  const toggleItemSelection = (id: string) => {
    const newSelected = new Set(selectedItems);
    if (newSelected.has(id)) {
      newSelected.delete(id);
    } else {
      newSelected.add(id);
    }
    setSelectedItems(newSelected);
  };

  const toggleSelectAll = () => {
    if (selectedItems.size === filteredItems.length && filteredItems.length > 0) {
      setSelectedItems(new Set());
    } else {
      setSelectedItems(new Set(filteredItems.map(item => item.id)));
    }
  };

  // 삭제 처리
  const handleDelete = (item: ItemMaster) => {
    setItemToDelete(item);
    setIsDeleteDialogOpen(true);
  };

  const confirmDelete = () => {
    if (itemToDelete) {
      deleteItemMaster(itemToDelete.id);
      toast.success(`품목 "${itemToDelete.itemName}"이(가) 삭제되었습니다.`);
      setItemToDelete(null);
      setIsDeleteDialogOpen(false);
    }
  };

  const confirmBulkDelete = () => {
    selectedItems.forEach(id => {
      deleteItemMaster(id);
    });
    toast.success(`${selectedItems.size}개 품목이 삭제되었습니다.`);
    setSelectedItems(new Set());
    setIsBulkDeleteDialogOpen(false);
  };

  // 테이블 행 렌더링
  const renderTableRow = (item: ItemMaster, index: number, globalIndex: number) => (
    <TableRow key={item.id} className="hover:bg-muted/50 h-14">
      <TableCell onClick={(e) => e.stopPropagation()}>
        <Checkbox
          checked={selectedItems.has(item.id)}
          onCheckedChange={() => toggleItemSelection(item.id)}
        />
      </TableCell>
      <TableCell className="text-muted-foreground hidden md:table-cell">
        {filteredItems.length - (startIndex + index)}
      </TableCell>
      <TableCell>
        <code className="text-xs bg-gray-100 dark:bg-gray-800 px-2 py-1 rounded">
          {formatItemCodeForAssembly(item) || '-'}
        </code>
      </TableCell>
      <TableCell>
        {getItemTypeBadge(item.itemType)}
        {item.itemType === 'PT' && (item as any).partType && (
          <Badge variant="outline" className="ml-1 bg-purple-50 text-purple-700 text-xs hidden lg:inline-flex">
            {(item as any).partType === 'ASSEMBLY' ? '조립' :
             (item as any).partType === 'BENDING' ? '절곡' :
             (item as any).partType === 'PURCHASED' ? '구매' : ''}
          </Badge>
        )}
      </TableCell>
      <TableCell>
        <div className="flex items-center gap-2">
          <span className="truncate max-w-[150px] md:max-w-none">{item.itemName}</span>
          {item.itemCode.includes('샘플') && (
            <Badge variant="outline" className="bg-green-50 text-green-700 text-xs hidden lg:inline-flex">
              견적산출용
            </Badge>
          )}
        </div>
      </TableCell>
      <TableCell className="text-sm text-muted-foreground hidden md:table-cell">
        {item.specification || "-"}
      </TableCell>
      <TableCell className="hidden md:table-cell">
        <Badge variant="secondary">{item.unit || "-"}</Badge>
      </TableCell>
      <TableCell className="hidden lg:table-cell">
        {item.status === 'active' && (
          <Badge variant="outline" className="bg-green-50 text-green-700 text-xs">사용중</Badge>
        )}
        {item.status === 'inactive' && (
          <Badge variant="outline" className="bg-gray-50 text-gray-700 text-xs">미사용</Badge>
        )}
        {item.status === 'development' && (
          <Badge variant="outline" className="bg-blue-50 text-blue-700 text-xs">개발중</Badge>
        )}
        {item.status === 'discontinued' && (
          <Badge variant="outline" className="bg-red-50 text-red-700 text-xs">폐기</Badge>
        )}
        {!item.status && (
          <Badge variant="outline" className="bg-green-50 text-green-700 text-xs">사용중</Badge>
        )}
      </TableCell>
      {selectedItems.has(item.id) && (
        <TableCell className="text-right" onClick={(e) => e.stopPropagation()}>
          <TableActionButtons
            onView={() => toast.info("상세 보기 기능은 ItemManagement.tsx에 구현되어 있습니다.")}
            onEdit={() => toast.info("수정 기능은 ItemManagement.tsx에 구현되어 있습니다.")}
            onDelete={() => handleDelete(item)}
          />
        </TableCell>
      )}
    </TableRow>
  );

  // 모바일 카드 렌더링
  const renderMobileCard = (item: ItemMaster, index: number, globalIndex: number, isSelected: boolean, onToggle: () => void) => (
    <div className="border rounded-lg p-4 space-y-3 bg-white dark:bg-card hover:bg-muted/50 transition-colors shadow-sm">
      {/* 번호와 체크박스 */}
      <div className="flex items-start gap-3">
        <Checkbox
          checked={isSelected}
          onCheckedChange={onToggle}
          onClick={(e) => e.stopPropagation()}
          className="mt-1"
        />
        <div className="flex-1 min-w-0 space-y-3">
          {/* 번호 + 품목코드 */}
          <div className="flex items-center gap-2 flex-wrap">
            <Badge variant="outline" className="bg-gray-100 dark:bg-gray-800 text-gray-700 dark:text-gray-300 font-mono text-xs">
              #{filteredItems.length - (startIndex + index)}
            </Badge>
            <code className="text-xs bg-blue-50 dark:bg-blue-900 text-blue-700 dark:text-blue-300 px-2 py-1 rounded font-mono">
              {formatItemCodeForAssembly(item) || item.itemCode}
            </code>
          </div>
          
          {/* 품목명 */}
          <div className="font-semibold text-base">
            {item.itemName}
          </div>

          {/* 품목 유형 */}
          <div>
            <span className="text-muted-foreground text-xs">품목유형</span>
            <div className="mt-1 flex items-center gap-2 flex-wrap">
              {getItemTypeBadge(item.itemType)}
              {item.itemType === 'PT' && (item as any).partType && (
                <Badge variant="outline" className="text-xs">
                  {(item as any).partType === 'ASSEMBLY' ? '조립' :
                   (item as any).partType === 'BENDING' ? '절곡' :
                   (item as any).partType === 'PURCHASED' ? '구매' : ''}
                </Badge>
              )}
            </div>
          </div>

          {/* 규격 정보 */}
          <div>
            <span className="text-muted-foreground text-xs">규격</span>
            <div className="font-medium mt-1">
              {item.specification || '-'}
            </div>
          </div>

          {/* 단위 정보 */}
          {item.unit && (
            <div>
              <span className="text-muted-foreground text-xs">단위</span>
              <div className="mt-1">
                <Badge variant="secondary" className="text-xs">{item.unit}</Badge>
              </div>
            </div>
          )}

          {/* 버전 및 상태 정보 */}
          <div className="flex items-center gap-2 flex-wrap">
            <Badge variant="outline" className="bg-purple-50 dark:bg-purple-900 text-purple-700 dark:text-purple-300 text-xs">
              V{(item as any).currentRevision || 0}
            </Badge>
            {item.status && (
              <Badge variant="outline" className="text-xs">
                {item.status === 'active' ? '사용중' :
                 item.status === 'development' ? '개발중' :
                 item.status === 'inactive' ? '미사용' : 
                 item.status === 'discontinued' ? '폐기' : item.status}
              </Badge>
            )}
          </div>
        </div>
      </div>

      {/* 액션 버튼 */}
      <div className="flex items-center justify-end gap-1 pt-3 border-t">
        <Button
          variant="ghost"
          size="sm"
          onClick={() => toast.info("상세 보기 기능은 ItemManagement.tsx에 구현되어 있습니다.")}
          className="h-9 px-3 flex-1 max-w-[100px]"
        >
          <Search className="h-4 w-4 mr-1.5" />
          <span className="text-sm">상세</span>
        </Button>
        <Button
          variant="ghost"
          size="sm"
          onClick={() => toast.info("수정 기능은 ItemManagement.tsx에 구현되어 있습니다.")}
          className="h-9 px-3 flex-1 max-w-[100px]"
        >
          <Edit className="h-4 w-4 mr-1.5" />
          <span className="text-sm">수정</span>
        </Button>
        <Button
          variant="ghost"
          size="sm"
          onClick={() => handleDelete(item)}
          className="h-9 px-3"
        >
          <Trash2 className="h-4 w-4 text-red-600" />
        </Button>
      </div>
    </div>
  );

  return (
    <>
      <IntegratedListTemplateV2
        title="품목 관리"
        description="제품, 부품, 부자재, 원자재, 소모품 등록 및 관리"
        icon={Package}
        headerActions={
          <ListActions
            onAdd={() => toast.info("등록 기능은 ItemManagement.tsx에 구현되어 있습니다.")}
            addText="품목 등록"
            selectedCount={selectedItems.size}
            onBulkDelete={() => setIsBulkDeleteDialogOpen(true)}
          />
        }
        stats={stats}
        versionHistory={screenVersion.versionHistory}
        versionHistoryTitle="품목 관리 수정 이력"
        searchValue={searchTerm}
        onSearchChange={setSearchTerm}
        searchPlaceholder="품목코드, 품목명, 규격 검색..."
        extraFilters={
          <Select value={filterType} onValueChange={setFilterType}>
            <SelectTrigger className="w-[180px]">
              <SelectValue placeholder="품목 유형" />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="all">전체 ({itemMasters.length})</SelectItem>
              <SelectItem value="FG">제품 ({itemMasters.filter(i => i.itemType === 'FG').length})</SelectItem>
              <SelectItem value="PT">부품 ({itemMasters.filter(i => i.itemType === 'PT').length})</SelectItem>
              <SelectItem value="SM">부자재 ({itemMasters.filter(i => i.itemType === 'SM').length})</SelectItem>
              <SelectItem value="RM">원자재 ({itemMasters.filter(i => i.itemType === 'RM').length})</SelectItem>
              <SelectItem value="CS">소모품 ({itemMasters.filter(i => i.itemType === 'CS').length})</SelectItem>
            </SelectContent>
          </Select>
        }
        tabs={tabs}
        activeTab={filterType}
        onTabChange={setFilterType}
        tableColumns={tableColumns}
        tableTitle={`${tabs.find(t => t.value === filterType)?.label || '전체'} 목록 (${filteredItems.length}개)`}
        data={paginatedItems}
        selectedItems={selectedItems}
        onToggleSelection={toggleItemSelection}
        onToggleSelectAll={toggleSelectAll}
        getItemId={(item) => item.id}
        renderTableRow={renderTableRow}
        renderMobileCard={renderMobileCard}
        pagination={{
          currentPage,
          totalPages,
          totalItems: filteredItems.length,
          itemsPerPage,
          onPageChange: setCurrentPage,
        }}
        devMetadata={{
          componentName: '품목관리 - IntegratedListTemplateV2',
          pagePath: '/components/ItemManagement_IntegratedListV2.tsx',
          description: 'IntegratedListTemplateV2를 사용한 품목 관리 목록 페이지',
        }}
      />

      {/* 삭제 확인 다이얼로그 */}
      <AlertDialog open={isDeleteDialogOpen} onOpenChange={setIsDeleteDialogOpen}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>품목 삭제</AlertDialogTitle>
            <AlertDialogDescription>
              {itemToDelete && (
                <>
                  <span className="font-medium">{itemToDelete.itemName}</span> 품목을 삭제하시겠습니까?<br />
                  이 작업은 되돌릴 수 없습니다.
                </>
              )}
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel>취소</AlertDialogCancel>
            <AlertDialogAction onClick={confirmDelete} className="bg-red-600 hover:bg-red-700">
              삭제
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>

      {/* 일괄 삭제 확인 다이얼로그 */}
      <AlertDialog open={isBulkDeleteDialogOpen} onOpenChange={setIsBulkDeleteDialogOpen}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>선택 품목 삭제</AlertDialogTitle>
            <AlertDialogDescription>
              선택한 {selectedItems.size}개의 품목을 삭제하시겠습니까?<br />
              이 작업은 되돌릴 수 없습니다.
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel>취소</AlertDialogCancel>
            <AlertDialogAction onClick={confirmBulkDelete} className="bg-red-600 hover:bg-red-700">
              삭제
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </>
  );
}