"use client";

/**
 * 생산지시 목록 페이지
 *
 * - 수주관리 > 생산지시 보기에서 접근
 * - 진행 단계 바
 * - 필터 탭: 전체, 생산대기, 생산중, 생산완료 (TabChip 사용)
 * - IntegratedListTemplateV2 템플릿 적용
 */

import { useState } from "react";
import { useRouter } from "next/navigation";
import { Button } from "@/components/ui/button";
import { Card, CardContent } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { DeleteConfirmDialog } from "@/components/ui/confirm-dialog";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import { Checkbox } from "@/components/ui/checkbox";
import {
  Factory,
  ArrowLeft,
  CheckCircle2,
  Eye,
  Trash2,
} from "lucide-react";
import {
  UniversalListPage,
  type UniversalListConfig,
  type TabOption,
  type TableColumn,
} from "@/components/templates/UniversalListPage";
import { BadgeSm } from "@/components/atoms/BadgeSm";
import { ListMobileCard, InfoField } from "@/components/organisms/MobileCard";

// 생산지시 상태 타입
type ProductionOrderStatus =
  | "waiting"      // 생산대기
  | "in_progress"  // 생산중
  | "completed";   // 생산완료

// 생산지시 데이터 타입
interface ProductionOrder {
  id: string;
  productionOrderNumber: string;  // PO-KD-TS-XXXXXX-XX
  orderNumber: string;            // KD-TS-XXXXXX-XX
  siteName: string;
  client: string;
  quantity: number;
  dueDate: string;
  productionOrderDate: string;
  status: ProductionOrderStatus;
  workOrderCount: number;
}

// 샘플 생산지시 데이터
const SAMPLE_PRODUCTION_ORDERS: ProductionOrder[] = [
  {
    id: "PO-001",
    productionOrderNumber: "PO-KD-TS-251217-07",
    orderNumber: "KD-TS-251217-07",
    siteName: "씨밋 광교 센트럴시티",
    client: "호반건설(주)",
    quantity: 2,
    dueDate: "2026-02-15",
    productionOrderDate: "2025-12-22",
    status: "waiting",
    workOrderCount: 3,
  },
  {
    id: "PO-002",
    productionOrderNumber: "PO-KD-TS-251217-09",
    orderNumber: "KD-TS-251217-09",
    siteName: "데시앙 동탄 파크뷰",
    client: "태영건설(주)",
    quantity: 10,
    dueDate: "2026-02-10",
    productionOrderDate: "2025-12-22",
    status: "waiting",
    workOrderCount: 0,
  },
  {
    id: "PO-003",
    productionOrderNumber: "PO-KD-TS-251217-06",
    orderNumber: "KD-TS-251217-06",
    siteName: "예술 검실 푸르지오",
    client: "롯데건설(주)",
    quantity: 1,
    dueDate: "2026-02-10",
    productionOrderDate: "2025-12-22",
    status: "waiting",
    workOrderCount: 0,
  },
  {
    id: "PO-004",
    productionOrderNumber: "PO-KD-BD-251220-35",
    orderNumber: "KD-BD-251220-35",
    siteName: "[코레타스프] 판교 물류센터 철거현장",
    client: "현대건설(주)",
    quantity: 3,
    dueDate: "2026-02-03",
    productionOrderDate: "2025-12-20",
    status: "in_progress",
    workOrderCount: 2,
  },
  {
    id: "PO-005",
    productionOrderNumber: "PO-KD-BD-251219-34",
    orderNumber: "KD-BD-251219-34",
    siteName: "[코레타스프1] 김포 6차 필라테스장",
    client: "신성플랜(주)",
    quantity: 2,
    dueDate: "2026-01-15",
    productionOrderDate: "2025-12-19",
    status: "in_progress",
    workOrderCount: 3,
  },
  {
    id: "PO-006",
    productionOrderNumber: "PO-KD-TS-250401-29",
    orderNumber: "KD-TS-250401-29",
    siteName: "포레나 전주",
    client: "한화건설(주)",
    quantity: 2,
    dueDate: "2025-05-16",
    productionOrderDate: "2025-04-01",
    status: "completed",
    workOrderCount: 3,
  },
  {
    id: "PO-007",
    productionOrderNumber: "PO-KD-BD-250331-28",
    orderNumber: "KD-BD-250331-28",
    siteName: "포레나 수원",
    client: "포레나건설(주)",
    quantity: 4,
    dueDate: "2025-05-15",
    productionOrderDate: "2025-03-31",
    status: "completed",
    workOrderCount: 3,
  },
  {
    id: "PO-008",
    productionOrderNumber: "PO-KD-TS-250314-23",
    orderNumber: "KD-TS-250314-23",
    siteName: "자이 흑산파크",
    client: "GS건설(주)",
    quantity: 3,
    dueDate: "2025-04-28",
    productionOrderDate: "2025-03-14",
    status: "completed",
    workOrderCount: 3,
  },
];

// 진행 단계 컴포넌트
function ProgressSteps() {
  const steps = [
    { label: "수주확정", active: true, completed: true },
    { label: "생산지시", active: true, completed: false },
    { label: "작업지시", active: false, completed: false },
    { label: "생산", active: false, completed: false },
    { label: "검사출하", active: false, completed: false },
  ];

  return (
    <div className="flex items-center justify-center gap-2 py-4">
      {steps.map((step, index) => (
        <div key={step.label} className="flex items-center">
          <div className="flex items-center gap-2">
            <div
              className={`flex items-center justify-center w-6 h-6 rounded-full text-xs font-medium ${
                step.completed
                  ? "bg-primary text-primary-foreground"
                  : step.active
                  ? "bg-primary/20 text-primary border-2 border-primary"
                  : "bg-gray-100 text-gray-400"
              }`}
            >
              {step.completed ? (
                <CheckCircle2 className="h-4 w-4" />
              ) : (
                index + 1
              )}
            </div>
            <span
              className={`text-sm ${
                step.active || step.completed
                  ? "text-foreground font-medium"
                  : "text-muted-foreground"
              }`}
            >
              {step.label}
            </span>
          </div>
          {index < steps.length - 1 && (
            <div
              className={`w-8 h-0.5 mx-2 ${
                step.completed ? "bg-primary" : "bg-gray-200"
              }`}
            />
          )}
        </div>
      ))}
    </div>
  );
}

// 상태 배지 헬퍼
function getStatusBadge(status: ProductionOrderStatus) {
  const config: Record<
    ProductionOrderStatus,
    { label: string; className: string }
  > = {
    waiting: {
      label: "생산대기",
      className: "bg-yellow-100 text-yellow-700 border-yellow-200",
    },
    in_progress: {
      label: "생산중",
      className: "bg-green-100 text-green-700 border-green-200",
    },
    completed: {
      label: "생산완료",
      className: "bg-gray-100 text-gray-700 border-gray-200",
    },
  };
  const c = config[status];
  return <BadgeSm className={c.className}>{c.label}</BadgeSm>;
}

// 테이블 컬럼 정의
const TABLE_COLUMNS: TableColumn[] = [
  { key: "no", label: "번호", className: "w-[60px] text-center" },
  { key: "productionOrderNumber", label: "생산지시번호", className: "min-w-[150px]" },
  { key: "orderNumber", label: "수주번호", className: "min-w-[140px]" },
  { key: "siteName", label: "현장명", className: "min-w-[180px]" },
  { key: "client", label: "거래처", className: "min-w-[120px]" },
  { key: "quantity", label: "수량", className: "w-[80px] text-center" },
  { key: "dueDate", label: "납기", className: "w-[110px]" },
  { key: "productionOrderDate", label: "생산지시일", className: "w-[110px]" },
  { key: "status", label: "상태", className: "w-[100px]" },
  { key: "workOrderCount", label: "작업지시", className: "w-[80px] text-center" },
  { key: "actions", label: "작업", className: "w-[100px] text-center" },
];

export default function ProductionOrdersListPage() {
  const router = useRouter();
  const [orders, setOrders] = useState<ProductionOrder[]>(SAMPLE_PRODUCTION_ORDERS);
  const [searchTerm, setSearchTerm] = useState("");
  const [activeTab, setActiveTab] = useState("all");
  const [selectedItems, setSelectedItems] = useState<Set<string>>(new Set());
  const [currentPage, setCurrentPage] = useState(1);
  const itemsPerPage = 20;

  // 삭제 확인 다이얼로그 상태
  const [showDeleteDialog, setShowDeleteDialog] = useState(false);
  const [deleteTargetId, setDeleteTargetId] = useState<string | null>(null); // 개별 삭제 시 사용

  // 필터링된 데이터
  const filteredData = orders.filter((item) => {
    // 탭 필터
    if (activeTab !== "all") {
      const statusMap: Record<string, ProductionOrderStatus> = {
        waiting: "waiting",
        in_progress: "in_progress",
        completed: "completed",
      };
      if (item.status !== statusMap[activeTab]) return false;
    }

    // 검색 필터
    if (searchTerm) {
      const term = searchTerm.toLowerCase();
      return (
        item.productionOrderNumber.toLowerCase().includes(term) ||
        item.orderNumber.toLowerCase().includes(term) ||
        item.siteName.toLowerCase().includes(term) ||
        item.client.toLowerCase().includes(term)
      );
    }

    return true;
  });

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

  // 탭별 건수
  const tabCounts = {
    all: orders.length,
    waiting: orders.filter((i) => i.status === "waiting").length,
    in_progress: orders.filter((i) => i.status === "in_progress").length,
    completed: orders.filter((i) => i.status === "completed").length,
  };

  // 탭 옵션
  const tabs: TabOption[] = [
    { value: "all", label: "전체", count: tabCounts.all },
    { value: "waiting", label: "생산대기", count: tabCounts.waiting, color: "yellow" },
    { value: "in_progress", label: "생산중", count: tabCounts.in_progress, color: "green" },
    { value: "completed", label: "생산완료", count: tabCounts.completed, color: "gray" },
  ];

  const handleBack = () => {
    router.push("/sales/order-management-sales");
  };

  const handleRowClick = (item: ProductionOrder) => {
    router.push(`/sales/order-management-sales/production-orders/${item.id}`);
  };

  const handleView = (item: ProductionOrder) => {
    router.push(`/sales/order-management-sales/production-orders/${item.id}`);
  };

  // 개별 삭제 다이얼로그 열기
  const handleDelete = (item: ProductionOrder) => {
    setDeleteTargetId(item.id);
    setShowDeleteDialog(true);
  };

  // 체크박스 선택
  const toggleSelection = (id: string) => {
    const newSelection = new Set(selectedItems);
    if (newSelection.has(id)) {
      newSelection.delete(id);
    } else {
      newSelection.add(id);
    }
    setSelectedItems(newSelection);
  };

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

  // 일괄 삭제 다이얼로그 열기
  const handleBulkDelete = () => {
    if (selectedItems.size > 0) {
      setDeleteTargetId(null); // 일괄 삭제
      setShowDeleteDialog(true);
    }
  };

  // 삭제 개수 계산 (개별 삭제 시 1, 일괄 삭제 시 selectedItems.size)
  const deleteCount = deleteTargetId ? 1 : selectedItems.size;

  // 실제 삭제 실행
  const handleConfirmDelete = () => {
    if (deleteTargetId) {
      // 개별 삭제
      setOrders(orders.filter((o) => o.id !== deleteTargetId));
      setSelectedItems(new Set([...selectedItems].filter(id => id !== deleteTargetId)));
    } else {
      // 일괄 삭제
      const selectedIds = Array.from(selectedItems);
      setOrders(orders.filter((o) => !selectedIds.includes(o.id)));
      setSelectedItems(new Set());
    }
    setShowDeleteDialog(false);
    setDeleteTargetId(null);
  };

  // 테이블 행 렌더링
  const renderTableRow = (
    item: ProductionOrder,
    index: number,
    globalIndex: number,
    handlers: { isSelected: boolean; onToggle: () => void; onRowClick?: () => void }
  ) => {
    const { isSelected, onToggle } = handlers;
    return (
      <TableRow
        key={item.id}
        className={`cursor-pointer hover:bg-muted/50 ${isSelected ? "bg-muted/30" : ""}`}
        onClick={() => handleRowClick(item)}
      >
        <TableCell onClick={(e) => e.stopPropagation()} className="text-center">
          <Checkbox
            checked={isSelected}
            onCheckedChange={onToggle}
          />
        </TableCell>
        <TableCell className="text-center text-muted-foreground">
          {globalIndex}
        </TableCell>
        <TableCell>
          <code className="text-xs bg-blue-50 text-blue-700 px-1.5 py-0.5 rounded">
            {item.productionOrderNumber}
          </code>
        </TableCell>
        <TableCell>
          <code className="text-xs bg-gray-100 px-1.5 py-0.5 rounded">
            {item.orderNumber}
          </code>
        </TableCell>
        <TableCell className="max-w-[200px] truncate">
          {item.siteName}
        </TableCell>
        <TableCell>{item.client}</TableCell>
        <TableCell className="text-center">{item.quantity}개</TableCell>
        <TableCell>{item.dueDate}</TableCell>
        <TableCell>{item.productionOrderDate}</TableCell>
        <TableCell>{getStatusBadge(item.status)}</TableCell>
        <TableCell className="text-center">
          {item.workOrderCount > 0 ? (
            <Badge variant="outline">{item.workOrderCount}건</Badge>
          ) : (
            <span className="text-muted-foreground">-</span>
          )}
        </TableCell>
        <TableCell onClick={(e) => e.stopPropagation()}>
          {isSelected && (
            <div className="flex gap-1 justify-center">
              <Button variant="ghost" size="sm" onClick={() => handleView(item)}>
                <Eye className="h-4 w-4" />
              </Button>
              <Button variant="ghost" size="sm" onClick={() => handleDelete(item)}>
                <Trash2 className="h-4 w-4" />
              </Button>
            </div>
          )}
        </TableCell>
      </TableRow>
    );
  };

  // 모바일 카드 렌더링
  const renderMobileCard = (
    item: ProductionOrder,
    index: number,
    globalIndex: number,
    handlers: { isSelected: boolean; onToggle: () => void; onRowClick?: () => void }
  ) => {
    const { isSelected, onToggle } = handlers;
    return (
      <ListMobileCard
        key={item.id}
        id={item.id}
        isSelected={isSelected}
        onToggleSelection={onToggle}
        onCardClick={() => handleRowClick(item)}
        headerBadges={
          <>
            <Badge
              variant="outline"
              className="bg-blue-50 text-blue-700 font-mono text-xs"
            >
              {item.productionOrderNumber}
            </Badge>
            {getStatusBadge(item.status)}
          </>
        }
        fields={
          <>
            <InfoField label="수주번호" value={item.orderNumber} />
            <InfoField label="현장명" value={item.siteName} />
            <InfoField label="거래처" value={item.client} />
            <InfoField label="수량" value={`${item.quantity}개`} />
            <InfoField label="납기" value={item.dueDate} />
            <InfoField label="생산지시일" value={item.productionOrderDate} />
            <InfoField
              label="작업지시"
              value={item.workOrderCount > 0 ? `${item.workOrderCount}건` : "-"}
            />
          </>
        }
        actions={
          isSelected ? (
            <div className="flex gap-2 w-full">
              <Button
                variant="outline"
                size="default"
                className="flex-1 min-w-[100px] h-11"
                onClick={(e) => {
                  e.stopPropagation();
                  handleView(item);
                }}
              >
                <Eye className="h-4 w-4 mr-2" />
                상세
              </Button>
              <Button
                variant="outline"
                size="default"
                className="flex-1 min-w-[100px] h-11"
                onClick={(e) => {
                  e.stopPropagation();
                  handleDelete(item);
                }}
              >
                <Trash2 className="h-4 w-4 mr-2" />
                삭제
              </Button>
            </div>
          ) : undefined
        }
      />
    );
  };

  // ===== UniversalListPage 설정 =====
  const productionOrderConfig: UniversalListConfig<ProductionOrder> = {
    title: "생산지시 목록",
    icon: Factory,
    basePath: "/sales/order-management-sales/production-orders",

    idField: "id",

    actions: {
      getList: async () => ({
        success: true,
        data: orders,
        totalCount: orders.length,
      }),
    },

    columns: TABLE_COLUMNS,

    tabs: tabs,
    defaultTab: activeTab,

    searchPlaceholder: "생산지시번호, 수주번호, 현장명 검색...",

    itemsPerPage,

    clientSideFiltering: true,

    searchFilter: (item, searchValue) => {
      const term = searchValue.toLowerCase();
      return (
        item.productionOrderNumber.toLowerCase().includes(term) ||
        item.orderNumber.toLowerCase().includes(term) ||
        item.siteName.toLowerCase().includes(term) ||
        item.client.toLowerCase().includes(term)
      );
    },

    tabFilter: (item, tabValue) => {
      if (tabValue === "all") return true;
      const statusMap: Record<string, ProductionOrderStatus> = {
        waiting: "waiting",
        in_progress: "in_progress",
        completed: "completed",
      };
      return item.status === statusMap[tabValue];
    },

    headerActions: (
      <Button variant="outline" onClick={handleBack}>
        <ArrowLeft className="h-4 w-4 mr-2" />
        수주 목록
      </Button>
    ),

    tabsContent: (
      <Card className="w-full mb-4">
        <CardContent className="py-2">
          <ProgressSteps />
        </CardContent>
      </Card>
    ),

    renderTableRow,
    renderMobileCard,

    renderDialogs: () => (
      <DeleteConfirmDialog
        open={showDeleteDialog}
        onOpenChange={setShowDeleteDialog}
        onConfirm={handleConfirmDelete}
        title="삭제 확인"
        description={
          <>
            선택한 <strong>{deleteCount}개</strong>의 항목을 삭제하시겠습니까?
            <br />
            <span className="text-muted-foreground text-sm">
              삭제된 항목은 복구할 수 없습니다. 관련된 데이터도 함께 삭제될 수 있습니다.
            </span>
          </>
        }
      />
    ),
  };

  return (
    <UniversalListPage<ProductionOrder>
      config={productionOrderConfig}
      initialData={orders}
      initialTotalCount={orders.length}
      externalSelection={{
        selectedItems,
        setSelectedItems,
      }}
      externalTab={{
        activeTab,
        setActiveTab: (value) => {
          setActiveTab(value);
          setCurrentPage(1);
        },
      }}
      externalSearch={{
        searchValue: searchTerm,
        setSearchValue: setSearchTerm,
      }}
      externalPagination={{
        currentPage,
        setCurrentPage,
      }}
    />
  );
}