/**
 * 검사기준관리 - 목록 페이지
 * IntegratedListTemplateV2 기반
 * 수입검사/중간검사/제품검사 3가지 타입
 */

import { useState, useMemo } from "react";
import { FileText, Plus, Edit, Trash2, Eye, FileCheck } from "lucide-react";
import { useData } from "./contexts/DataContext";
import type { InspectionStandard } from "./contexts/DataContext";
import { IntegratedListTemplateV2, TabOption, TableColumn } from "./templates/IntegratedListTemplateV2";
import { Button } from "./ui/button";
import { Badge } from "./ui/badge";
import { TableRow, TableCell } from "./ui/table";
import { Checkbox } from "./ui/checkbox";
import { toast } from "sonner@2.0.3";
import { InspectionStandardForm } from "./InspectionStandardForm";
import { InspectionStandardView } from "./InspectionStandardView";

type ViewMode = "list" | "form" | "view";

export function InspectionStandardManagement() {
  const { inspectionStandards, deleteInspectionStandard } = useData();
  const [viewMode, setViewMode] = useState<ViewMode>("list");
  const [selectedStandard, setSelectedStandard] = useState<InspectionStandard | null>(null);
  const [searchTerm, setSearchTerm] = useState("");
  const [activeTab, setActiveTab] = useState("all");
  const [selectedItems, setSelectedItems] = useState<Set<string>>(new Set());
  const [currentPage, setCurrentPage] = useState(1);
  const itemsPerPage = 10;

  // 검사 유형 옵션
  const inspectionTypes = [
    { value: "incoming", label: "수입검사", color: "bg-blue-500" },
    { value: "process", label: "중간검사", color: "bg-orange-500" },
    { value: "final", label: "제품검사", color: "bg-green-500" }
  ];

  // 탭 옵션
  const tabs: TabOption[] = [
    { value: "all", label: "전체", count: inspectionStandards.length },
    { value: "incoming", label: "수입검사", count: inspectionStandards.filter(s => s.inspectionType === "incoming").length, color: "blue" },
    { value: "process", label: "중간검사", count: inspectionStandards.filter(s => s.inspectionType === "process").length, color: "orange" },
    { value: "final", label: "제품검사", count: inspectionStandards.filter(s => s.inspectionType === "final").length, color: "green" },
    { value: "active", label: "사용중", count: inspectionStandards.filter(s => s.status === "active").length },
    { value: "inactive", label: "미사용", count: inspectionStandards.filter(s => s.status === "inactive").length }
  ];

  // 통계 카드 데이터
  const stats = [
    {
      label: "전체 검사기준",
      value: inspectionStandards.length,
      icon: FileText,
      iconColor: "text-blue-500"
    },
    {
      label: "수입검사",
      value: inspectionStandards.filter(s => s.inspectionType === "incoming").length,
      icon: FileCheck,
      iconColor: "text-blue-500"
    },
    {
      label: "중간검사",
      value: inspectionStandards.filter(s => s.inspectionType === "process").length,
      icon: FileCheck,
      iconColor: "text-orange-500"
    },
    {
      label: "제품검사",
      value: inspectionStandards.filter(s => s.inspectionType === "final").length,
      icon: FileCheck,
      iconColor: "text-green-500"
    }
  ];

  // 테이블 컬럼 정의
  const tableColumns: TableColumn[] = [
    { key: "standardNumber", label: "기준번호", className: "px-4" },
    { key: "inspectionType", label: "검사유형", className: "px-4" },
    { key: "inspectionName", label: "검사명칭", className: "px-4" },
    { key: "description", label: "설명", className: "px-4", hideOnMobile: true },
    { key: "status", label: "상태", className: "px-4" },
    { key: "isFinal", label: "확정여부", className: "px-4", hideOnMobile: true },
    { key: "createdAt", label: "등록일", className: "px-4", hideOnMobile: true },
    { key: "actions", label: "작업", className: "px-4 text-right" }
  ];

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

    // 탭 필터
    if (activeTab !== "all") {
      if (activeTab === "active" || activeTab === "inactive") {
        filtered = filtered.filter(s => s.status === activeTab);
      } else {
        filtered = filtered.filter(s => s.inspectionType === activeTab);
      }
    }

    // 검색 필터
    if (searchTerm) {
      const term = searchTerm.toLowerCase();
      filtered = filtered.filter(
        s =>
          s.standardNumber.toLowerCase().includes(term) ||
          s.inspectionName.toLowerCase().includes(term) ||
          s.itemName?.toLowerCase().includes(term) ||
          s.description?.toLowerCase().includes(term)
      );
    }

    return filtered;
  }, [inspectionStandards, activeTab, searchTerm]);

  // 페이지네이션
  const totalPages = Math.ceil(filteredData.length / itemsPerPage);
  const paginatedData = filteredData.slice(
    (currentPage - 1) * itemsPerPage,
    currentPage * itemsPerPage
  );

  // 선택 관련 함수
  const handleToggleSelection = (id: string) => {
    setSelectedItems(prev => {
      const newSet = new Set(prev);
      if (newSet.has(id)) {
        newSet.delete(id);
      } else {
        newSet.add(id);
      }
      return newSet;
    });
  };

  const handleToggleSelectAll = () => {
    if (selectedItems.size === paginatedData.length && paginatedData.length > 0) {
      setSelectedItems(new Set());
    } else {
      setSelectedItems(new Set(paginatedData.map(s => s.id)));
    }
  };

  // 액션 핸들러
  const handleAdd = () => {
    setSelectedStandard(null);
    setViewMode("form");
  };

  const handleEdit = (standard: InspectionStandard) => {
    setSelectedStandard(standard);
    setViewMode("form");
  };

  const handleView = (standard: InspectionStandard) => {
    setSelectedStandard(standard);
    setViewMode("view");
  };

  const handleDelete = (standard: InspectionStandard) => {
    if (confirm(`"${standard.inspectionName}" 검사기준을 삭제하시겠습니까?`)) {
      deleteInspectionStandard(standard.id);
    }
  };

  const handleBack = () => {
    setViewMode("list");
    setSelectedStandard(null);
  };

  // 테이블 행 렌더링
  const renderTableRow = (standard: InspectionStandard, index: number, globalIndex: number) => {
    const isSelected = selectedItems.has(standard.id);
    const type = inspectionTypes.find(t => t.value === standard.inspectionType);

    return (
      <TableRow 
        key={standard.id}
        className="cursor-pointer hover:bg-muted/50 h-14"
        onClick={() => handleView(standard)}
      >
        <TableCell onClick={(e) => e.stopPropagation()}>
          <Checkbox
            checked={isSelected}
            onCheckedChange={() => handleToggleSelection(standard.id)}
          />
        </TableCell>
        <TableCell>
          <span className="font-mono text-sm">{standard.standardNumber}</span>
        </TableCell>
        <TableCell>
          <Badge className={`${type?.color} text-white`}>
            {type?.label}
          </Badge>
        </TableCell>
        <TableCell>
          <div>
            <div className="font-medium">{standard.inspectionName}</div>
            {standard.itemName && (
              <div className="text-xs text-muted-foreground">{standard.itemName}</div>
            )}
          </div>
        </TableCell>
        <TableCell className="hidden md:table-cell">
          <span className="text-sm text-muted-foreground line-clamp-2">
            {standard.description || "-"}
          </span>
        </TableCell>
        <TableCell>
          <Badge variant={standard.status === "active" ? "default" : "secondary"}>
            {standard.status === "active" ? "사용중" : "미사용"}
          </Badge>
        </TableCell>
        <TableCell className="hidden md:table-cell">
          <Badge variant={standard.isFinal ? "default" : "outline"}>
            {standard.isFinal ? "확정" : `${standard.currentRevision}차`}
          </Badge>
        </TableCell>
        <TableCell className="hidden md:table-cell">
          <span className="text-sm text-muted-foreground">
            {new Date(standard.createdAt).toLocaleDateString()}
          </span>
        </TableCell>
        {isSelected && (
          <TableCell className="text-right" onClick={(e) => e.stopPropagation()}>
            <div className="flex items-center justify-end gap-1">
              <Button
                variant="ghost"
                size="sm"
                onClick={() => handleView(standard)}
                title="상세보기"
              >
                <Eye className="h-4 w-4" />
              </Button>
              <Button
                variant="ghost"
                size="sm"
                onClick={() => handleEdit(standard)}
                title="수정"
                disabled={standard.isFinal}
              >
                <Edit className="h-4 w-4" />
              </Button>
              <Button
                variant="ghost"
                size="sm"
                onClick={() => handleDelete(standard)}
                className="text-red-600 hover:text-red-700 hover:bg-red-50"
                title="삭제"
              >
                <Trash2 className="h-4 w-4" />
              </Button>
            </div>
          </TableCell>
        )}
      </TableRow>
    );
  };

  // 모바일 카드 렌더링
  const renderMobileCard = (
    standard: InspectionStandard,
    index: number,
    globalIndex: number,
    isSelected: boolean,
    onToggle: () => void
  ) => {
    const type = inspectionTypes.find(t => t.value === standard.inspectionType);

    return (
      <div
        key={standard.id}
        className="p-4 border rounded-lg bg-card cursor-pointer hover:bg-muted/50"
        onClick={() => handleView(standard)}
      >
        <div className="flex items-start gap-3">
          <div onClick={(e) => e.stopPropagation()}>
            <Checkbox checked={isSelected} onCheckedChange={onToggle} />
          </div>
          <div className="flex-1 space-y-2">
            <div className="flex items-center justify-between">
              <span className="font-mono text-sm">{standard.standardNumber}</span>
              <Badge className={`${type?.color} text-white`}>
                {type?.label}
              </Badge>
            </div>
            <div>
              <div className="font-medium">{standard.inspectionName}</div>
              {standard.itemName && (
                <div className="text-xs text-muted-foreground">{standard.itemName}</div>
              )}
            </div>
            <div className="flex items-center gap-2">
              <Badge variant={standard.status === "active" ? "default" : "secondary"}>
                {standard.status === "active" ? "사용중" : "미사용"}
              </Badge>
              <Badge variant={standard.isFinal ? "default" : "outline"}>
                {standard.isFinal ? "확정" : `${standard.currentRevision}차`}
              </Badge>
            </div>
            <div className="flex items-center justify-between text-sm text-muted-foreground">
              <span>{new Date(standard.createdAt).toLocaleDateString()}</span>
              <div className="flex gap-1" onClick={(e) => e.stopPropagation()}>
                <Button variant="ghost" size="sm" onClick={() => handleEdit(standard)} disabled={standard.isFinal}>
                  <Edit className="h-4 w-4" />
                </Button>
                <Button
                  variant="ghost"
                  size="sm"
                  onClick={() => handleDelete(standard)}
                  className="text-red-600"
                >
                  <Trash2 className="h-4 w-4" />
                </Button>
              </div>
            </div>
          </div>
        </div>
      </div>
    );
  };

  // 등록/수정 폼 화면
  if (viewMode === "form") {
    return (
      <InspectionStandardForm
        standard={selectedStandard}
        onBack={handleBack}
      />
    );
  }

  // 상세보기 화면
  if (viewMode === "view" && selectedStandard) {
    return (
      <InspectionStandardView
        standard={selectedStandard}
        onBack={handleBack}
        onEdit={() => {
          if (!selectedStandard.isFinal) {
            setViewMode("form");
          } else {
            toast.error("확정된 검사기준은 수정할 수 없습니다.");
          }
        }}
      />
    );
  }

  // 목록 화면
  return (
    <IntegratedListTemplateV2
      title="검사기준 목록"
      description="수입검사/중간검사/제품검사 기준 관리"
      icon={FileText}
      headerActions={
        <Button onClick={handleAdd}>
          <Plus className="h-4 w-4 mr-2" />
          검사기준 추가
        </Button>
      }
      stats={stats}
      searchValue={searchTerm}
      onSearchChange={setSearchTerm}
      searchPlaceholder="기준번호, 검사명칭, 품목명으로 검색..."
      tabs={tabs}
      activeTab={activeTab}
      onTabChange={(value) => {
        setActiveTab(value);
        setCurrentPage(1);
      }}
      tableColumns={tableColumns}
      tableTitle={`${tabs.find(t => t.value === activeTab)?.label || "전체"} (${filteredData.length}개)`}
      data={paginatedData}
      selectedItems={selectedItems}
      onToggleSelection={handleToggleSelection}
      onToggleSelectAll={handleToggleSelectAll}
      getItemId={(standard) => standard.id}
      renderTableRow={renderTableRow}
      renderMobileCard={renderMobileCard}
      pagination={{
        currentPage,
        totalPages,
        totalItems: filteredData.length,
        itemsPerPage,
        onPageChange: setCurrentPage
      }}
    />
  );
}