"use client";

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

import { useState, useCallback } from "react";
import { useRouter } from "next/navigation";
import { useModules } from "@/hooks/useModules";
import { Button } from "@/components/ui/button";
import { Card, CardContent } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import {
  TableRow,
  TableCell,
} from "@/components/ui/table";
import { Checkbox } from "@/components/ui/checkbox";
import {
  Factory,
  ArrowLeft,
  CheckCircle2,
  Eye,
} 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";
import {
  getProductionOrders,
  getProductionOrderStats,
} from "@/lib/api/production-orders";
import type {
  ProductionOrder,
  ProductionStatus,
  ProductionOrderStats,
} from "@/lib/api/production-orders";
import { formatNumber } from '@/lib/utils/amount';

// 진행 단계 컴포넌트
function ProgressSteps({ statusCode }: { statusCode?: string }) {
  const getSteps = () => {
    // 기본: 생산지시 목록에 있으면 수주확정, 생산지시는 이미 완료
    const steps = [
      { label: "수주확정", completed: true, active: false },
      { label: "생산지시", completed: true, active: false },
      { label: "작업지시", completed: false, active: false },
      { label: "생산", completed: false, active: false },
      { label: "검사출하", completed: false, active: false },
    ];

    if (!statusCode) return steps;

    // IN_PROGRESS = 생산대기 (작업지시 배정 진행 중)
    if (statusCode === "IN_PROGRESS") {
      steps[2].active = true;
    }
    // IN_PRODUCTION = 생산중
    if (statusCode === "IN_PRODUCTION") {
      steps[2].completed = true;
      steps[3].active = true;
    }
    // PRODUCED = 생산완료
    if (statusCode === "PRODUCED") {
      steps[2].completed = true;
      steps[3].completed = true;
      steps[4].active = true;
    }
    // SHIPPING = 출하중
    if (statusCode === "SHIPPING") {
      steps[2].completed = true;
      steps[3].completed = true;
      steps[4].active = true;
    }
    // SHIPPED = 출하완료
    if (statusCode === "SHIPPED") {
      steps[2].completed = true;
      steps[3].completed = true;
      steps[4].completed = true;
    }

    return steps;
  };

  const steps = getSteps();

  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: ProductionStatus) {
  const config: Record<
    ProductionStatus,
    { label: string; className: string }
  > = {
    waiting: {
      label: "생산대기",
      className: "bg-yellow-100 text-yellow-700 border-yellow-200",
    },
    in_production: {
      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: "orderNumber", label: "수주번호", className: "min-w-[150px]", copyable: true },
  { key: "siteName", label: "현장명", className: "min-w-[180px]", copyable: true },
  { key: "clientName", label: "거래처", className: "min-w-[120px]", copyable: true },
  { key: "nodeCount", label: "개소", className: "w-[80px] text-center", copyable: true },
  { key: "deliveryDate", label: "납기", className: "w-[110px]", copyable: true },
  { key: "productionOrderedAt", label: "생산지시일", className: "w-[110px]", copyable: true },
  { key: "status", label: "상태", className: "w-[100px]" },
  { key: "workOrderCount", label: "작업지시", className: "w-[80px] text-center", copyable: true },
  { key: "actions", label: "작업", className: "w-[100px] text-center" },
];

export default function ProductionOrdersListPage() {
  const router = useRouter();
  const { isEnabled, tenantIndustry } = useModules();

  // 생산 모듈 비활성 시 접근 차단 (tenantIndustry 미설정 시 전부 허용)
  if (tenantIndustry && !isEnabled('production')) {
    return (
      <div className="flex flex-col items-center justify-center min-h-[40vh]">
        <p className="text-muted-foreground">생산관리 모듈이 활성화되어 있지 않습니다.</p>
        <button
          className="mt-4 text-sm text-blue-600 hover:underline"
          onClick={() => router.push('/sales/order-management-sales')}
        >
          ← 수주 목록으로
        </button>
      </div>
    );
  }

  const [stats, setStats] = useState<ProductionOrderStats>({
    total: 0,
    waiting: 0,
    in_production: 0,
    completed: 0,
  });

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

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

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

  // 탭 옵션 (통계 기반 동적 카운트)
  const tabs: TabOption[] = [
    { value: "all", label: "전체", count: stats.total },
    { value: "waiting", label: "생산대기", count: stats.waiting, color: "yellow" },
    { value: "in_production", label: "생산중", count: stats.in_production, color: "green" },
    { value: "completed", label: "생산완료", count: stats.completed, color: "gray" },
  ];

  // 테이블 행 렌더링
  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.orderNumber}
          </code>
        </TableCell>
        <TableCell className="max-w-[200px] truncate">
          {item.siteName}
        </TableCell>
        <TableCell>{item.clientName}</TableCell>
        <TableCell className="text-center">{formatNumber(item.nodeCount)}개소</TableCell>
        <TableCell>{item.deliveryDate}</TableCell>
        <TableCell>{item.productionOrderedAt}</TableCell>
        <TableCell>{getStatusBadge(item.productionStatus)}</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>
            </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}
        title={item.siteName}
        isSelected={isSelected}
        onToggleSelection={onToggle}
        onCardClick={() => handleRowClick(item)}
        headerBadges={
          <>
            <Badge
              variant="outline"
              className="bg-blue-50 text-blue-700 font-mono text-xs"
            >
              {item.orderNumber}
            </Badge>
            {getStatusBadge(item.productionStatus)}
          </>
        }
        infoGrid={
          <div className="grid grid-cols-2 gap-x-4 gap-y-3">
            <InfoField label="수주번호" value={item.orderNumber} />
            <InfoField label="현장명" value={item.siteName} />
            <InfoField label="거래처" value={item.clientName} />
            <InfoField label="개소" value={`${formatNumber(item.nodeCount)}개소`} />
            <InfoField label="납기" value={item.deliveryDate} />
            <InfoField label="생산지시일" value={item.productionOrderedAt} />
            <InfoField
              label="작업지시"
              value={item.workOrderCount > 0 ? `${item.workOrderCount}건` : "-"}
            />
          </div>
        }
        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>
            </div>
          ) : undefined
        }
      />
    );
  };

  // getList API 호출
  const getList = useCallback(async (params?: { page?: number; pageSize?: number; search?: string; tab?: string }) => {
    const productionStatus = params?.tab && params.tab !== "all"
      ? (params.tab as ProductionStatus)
      : undefined;

    const result = await getProductionOrders({
      search: params?.search,
      productionStatus,
      page: params?.page,
      perPage: params?.pageSize,
    });

    if (result.success) {
      // 통계 새로고침
      getProductionOrderStats().then((statsResult) => {
        if (statsResult.success && statsResult.data) {
          setStats(statsResult.data);
        }
      });

      return {
        success: true,
        data: result.data,
        totalCount: result.pagination?.total || 0,
        totalPages: result.pagination?.lastPage || 1,
      };
    }

    return {
      success: false,
      data: [],
      totalCount: 0,
      error: result.error,
    };
  }, []);

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

    idField: "id",

    actions: {
      getList,
    },

    columns: TABLE_COLUMNS,

    tabs: tabs,
    defaultTab: "all",

    searchPlaceholder: "수주번호, 현장명, 거래처 검색...",

    itemsPerPage: 20,

    clientSideFiltering: false,

    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,
  };

  return (
    <UniversalListPage<ProductionOrder>
      config={productionOrderConfig}
    />
  );
}
