"use client";

import React, { useState, useEffect, useCallback, useMemo } from "react";
import { apiClient } from "@/lib/api/client";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { cn } from "@/lib/utils";
import { useMonitoringSettings } from "@/hooks/useMonitoringSettings";
import { getMonitoringTheme } from "@/lib/monitoringTheme";
import { useTabStore } from "@/stores/tabStore";
import type { ProductionDisplayFields } from "@/types/monitoringSettings";
import {
  RefreshCw,
  Clock,
  Loader2,
  Inbox,
  Timer,
  CheckCircle2,
  AlertTriangle,
  TrendingUp,
  Play,
  Pause,
  Settings2,
} from "lucide-react";

// ─── 타입 정의 ─────────────────────────────────────────────
interface WorkInstructionDetail {
  item_name?: string;
  spec?: string;
  customer_name?: string;
}

interface WorkInstruction {
  id: string;
  wi_id?: string;
  work_instruction_no: string;
  status: string; // 일반 / 긴급
  progress_status?: string; // 대기 / 진행중 / 완료
  qty: number;
  completed_qty: number;
  start_date: string | null;
  end_date: string | null;
  worker: string | null;
  equipment_id: string | null;
  equipment_name?: string | null;
  details?: WorkInstructionDetail[];
}

interface ProcessStep {
  wo_id: string;
  process_name: string;
  status: string; // acceptable / in_progress / completed
  seq_no: number;
  parent_process_id?: string | null;
}

type FilterTab = "전체" | "대기" | "진행중" | "완료";

// ─── 유틸리티 ──────────────────────────────────────────────
function formatDate(dateStr: string | null | undefined): string {
  if (!dateStr) return "-";
  try {
    const d = new Date(dateStr);
    const y = d.getFullYear();
    const m = String(d.getMonth() + 1).padStart(2, "0");
    const day = String(d.getDate()).padStart(2, "0");
    return `${y}-${m}-${day}`;
  } catch {
    return dateStr;
  }
}

function formatTime(date: Date): string {
  const h = String(date.getHours()).padStart(2, "0");
  const m = String(date.getMinutes()).padStart(2, "0");
  const s = String(date.getSeconds()).padStart(2, "0");
  return `${h}:${m}:${s}`;
}

// 작업지시 진행상태 계산: progress_status 우선, 없으면 공정현황으로 판단
function computeProgress(
  wi: WorkInstruction,
  processMap: Map<string, ProcessStep[]>,
): "대기" | "진행중" | "완료" {
  // 1) DB의 progress_status가 있으면 우선 사용
  const ps = wi.progress_status?.trim();
  if (ps) {
    if (["완료", "complete", "completed"].includes(ps.toLowerCase())) return "완료";
    if (["진행중", "진행", "in_progress", "inprogress", "processing"].includes(ps.toLowerCase())) return "진행중";
    if (["대기", "waiting", "pending"].includes(ps.toLowerCase())) return "대기";
  }

  // 2) 완료수량 기반 판단
  const totalQty = Number((wi as any).total_qty || wi.qty || 0);
  const completedQty = Number(wi.completed_qty || 0);
  if (totalQty > 0 && completedQty >= totalQty) return "완료";
  if (completedQty > 0) return "진행중";

  // 3) 공정현황 fallback
  const wiId = wi.wi_id || wi.id;
  const steps = processMap.get(String(wiId));
  if (!steps || steps.length === 0) return "대기";
  const completedCount = steps.filter((s) => s.status === "completed").length;
  const inProgressCount = steps.filter((s) => s.status === "in_progress").length;
  if (completedCount === steps.length) return "완료";
  if (completedCount > 0 || inProgressCount > 0) return "진행중";
  return "대기";
}

// ─── 메인 컴포넌트 ────────────────────────────────────────
export default function ProductionMonitoringPage() {
  const { settings } = useMonitoringSettings("production");
  const theme = getMonitoringTheme(settings.theme);
  const openTab = useTabStore((s) => s.openTab);

  const [workInstructions, setWorkInstructions] = useState<WorkInstruction[]>([]);
  const [processMap, setProcessMap] = useState<Map<string, ProcessStep[]>>(new Map());
  const [loading, setLoading] = useState(true);
  const [currentTime, setCurrentTime] = useState(new Date());
  const [autoRefresh, setAutoRefresh] = useState(settings.autoRefresh);
  const [activeTab, setActiveTab] = useState<FilterTab>("전체");

  // ─── 실시간 시계 ─────────────────────────────────────────
  useEffect(() => {
    const timer = setInterval(() => setCurrentTime(new Date()), 1000);
    return () => clearInterval(timer);
  }, []);

  // ─── 데이터 로드 ─────────────────────────────────────────
  const fetchData = useCallback(async () => {
    try {
      setLoading(true);

      // 작업지시 목록 조회
      const wiRes = await apiClient.get("/work-instruction/list");
      const wiRaw: WorkInstruction[] = wiRes.data?.success && Array.isArray(wiRes.data.data) ? wiRes.data.data : [];
      // 작업지시번호 기준 중복 제거 (디테일 JOIN으로 중복 발생 가능)
      const seen = new Set<string>();
      const wiData = wiRaw.filter((wi) => {
        const key = wi.work_instruction_no || wi.id;
        if (seen.has(key)) return false;
        seen.add(key);
        return true;
      });
      setWorkInstructions(wiData);

      // 공정현황 조회 (실패해도 작업지시는 표시)
      try {
        const procRes = await apiClient.post("/table-management/tables/work_order_process/data", {
          page: 1,
          size: 1000,
          autoFilter: true,
        });
        const rows: ProcessStep[] = procRes.data?.data?.data || procRes.data?.data?.rows || procRes.data?.data || [];

        // wo_id + seq_no 기준 그룹핑, 마스터/분할 행 통합하여 가장 높은 상태 반영
        const statusPriority = (s: string) => (s === "completed" ? 3 : s === "in_progress" ? 2 : s === "acceptable" ? 1 : 0);
        const rawMap = new Map<string, ProcessStep[]>();
        rows.forEach((row) => {
          const key = String(row.wo_id);
          if (!rawMap.has(key)) rawMap.set(key, []);
          rawMap.get(key)!.push(row);
        });

        const map = new Map<string, ProcessStep[]>();
        rawMap.forEach((steps, woId) => {
          // seq_no + process_name 기준으로 대표 1건 (마스터 행 기본, 분할 행의 높은 status 반영)
          const grouped = new Map<string, ProcessStep>();
          for (const s of steps) {
            const gk = `${s.seq_no}_${s.process_name}`;
            const existing = grouped.get(gk);
            if (!existing) {
              // 마스터 행 우선, 없으면 아무거나
              grouped.set(gk, { ...s });
            } else {
              // 더 높은 상태로 업데이트 (split 행이 in_progress/completed이면 반영)
              if (statusPriority(s.status) > statusPriority(existing.status)) {
                existing.status = s.status;
              }
            }
          }
          // parent_process_id 제거 (표시용 마스터 데이터)
          const deduped = Array.from(grouped.values())
            .map((s) => ({ ...s, parent_process_id: null }))
            .sort((a, b) => (a.seq_no ?? 0) - (b.seq_no ?? 0));
          map.set(woId, deduped);
        });
        setProcessMap(map);
      } catch {
        // 공정현황 조회 실패 → 빈 맵 유지
        setProcessMap(new Map());
      }
    } catch (err) {
      console.error("생산모니터링 데이터 조회 실패:", err);
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => {
    fetchData();
  }, [fetchData]);

  // ─── 자동갱신 ────────────────────────────────────────────
  useEffect(() => {
    if (!autoRefresh) return;
    const timer = setInterval(fetchData, settings.refreshInterval * 1000);
    return () => clearInterval(timer);
  }, [autoRefresh, fetchData, settings.refreshInterval]);

  // ─── 통계 계산 ───────────────────────────────────────────
  const stats = useMemo(() => {
    let waiting = 0;
    let inProgress = 0;
    let completed = 0;
    let totalQty = 0;
    let completedQty = 0;

    workInstructions.forEach((wi) => {
      const progress = computeProgress(wi, processMap);
      if (progress === "대기") waiting++;
      else if (progress === "진행중") inProgress++;
      else completed++;
      totalQty += Number((wi as any).total_qty || wi.qty || 0);
      completedQty += Number(wi.completed_qty) || 0;
    });

    const achievementRate = totalQty > 0 ? Math.round((completedQty / totalQty) * 100) : 0;

    return { waiting, inProgress, completed, achievementRate };
  }, [workInstructions, processMap]);

  // ─── 필터링된 작업 목록 ──────────────────────────────────
  const filteredInstructions = useMemo(() => {
    return workInstructions.filter((wi) => {
      if (activeTab === "전체") return true;
      const progress = computeProgress(wi, processMap);
      return progress === activeTab;
    });
  }, [workInstructions, processMap, activeTab]);

  // ─── 렌더링 ──────────────────────────────────────────────
  return (
    <div className={cn("flex h-full min-h-0 flex-col gap-4 overflow-auto p-4", theme.root)} style={theme.cssVars}>
      {/* 헤더 */}
      <div className="flex flex-shrink-0 items-center justify-between">
        <h1 className={cn("text-2xl font-bold", theme.headerText)}>생산모니터링</h1>
        <div className="flex items-center gap-3">
          <div className={cn("flex items-center gap-1.5 text-sm", theme.mutedText)}>
            <Clock className="h-4 w-4" />
            <span className="font-mono">{formatTime(currentTime)}</span>
          </div>
          <Button variant="outline" size="sm" onClick={fetchData} disabled={loading} className="gap-1.5">
            <RefreshCw className={cn("h-4 w-4", loading && "animate-spin")} />
            새로고침
          </Button>
          <Button
            variant={autoRefresh ? "default" : "outline"}
            size="sm"
            onClick={() => setAutoRefresh(!autoRefresh)}
            className="gap-1.5"
          >
            {autoRefresh ? <Pause className="h-4 w-4" /> : <Play className="h-4 w-4" />}
            자동갱신 {autoRefresh ? "ON" : "OFF"}
          </Button>
          <Button
            variant="outline"
            size="sm"
            onClick={() => openTab({ type: "admin", title: "모니터링 설정", adminUrl: "/monitoring/settings" })}
            className="gap-1.5"
          >
            <Settings2 className="h-4 w-4" />
            설정
          </Button>
        </div>
      </div>

      {/* 요약 카드 */}
      <div className="grid flex-shrink-0 grid-cols-4 gap-4">
        <SummaryCard
          icon={<Timer className="h-5 w-5" />}
          label="대기중"
          value={stats.waiting}
          colorClass="text-amber-500 bg-amber-500/10 border-amber-500/20"
        />
        <SummaryCard
          icon={<Loader2 className="h-5 w-5" />}
          label="진행중"
          value={stats.inProgress}
          colorClass="text-blue-500 bg-blue-500/10 border-blue-500/20"
        />
        <SummaryCard
          icon={<CheckCircle2 className="h-5 w-5" />}
          label="완료"
          value={stats.completed}
          colorClass="text-emerald-500 bg-emerald-500/10 border-emerald-500/20"
        />
        <SummaryCard
          icon={<TrendingUp className="h-5 w-5" />}
          label="달성율"
          value={`${stats.achievementRate}%`}
          colorClass="text-purple-500 bg-purple-500/10 border-purple-500/20"
        />
      </div>

      {/* 탭 필터 */}
      <div className="flex flex-shrink-0 items-center gap-2">
        {(["전체", "대기", "진행중", "완료"] as FilterTab[]).map((tab) => (
          <Button
            key={tab}
            variant={activeTab === tab ? "default" : "outline"}
            size="sm"
            onClick={() => setActiveTab(tab)}
            className={cn(
              "min-w-[64px]",
              activeTab === tab && tab === "대기" && "bg-amber-500 text-white hover:bg-amber-600",
              activeTab === tab && tab === "진행중" && "bg-blue-500 text-white hover:bg-blue-600",
              activeTab === tab && tab === "완료" && "bg-emerald-500 text-white hover:bg-emerald-600",
            )}
          >
            {tab}
            {tab === "전체" && ` (${workInstructions.length})`}
            {tab === "대기" && ` (${stats.waiting})`}
            {tab === "진행중" && ` (${stats.inProgress})`}
            {tab === "완료" && ` (${stats.completed})`}
          </Button>
        ))}
      </div>

      {/* 로딩 상태 */}
      {loading && workInstructions.length === 0 && (
        <div className="text-muted-foreground flex flex-col items-center justify-center py-20">
          <Loader2 className="mb-3 h-10 w-10 animate-spin" />
          <span className="text-sm">데이터를 불러오는 중입니다...</span>
        </div>
      )}

      {/* 빈 상태 */}
      {!loading && filteredInstructions.length === 0 && (
        <div className="text-muted-foreground flex flex-col items-center justify-center py-20">
          <Inbox className="mb-3 h-12 w-12" />
          <span className="text-sm">
            {activeTab === "전체" ? "등록된 작업지시가 없습니다." : `"${activeTab}" 상태의 작업지시가 없습니다.`}
          </span>
        </div>
      )}

      {/* 작업 카드 */}
      {filteredInstructions.length > 0 && (
        <div
          className={cn(
            "flex-1 gap-4",
            settings.layout === "grid" && "grid",
            settings.layout === "list" && "flex flex-col",
            settings.layout === "split" && "grid grid-cols-2",
          )}
          style={
            settings.layout === "grid" ? { gridTemplateColumns: "repeat(auto-fill, minmax(420px, 1fr))" } : undefined
          }
        >
          {filteredInstructions.map((wi, idx) => (
            <WorkCard
              key={wi.id || `wi-${idx}`}
              instruction={wi}
              steps={processMap.get(wi.wi_id || wi.id) || []}
              progress={computeProgress(wi, processMap)}
              displayFields={settings.displayFields}
            />
          ))}
        </div>
      )}
    </div>
  );
}

// ─── 요약 카드 ─────────────────────────────────────────────
function SummaryCard({
  icon,
  label,
  value,
  colorClass,
}: {
  icon: React.ReactNode;
  label: string;
  value: number | string;
  colorClass: string;
}) {
  return (
    <div className="bg-card flex items-center gap-4 rounded-lg border p-4">
      <div className={cn("rounded-lg border p-2.5", colorClass)}>{icon}</div>
      <div className="flex flex-col">
        <span className="text-muted-foreground text-xs">{label}</span>
        <span className="text-foreground text-2xl font-bold">{value}</span>
      </div>
    </div>
  );
}

// ─── 작업 카드 ─────────────────────────────────────────────
function WorkCard({
  instruction: wi,
  steps,
  progress,
  displayFields: df,
}: {
  instruction: WorkInstruction;
  steps: ProcessStep[];
  progress: "대기" | "진행중" | "완료";
  displayFields: ProductionDisplayFields;
}) {
  // API 응답은 flat 구조 (details 배열 아님)
  const itemName = (wi as any).item_name || "-";
  const spec = (wi as any).item_spec || "-";
  const customerName = (wi as any).customer_name || "-";

  // 진척률 (total_qty 또는 qty)
  const totalQty = Number((wi as any).total_qty || wi.qty || 0);
  const completedQty = Number(wi.completed_qty || 0);
  const progressPercent = totalQty > 0 ? Math.min(100, Math.round((completedQty / totalQty) * 100)) : 0;

  // 공정 현황 계산
  const completedSteps = steps.filter((s) => s.status === "completed").length;
  const currentStep = steps.find((s) => s.status === "in_progress") || steps.find((s) => s.status !== "completed");

  // 프로그레스바 색상
  const barColor = progressPercent >= 100 ? "bg-emerald-500" : progressPercent >= 50 ? "bg-blue-500" : "bg-amber-500";

  // 상태 배지 스타일
  const statusBadge: Record<string, string> = {
    대기: "bg-amber-500/10 text-amber-500 border-amber-500/30",
    진행중: "bg-blue-500/10 text-blue-500 border-blue-500/30",
    완료: "bg-emerald-500/10 text-emerald-500 border-emerald-500/30",
  };

  const isUrgent = wi.status === "긴급";

  return (
    <div className="bg-card flex flex-col overflow-hidden rounded-lg border">
      {/* 카드 헤더 */}
      <div className="bg-muted/30 flex items-center justify-between border-b px-4 py-3">
        <div className="flex items-center gap-2">
          {df.workInstructionNo && (
            <span className="text-foreground text-sm font-semibold">{wi.work_instruction_no}</span>
          )}
          {df.priority && isUrgent && (
            <Badge variant="outline" className="gap-1 border-red-500/30 bg-red-500/10 text-xs text-red-500">
              <AlertTriangle className="h-3 w-3" />
              긴급
            </Badge>
          )}
        </div>
        <Badge variant="outline" className={cn("text-xs", statusBadge[progress])}>
          {progress}
        </Badge>
      </div>

      {/* 카드 본문 - 정보 */}
      <div className="grid grid-cols-2 gap-x-4 gap-y-1.5 border-b px-4 py-3 text-sm">
        {df.itemName && <InfoRow label="품목명" value={itemName} />}
        {df.spec && <InfoRow label="규격" value={spec} />}
        {df.customerName && <InfoRow label="거래처" value={customerName} />}
        {df.worker && <InfoRow label="작업자" value={wi.worker || "-"} />}
        {df.dueDate && <InfoRow label="납기일" value={formatDate(wi.end_date)} />}
        {df.equipment && <InfoRow label="설비" value={wi.equipment_name || wi.equipment_id || "-"} />}
        {df.salesOrderNo && <InfoRow label="수주번호" value={(wi as any).sales_order_no || "-"} />}
        {df.quantityInfo && <InfoRow label="수량" value={`${completedQty} / ${totalQty}`} />}
      </div>

      {/* 공정현황 */}
      {df.processProgress && (
        <div className="border-b px-4 py-3">
          <div className="mb-2 flex items-center justify-between">
            <span className="text-muted-foreground text-xs font-medium">공정현황</span>
            {steps.length > 0 && (
              <span className="text-muted-foreground text-xs">
                완료 {completedSteps}/{steps.length}
                {currentStep && (
                  <span>
                    {" "}
                    · 현재: <span className="text-blue-400">{currentStep.process_name}</span>
                  </span>
                )}
              </span>
            )}
          </div>
          {steps.length > 0 ? (
            <div className="flex flex-wrap items-center gap-1">
              {steps.map((step, idx) => {
                const isDone = step.status === "completed";
                const isInProgress = step.status === "in_progress";
                const isCurrent = isInProgress || (!isDone && idx === completedSteps);
                return (
                  <React.Fragment key={`${step.wo_id}-${step.seq_no}-${idx}`}>
                    {idx > 0 && (
                      <span className={cn("text-xs", isDone || isCurrent ? "text-emerald-400/60" : "text-muted-foreground/40")}>→</span>
                    )}
                    <span
                      className={cn(
                        "rounded px-2 py-0.5 text-xs font-medium transition-all",
                        isDone && "bg-emerald-500/20 text-emerald-400",
                        isCurrent && "animate-pulse bg-blue-500/20 text-blue-400",
                        !isDone && !isCurrent && "bg-muted text-muted-foreground",
                      )}
                    >
                      {step.process_name}
                    </span>
                  </React.Fragment>
                );
              })}
            </div>
          ) : (
            <span className="text-muted-foreground text-xs">공정 정보 없음</span>
          )}
        </div>
      )}

      {/* 프로그레스바 */}
      {df.progressBar && (
        <div className="px-4 py-3">
          <div className="mb-1.5 flex items-center justify-between">
            <span className="text-muted-foreground text-xs">
              {completedQty} / {totalQty}
            </span>
            <span
              className={cn(
                "text-xs font-bold",
                progressPercent >= 100
                  ? "text-emerald-500"
                  : progressPercent >= 50
                    ? "text-blue-500"
                    : "text-amber-500",
              )}
            >
              {progressPercent}%
            </span>
          </div>
          <div className="bg-muted h-2.5 w-full overflow-hidden rounded-full">
            <div
              className={cn("h-full rounded-full transition-all duration-500", barColor)}
              style={{ width: `${progressPercent}%` }}
            />
          </div>
        </div>
      )}
    </div>
  );
}

// ─── 정보 행 ───────────────────────────────────────────────
function InfoRow({ label, value }: { label: string; value: string }) {
  return (
    <div className="flex min-w-0 items-center gap-1.5">
      <span className="text-muted-foreground shrink-0">{label}:</span>
      <span className="text-foreground truncate">{value}</span>
    </div>
  );
}
