"use client";

import React, { useState, useEffect, useRef } from "react";
import { useRouter } from "next/navigation";
import { usePopCompanyPath } from "@/hooks/usePopCompanyPath";
import { SupplierModal, type Supplier, type PartnerSourceConfig } from "../../_components/inbound/SupplierModal";
import { EquipmentModal, type EquipmentItem } from "../../_components/common/EquipmentModal";
import { getProcessEquipments } from "@/lib/api/processInfo";
import { useProcessData } from "../../_components/production/useProcessData";
import { WorkOrderList } from "../../_components/production/WorkOrderList";

/* ------------------------------------------------------------------ */
/* Types                                                               */
/* ------------------------------------------------------------------ */

type ColsKey = 1 | 2 | 3;

/** process_mng 테이블 소스 설정 — SupplierModal에 전달하여 공정 목록 조회 */
const PROCESS_SOURCE: PartnerSourceConfig = {
  tableName: "process_mng",
  fields: {
    code: "process_code",
    name: "process_name",
  },
};

/* ------------------------------------------------------------------ */
/* Static Data                                                         */
/* ------------------------------------------------------------------ */

const COLS_OPTIONS: ColsKey[] = [1, 2, 3];
/** 신규 POP 전용 카드 열 localStorage 키 (구 POP `workorder-card-cols`와 독립) */
const POP_NEW_COLS_KEY = "pop-new-workorder-cols";
/** 신규 POP 공정실행 목록 상태 sessionStorage 키 (라우트 이동 후 복원) */
const POP_NEW_PROD_STATE_KEY = "pop-new-production-process-state";
const DEFAULT_COLS: ColsKey = 2;

/* ------------------------------------------------------------------ */
/* Page                                                                */
/* ------------------------------------------------------------------ */

export default function ProductionProcessPage() {
  const router = useRouter();
  const companyPath = usePopCompanyPath();

  /* 카드 열 수 (localStorage 연동) */
  const [cols, setCols] = useState<ColsKey>(DEFAULT_COLS);
  useEffect(() => {
    try {
      const saved = localStorage.getItem(POP_NEW_COLS_KEY);
      if (saved) {
        const n = parseInt(saved, 10) as ColsKey;
        if (COLS_OPTIONS.includes(n)) setCols(n);
      }
    } catch {
      // ignore
    }
  }, []);
  const handleSetCols = (n: ColsKey) => {
    setCols(n);
    try {
      localStorage.setItem(POP_NEW_COLS_KEY, String(n));
    } catch {
      // ignore
    }
  };

  /* 필터 상태 */
  const [selectedProcess, setSelectedProcess] = useState<Supplier | null>(null);
  const [processModalOpen, setProcessModalOpen] = useState(false);
  const [selectedEquipment, setSelectedEquipment] = useState<EquipmentItem | null>(null);
  const [equipmentModalOpen, setEquipmentModalOpen] = useState(false);
  const [equipments, setEquipments] = useState<EquipmentItem[]>([]);
  const [equipmentLoading, setEquipmentLoading] = useState(false);

  /* 마운트 시 selectedProcess 복원 (selectedEquipment는 equipments 로딩 완료 후 2단계 복원) */
  useEffect(() => {
    try {
      const saved = sessionStorage.getItem(POP_NEW_PROD_STATE_KEY);
      if (!saved) return;
      const parsed = JSON.parse(saved);
      if (parsed.selectedProcess && parsed.selectedProcess.customer_code) {
        setSelectedProcess(parsed.selectedProcess as Supplier);
      }
    } catch {
      // ignore
    }
  }, []);

  /* selectedProcess 변경 시 sessionStorage 머지 저장 */
  useEffect(() => {
    try {
      const existing = JSON.parse(
        sessionStorage.getItem(POP_NEW_PROD_STATE_KEY) || "{}",
      );
      sessionStorage.setItem(
        POP_NEW_PROD_STATE_KEY,
        JSON.stringify({ ...existing, selectedProcess }),
      );
    } catch {
      // ignore
    }
  }, [selectedProcess]);

  /* selectedEquipment 변경 시 sessionStorage 머지 저장 */
  useEffect(() => {
    try {
      const existing = JSON.parse(
        sessionStorage.getItem(POP_NEW_PROD_STATE_KEY) || "{}",
      );
      sessionStorage.setItem(
        POP_NEW_PROD_STATE_KEY,
        JSON.stringify({ ...existing, selectedEquipment }),
      );
    } catch {
      // ignore
    }
  }, [selectedEquipment]);

  /* equipments 로딩 완료 후 selectedEquipment 1회 복원 */
  const equipRestoredRef = useRef(false);
  useEffect(() => {
    if (equipRestoredRef.current) return;
    if (equipmentLoading) return;
    if (equipments.length === 0) return;
    try {
      const saved = sessionStorage.getItem(POP_NEW_PROD_STATE_KEY);
      if (saved) {
        const parsed = JSON.parse(saved);
        const savedEq = parsed.selectedEquipment as EquipmentItem | null;
        if (savedEq && savedEq.id) {
          const found = equipments.find((e) => e.id === savedEq.id);
          if (found) setSelectedEquipment(found);
        }
      }
    } catch {
      // ignore
    }
    equipRestoredRef.current = true;
  }, [equipmentLoading, equipments]);

  /* 공정 변경 시 해당 공정 등록 설비 조회 */
  useEffect(() => {
    if (!selectedProcess?.customer_code) {
      setEquipments([]);
      setSelectedEquipment(null);
      return;
    }
    let cancelled = false;
    setEquipmentLoading(true);
    getProcessEquipments(selectedProcess.customer_code)
      .then((res) => {
        if (cancelled) return;
        if (res.success && Array.isArray(res.data)) {
          const list: EquipmentItem[] = res.data.map((e) => ({
            id: String(e.id ?? ""),
            equipment_code: String(e.equipment_code ?? ""),
            equipment_name: String(e.equipment_name ?? e.equipment_code ?? ""),
          }));
          setEquipments(list);
        } else {
          setEquipments([]);
        }
        setSelectedEquipment(null);
      })
      .finally(() => {
        if (!cancelled) setEquipmentLoading(false);
      });
    return () => { cancelled = true; };
  }, [selectedProcess?.customer_code]);

  const equipmentDisabled = !selectedProcess;

  /* 데이터 훅 — 진입 시 1회 sync, refresh/refetch 제공 */
  const {
    instructions,
    allProcesses,
    processList,
    equipmentList,
    itemNameMap,
    itemTypeMap,
    loading,
    syncing,
    refresh,
    refetch,
  } = useProcessData();

  /* WorkOrderList용 문자열 필터값 ("__all__" 또는 code) */
  const selectedProcessCode = selectedProcess?.customer_code || "__all__";
  const selectedEquipmentCode = selectedEquipment?.equipment_code || "__all__";

  return (
    <div className="flex flex-col gap-4">
      {/* ===== Back + Title ===== */}
      <div className="flex items-center gap-3">
        <button
          onClick={() => router.push(companyPath("/pop/production"))}
          className="w-10 h-10 rounded-xl bg-white border border-gray-200 flex items-center justify-center text-gray-500 hover:bg-gray-50 active:scale-95 transition-all"
        >
          <svg className="w-5 h-5" fill="none" stroke="currentColor" strokeWidth={2} viewBox="0 0 24 24">
            <path strokeLinecap="round" strokeLinejoin="round" d="M15.75 19.5L8.25 12l7.5-7.5" />
          </svg>
        </button>
        <h1 className="text-xl sm:text-2xl font-bold text-gray-900 tracking-tight">공정실행</h1>
      </div>

      {/* ===== Top Row: Card Cols + Refresh ===== */}
      <div className="flex items-center justify-between">
        <div className="flex items-center gap-2">
          <span className="text-sm font-medium text-gray-600">카드 열:</span>
          <div className="flex items-center gap-1">
            {COLS_OPTIONS.map((c) => (
              <button
                key={c}
                onClick={() => handleSetCols(c)}
                className={`w-10 h-10 rounded-lg text-sm font-semibold transition-all active:scale-95 ${
                  cols === c
                    ? "bg-blue-500 text-white shadow-sm"
                    : "bg-white text-gray-700 border border-gray-200 hover:bg-gray-50"
                }`}
              >
                {c}열
              </button>
            ))}
          </div>
        </div>
        <button
          onClick={refresh}
          disabled={syncing}
          className="flex items-center gap-2 px-4 h-10 rounded-lg bg-white border border-blue-300 text-blue-600 text-sm font-semibold hover:bg-blue-50 active:scale-95 transition-all disabled:opacity-50"
        >
          <svg
            className={`w-4 h-4 ${syncing ? "animate-spin" : ""}`}
            fill="none"
            stroke="currentColor"
            strokeWidth={2}
            viewBox="0 0 24 24"
          >
            <path
              strokeLinecap="round"
              strokeLinejoin="round"
              d="M16.023 9.348h4.992v-.001M2.985 19.644v-4.992m0 0h4.992m-4.993 0l3.181 3.183a8.25 8.25 0 0013.803-3.7M4.031 9.865a8.25 8.25 0 0113.803-3.7l3.181 3.182m0-4.991v4.99"
            />
          </svg>
          <span>{syncing ? "동기화중..." : "새로고침"}</span>
        </button>
      </div>

      {/* ===== Filter Row: Process + Equipment ===== */}
      <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
        <button
          onClick={() => setProcessModalOpen(true)}
          className="flex items-center gap-2 h-14 px-4 bg-white border border-gray-200 rounded-xl text-left hover:bg-gray-50 active:scale-[0.99] transition-all"
        >
          <svg className="w-5 h-5 text-gray-500" fill="none" stroke="currentColor" strokeWidth={1.8} viewBox="0 0 24 24">
            <path strokeLinecap="round" strokeLinejoin="round" d="M9.594 3.94c.09-.542.56-.94 1.11-.94h2.593c.55 0 1.02.398 1.11.94l.213 1.281c.063.374.313.686.645.87.074.04.147.083.22.127.324.196.72.257 1.075.124l1.217-.456a1.125 1.125 0 011.37.49l1.296 2.247a1.125 1.125 0 01-.26 1.431l-1.003.827c-.293.24-.438.613-.431.992a6.759 6.759 0 010 .255c-.007.378.138.75.43.99l1.005.828c.424.35.534.954.26 1.43l-1.298 2.247a1.125 1.125 0 01-1.369.491l-1.217-.456c-.355-.133-.75-.072-1.076.124a6.57 6.57 0 01-.22.128c-.331.183-.581.495-.644.869l-.213 1.28c-.09.543-.56.941-1.11.941h-2.594c-.55 0-1.02-.398-1.11-.94l-.213-1.281c-.062-.374-.312-.686-.644-.87a6.52 6.52 0 01-.22-.127c-.325-.196-.72-.257-1.076-.124l-1.217.456a1.125 1.125 0 01-1.369-.49l-1.297-2.247a1.125 1.125 0 01.26-1.431l1.004-.827c.292-.24.437-.613.43-.992a6.932 6.932 0 010-.255c.007-.378-.138-.75-.43-.99l-1.004-.828a1.125 1.125 0 01-.26-1.43l1.297-2.247a1.125 1.125 0 011.37-.491l1.216.456c.356.133.751.072 1.076-.124.072-.044.146-.087.22-.128.332-.183.582-.495.644-.869l.214-1.281z" />
            <path strokeLinecap="round" strokeLinejoin="round" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
          </svg>
          <span className={`flex-1 text-sm ${selectedProcess ? "text-gray-900 font-semibold" : "text-gray-400"}`}>
            {selectedProcess ? selectedProcess.customer_name : "공정을 선택하세요"}
          </span>
          <svg className="w-5 h-5 text-gray-400 shrink-0" fill="none" stroke="currentColor" strokeWidth={2} viewBox="0 0 24 24">
            <path strokeLinecap="round" strokeLinejoin="round" d="M19.5 8.25l-7.5 7.5-7.5-7.5" />
          </svg>
        </button>
        <button
          onClick={() => { if (!equipmentDisabled) setEquipmentModalOpen(true); }}
          disabled={equipmentDisabled}
          className={`flex items-center gap-2 h-14 px-4 bg-white border border-gray-200 rounded-xl text-left transition-all ${
            equipmentDisabled
              ? "opacity-60 cursor-not-allowed"
              : "hover:bg-gray-50 active:scale-[0.99]"
          }`}
        >
          <svg className="w-5 h-5 text-gray-500" fill="none" stroke="currentColor" strokeWidth={1.8} viewBox="0 0 24 24">
            <path strokeLinecap="round" strokeLinejoin="round" d="M3 3v1.5M3 21v-6m0 0l2.77-.693a9 9 0 016.208.682l.108.054a9 9 0 006.086.71l3.114-.732a48.524 48.524 0 01-.005-10.499l-3.11.732a9 9 0 01-6.085-.711l-.108-.054a9 9 0 00-6.208-.682L3 4.5M3 15V4.5" />
          </svg>
          <span className={`flex-1 text-sm ${selectedEquipment ? "text-gray-900 font-semibold" : "text-gray-400"}`}>
            {selectedEquipment
              ? selectedEquipment.equipment_name
              : equipmentDisabled
              ? "공정 선택 후 설비 선택"
              : "설비를 선택하세요"}
          </span>
          <svg className="w-5 h-5 text-gray-400 shrink-0" fill="none" stroke="currentColor" strokeWidth={2} viewBox="0 0 24 24">
            <path strokeLinecap="round" strokeLinejoin="round" d="M19.5 8.25l-7.5 7.5-7.5-7.5" />
          </svg>
        </button>
      </div>

      {/* ===== Work Order List (복사된 구 POP 컴포넌트, 플랜 A-2b로 props 리팩터됨) ===== */}
      <WorkOrderList
        instructions={instructions}
        allProcesses={allProcesses}
        processList={processList}
        equipmentList={equipmentList}
        itemNameMap={itemNameMap}
        itemTypeMap={itemTypeMap}
        loading={loading}
        selectedProcess={selectedProcessCode}
        selectedEquipment={selectedEquipmentCode}
        cardCols={cols}
        refetch={refetch}
      />

      {/* ===== Process Selection Modal ===== */}
      <SupplierModal
        open={processModalOpen}
        onClose={() => setProcessModalOpen(false)}
        onSelect={(s) => setSelectedProcess(s)}
        source={PROCESS_SOURCE}
        title="공정 선택"
        searchPlaceholder="공정명 또는 코드 검색..."
      />

      {/* ===== Equipment Selection Modal ===== */}
      <EquipmentModal
        open={equipmentModalOpen}
        onClose={() => setEquipmentModalOpen(false)}
        onSelect={(e) => setSelectedEquipment(e)}
        items={equipments}
        loading={equipmentLoading}
        title="설비 선택"
        searchPlaceholder="설비명 또는 코드 검색..."
      />
    </div>
  );
}
