"use client";

/**
 * 생산지시 상세 페이지
 *
 * - 공정 진행 현황
 * - 기본 정보 / 거래처/현장 정보
 * - BOM 품목별 공정 분류
 * - 작업지시서 목록
 */

import { useState, useEffect } from "react";
import { useRouter, useParams } from "next/navigation";
import { useModules } from "@/hooks/useModules";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import {
  Factory,
  ArrowLeft,
  ClipboardList,
  CheckCircle2,
  Circle,
  Activity,
  Play,
  ChevronDown,
} from "lucide-react";
import { PageLayout } from "@/components/organisms/PageLayout";
import { PageHeader } from "@/components/organisms/PageHeader";
import { BadgeSm } from "@/components/atoms/BadgeSm";
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from "@/components/ui/alert-dialog";
import { ConfirmDialog } from "@/components/ui/confirm-dialog";
import { toast } from "sonner";
import { ServerErrorPage } from "@/components/common/ServerErrorPage";
import { formatNumber } from '@/lib/utils/amount';
import { getProductionOrderDetail } from "@/lib/api/production-orders";
import { createProductionOrder } from "@/components/orders/actions";
import type {
  ProductionOrderDetail,
  ProductionStatus,
  ProductionWorkOrder,
} from "@/lib/api/production-orders";

// 공정 진행 현황 컴포넌트
function ProcessProgress({ workOrders }: { workOrders: ProductionWorkOrder[] }) {
  if (workOrders.length === 0) {
    return (
      <Card>
        <CardHeader>
          <CardTitle className="text-base flex items-center gap-2">
            <Activity className="h-4 w-4" />
            공정 진행 현황
          </CardTitle>
        </CardHeader>
        <CardContent>
          <p className="text-muted-foreground text-sm text-center py-4">
            아직 작업지시가 생성되지 않았습니다.
          </p>
        </CardContent>
      </Card>
    );
  }

  const completedCount = workOrders.filter(
    (w) => w.status === "completed" || w.status === "shipped"
  ).length;
  const totalCount = workOrders.length;
  const progressPercent = Math.round((completedCount / totalCount) * 100);

  return (
    <Card>
      <CardHeader>
        <CardTitle className="text-base flex items-center gap-2">
          <Activity className="h-4 w-4" />
          공정 진행 현황
        </CardTitle>
      </CardHeader>
      <CardContent>
        <div className="space-y-4">
          {/* 진행률 바 */}
          <div className="space-y-2">
            <div className="flex justify-between text-sm">
              <span className="text-muted-foreground">진행률</span>
              <span className="font-medium">{progressPercent}%</span>
            </div>
            <div className="h-2 bg-gray-100 rounded-full overflow-hidden">
              <div
                className="h-full bg-primary transition-all"
                style={{ width: `${progressPercent}%` }}
              />
            </div>
          </div>

          {/* 공정 단계 */}
          <div className="flex items-center justify-center gap-2 pt-2">
            {workOrders.map((wo, index) => (
              <div key={wo.id} className="flex items-center">
                <div className="flex flex-col items-center gap-1">
                  <div
                    className={`flex items-center justify-center w-8 h-8 rounded-full ${
                      wo.status === "completed" || wo.status === "shipped"
                        ? "bg-green-500 text-white"
                        : wo.status === "in_progress"
                        ? "bg-blue-500 text-white"
                        : "bg-gray-100 text-gray-400"
                    }`}
                  >
                    {wo.status === "completed" || wo.status === "shipped" ? (
                      <CheckCircle2 className="h-4 w-4" />
                    ) : (
                      <Circle className="h-4 w-4" />
                    )}
                  </div>
                  <span className="text-xs text-muted-foreground">{wo.processName}</span>
                </div>
                {index < workOrders.length - 1 && (
                  <div
                    className={`w-12 h-0.5 mx-1 ${
                      wo.status === "completed" || wo.status === "shipped"
                        ? "bg-green-500"
                        : "bg-gray-200"
                    }`}
                  />
                )}
              </div>
            ))}
          </div>
        </div>
      </CardContent>
    </Card>
  );
}

// 상태 배지 헬퍼
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>;
}

// 작업지시 상태 배지 헬퍼
function getWorkOrderStatusBadge(status: string) {
  const config: Record<string, { label: string; className: string }> = {
    unassigned: { label: "미배정", className: "bg-gray-100 text-gray-700 border-gray-200" },
    pending: { label: "대기", className: "bg-gray-100 text-gray-700 border-gray-200" },
    waiting: { label: "준비중", className: "bg-yellow-100 text-yellow-700 border-yellow-200" },
    in_progress: { label: "작업중", className: "bg-blue-100 text-blue-700 border-blue-200" },
    completed: { label: "완료", className: "bg-green-100 text-green-700 border-green-200" },
    shipped: { label: "출하", className: "bg-purple-100 text-purple-700 border-purple-200" },
  };
  const c = config[status] || { label: status, className: "bg-gray-100 text-gray-700 border-gray-200" };
  return <BadgeSm className={c.className}>{c.label}</BadgeSm>;
}

// 정보 표시 컴포넌트
function InfoItem({ label, value }: { label: string; value: string }) {
  return (
    <div>
      <p className="text-sm text-muted-foreground">{label}</p>
      <p className="font-medium">{value || "-"}</p>
    </div>
  );
}

export default function ProductionOrderDetailPage() {
  const router = useRouter();
  const params = useParams();
  const orderId = params.id as string;
  const { isEnabled, tenantIndustry } = useModules();

  // 생산 모듈 비활성 시 접근 차단 (tenantIndustry 미설정 시 전부 허용)
  if (tenantIndustry && !isEnabled('production')) {
    return (
      <PageLayout>
        <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>
      </PageLayout>
    );
  }

  const [detail, setDetail] = useState<ProductionOrderDetail | null>(null);
  const [loading, setLoading] = useState(true);
  const [isCreateWorkOrderDialogOpen, setIsCreateWorkOrderDialogOpen] = useState(false);
  const [isSuccessDialogOpen, setIsSuccessDialogOpen] = useState(false);
  const [isCreating, setIsCreating] = useState(false);
  const [bomOpen, setBomOpen] = useState(false);

  // 데이터 로드
  const loadDetail = async () => {
    setLoading(true);
    const result = await getProductionOrderDetail(orderId);
    if (result.success && result.data) {
      setDetail(result.data);
    } else {
      setDetail(null);
    }
    setLoading(false);
  };

  useEffect(() => {
    loadDetail();
  }, [orderId]);

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

  const handleCreateWorkOrder = () => {
    setIsCreateWorkOrderDialogOpen(true);
  };

  const handleConfirmCreateWorkOrder = async () => {
    setIsCreating(true);
    try {
      const result = await createProductionOrder(orderId);
      if (result.success) {
        setIsCreateWorkOrderDialogOpen(false);
        setIsSuccessDialogOpen(true);
      } else {
        toast.error(result.error || "작업지시 생성에 실패했습니다.");
      }
    } finally {
      setIsCreating(false);
    }
  };

  const handleSuccessDialogClose = () => {
    setIsSuccessDialogOpen(false);
    // 생산지시 목록으로 이동 (공통 ERP 영역 내 경로)
    router.push("/sales/order-management-sales/production-orders");
  };

  if (loading) {
    return (
      <PageLayout>
        <div className="flex items-center justify-center h-64">
          <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary" />
        </div>
      </PageLayout>
    );
  }

  if (!detail) {
    return (
      <ServerErrorPage
        title="생산지시 정보를 불러올 수 없습니다"
        message="생산지시 정보를 찾을 수 없습니다."
        showBackButton={true}
        showHomeButton={true}
      />
    );
  }

  const hasWorkOrders = detail.workOrders.length > 0;
  const canCreateWorkOrders = detail.productionStatus === "waiting" && !hasWorkOrders;

  return (
    <PageLayout>
      {/* 헤더 */}
      <PageHeader
        title={
          <div className="flex items-center gap-3">
            <span>생산지시 상세</span>
            <code className="text-sm font-mono bg-blue-50 text-blue-700 px-2 py-1 rounded">
              {detail.orderNumber}
            </code>
            {getStatusBadge(detail.productionStatus)}
          </div>
        }
        icon={Factory}
        actions={
          <div className="flex items-center gap-2">
            <Button variant="outline" onClick={handleBack}>
              <ArrowLeft className="h-4 w-4 mr-2" />
              목록
            </Button>
            {canCreateWorkOrders && (
              <Button onClick={handleCreateWorkOrder}>
                <ClipboardList className="h-4 w-4 mr-2" />
                작업지시 생성
              </Button>
            )}
          </div>
        }
      />

      <div className="space-y-6">
        {/* 공정 진행 현황 */}
        <ProcessProgress workOrders={detail.workOrders} />

        {/* 기본 정보 & 거래처/현장 정보 */}
        <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
          {/* 기본 정보 */}
          <Card>
            <CardHeader>
              <CardTitle className="text-base">기본 정보</CardTitle>
            </CardHeader>
            <CardContent>
              <div className="grid grid-cols-2 gap-4">
                <InfoItem label="수주번호" value={detail.orderNumber} />
                <InfoItem label="생산지시일" value={detail.productionOrderedAt} />
                <InfoItem label="납기일" value={detail.deliveryDate} />
                <InfoItem label="개소" value={`${formatNumber(detail.nodeCount)}개소`} />
              </div>
            </CardContent>
          </Card>

          {/* 거래처/현장 정보 */}
          <Card>
            <CardHeader>
              <CardTitle className="text-base">거래처/현장 정보</CardTitle>
            </CardHeader>
            <CardContent>
              <div className="grid grid-cols-2 gap-4">
                <InfoItem label="거래처" value={detail.clientName} />
                <InfoItem label="현장명" value={detail.siteName} />
              </div>
            </CardContent>
          </Card>
        </div>

        {/* BOM 품목별 공정 분류 (접이식) */}
        {detail.bomProcessGroups.length > 0 && (
          <Card>
            <CardHeader
              className="cursor-pointer select-none"
              onClick={() => setBomOpen((prev) => !prev)}
            >
              <div className="flex items-center justify-between">
                <CardTitle className="text-base">
                  BOM 품목별 공정 분류
                  <span className="ml-2 text-sm font-normal text-muted-foreground">
                    ({detail.bomProcessGroups.length}개 공정)
                  </span>
                </CardTitle>
                <ChevronDown
                  className={`h-5 w-5 text-muted-foreground transition-transform ${
                    bomOpen ? "rotate-180" : ""
                  }`}
                />
              </div>
            </CardHeader>
            {bomOpen && (
              <CardContent className="space-y-6 pt-0">
                {detail.bomProcessGroups.map((group) => (
                  <div key={group.processName} className="space-y-2">
                    <h4 className="text-sm font-semibold flex items-center gap-2">
                      <Badge variant="outline">{group.processName}</Badge>
                      <span className="text-muted-foreground font-normal text-xs">
                        {group.items.length}건
                      </span>
                    </h4>

                    <div className="border rounded-lg overflow-hidden">
                      <Table className="table-fixed">
                        <colgroup>
                          <col style={{ width: '20%' }} />
                          <col />
                          <col style={{ width: '20%' }} />
                          <col style={{ width: '8%' }} />
                          <col style={{ width: '10%' }} />
                          <col style={{ width: '12%' }} />
                        </colgroup>
                        <TableHeader>
                          <TableRow className="bg-gray-50">
                            <TableHead>품목코드</TableHead>
                            <TableHead>품목명</TableHead>
                            <TableHead>규격</TableHead>
                            <TableHead className="text-center">단위</TableHead>
                            <TableHead className="text-right">수량</TableHead>
                            <TableHead>개소</TableHead>
                          </TableRow>
                        </TableHeader>
                        <TableBody>
                          {group.items.map((item, idx) => (
                            <TableRow key={`${item.id}-${idx}`}>
                              <TableCell>
                                <code className="text-xs bg-gray-100 px-1.5 py-0.5 rounded">
                                  {item.itemCode}
                                </code>
                              </TableCell>
                              <TableCell>{item.itemName}</TableCell>
                              <TableCell className="text-muted-foreground">
                                {item.spec || "-"}
                              </TableCell>
                              <TableCell className="text-center">{item.unit || "-"}</TableCell>
                              <TableCell className="text-right">{formatNumber(item.quantity)}</TableCell>
                              <TableCell className="text-muted-foreground text-xs">{item.nodeName || "-"}</TableCell>
                            </TableRow>
                          ))}
                        </TableBody>
                      </Table>
                    </div>
                  </div>
                ))}
              </CardContent>
            )}
          </Card>
        )}

        {/* 작업지시서 목록 */}
        <Card>
          <CardHeader className="flex flex-row items-center justify-between">
            <CardTitle className="text-base">작업지시서 목록</CardTitle>
            {canCreateWorkOrders && (
              <Button onClick={handleCreateWorkOrder}>
                <Play className="h-4 w-4 mr-2" />
                작업지시 생성
              </Button>
            )}
          </CardHeader>
          <CardContent>
            {!hasWorkOrders ? (
              <div className="text-center py-8">
                <div className="flex flex-col items-center gap-2">
                  <ClipboardList className="h-12 w-12 text-gray-300" />
                  <p className="text-muted-foreground text-sm">
                    아직 작업지시서가 생성되지 않았습니다.
                  </p>
                  {canCreateWorkOrders && (
                    <p className="text-sm text-muted-foreground">
                      위 버튼을 클릭하여 BOM 기반 작업지시서를 자동 생성하세요.
                    </p>
                  )}
                </div>
              </div>
            ) : (
              <div className="border rounded-lg overflow-hidden">
                <Table>
                  <TableHeader>
                    <TableRow>
                      <TableHead>작업지시번호</TableHead>
                      <TableHead>공정</TableHead>
                      <TableHead className="text-center">개소</TableHead>
                      <TableHead>상태</TableHead>
                      <TableHead>담당자</TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {detail.workOrders.map((wo) => (
                      <TableRow key={wo.id}>
                        <TableCell>
                          <code className="text-xs bg-gray-100 px-1.5 py-0.5 rounded">
                            {wo.workOrderNo}
                          </code>
                        </TableCell>
                        <TableCell>{wo.processName}</TableCell>
                        <TableCell className="text-center">{wo.quantity}개소</TableCell>
                        <TableCell>{getWorkOrderStatusBadge(wo.status)}</TableCell>
                        <TableCell>{wo.assignees.length > 0 ? wo.assignees.join(", ") : "-"}</TableCell>
                      </TableRow>
                    ))}
                  </TableBody>
                </Table>
              </div>
            )}
          </CardContent>
        </Card>
      </div>

      {/* 작업지시 생성 확인 다이얼로그 */}
      <ConfirmDialog
        open={isCreateWorkOrderDialogOpen}
        onOpenChange={setIsCreateWorkOrderDialogOpen}
        onConfirm={handleConfirmCreateWorkOrder}
        title="작업지시서 자동 생성"
        description={
          <div className="space-y-4 pt-2">
            <p className="font-medium text-foreground">
              이 수주에 대한 작업지시서를 자동 생성합니다.
            </p>
            <p className="text-muted-foreground">
              BOM 기반으로 공정별 작업지시서가 생성됩니다.
              생성된 작업지시서는 생산팀에서 확인하고 작업을 진행할 수 있습니다.
            </p>
          </div>
        }
        confirmText="작업지시 생성"
        loading={isCreating}
      />

      {/* 작업지시 생성 성공 다이얼로그 */}
      <AlertDialog open={isSuccessDialogOpen} onOpenChange={setIsSuccessDialogOpen}>
        <AlertDialogContent className="max-w-md">
          <AlertDialogHeader>
            <AlertDialogTitle className="sr-only">작업지시 생성 완료</AlertDialogTitle>
            <AlertDialogDescription asChild>
              <div className="space-y-4 pt-2">
                <div className="flex items-center gap-2">
                  <CheckCircle2 className="h-5 w-5 text-green-600" />
                  <span className="font-medium text-foreground">
                    작업지시서가 자동 생성되었습니다.
                  </span>
                </div>
                <p className="text-muted-foreground">
                  작업지시 관리 페이지로 이동합니다.
                </p>
              </div>
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogAction onClick={handleSuccessDialogClose}>
              확인
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </PageLayout>
  );
}
