"use client";

// 생산관리 > M-BOM 관리 — BOM 할당 다이얼로그 (PR-B5).
//
// 운영판 mBomEbomSelectPopup.jsp (324 lines) 1:1 재구성.
// 레이아웃 (상→하):
//   1) 헤더: "E-BOM 선택" 또는 "E-BOM 상세 및 변경" + 닫기/변경 토글
//   2) 현재 할당된 E-BOM 정보 카드 (할당된 경우만, 2×3 table)
//   3) 리스트 섹션 (할당 안 됐거나 변경 토글 ON 일 때 표시):
//      - 검색폼: 제품구분(select) + 품번 + 품명 + 등록일(범위)
//      - 헤더: "E-BOM List (상태: Y)" + 우측 [조회][E-BOM 할당] 버튼
//      - 그리드 (제품구분/품번/품명/Ver/등록일/작성자)
//   4) 미리보기: 선택한 E-BOM 의 트리 (운영판 iframe → 직접 렌더)
//
// (M-BOM 할당은 PR-B5 v2 — 우선 E-BOM 만)

import React, { useEffect, useMemo, useState } from "react";
import {
  Dialog, DialogContent, DialogHeader, DialogTitle,
} from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Loader2, Search, Link as LinkIcon, Eye, RefreshCw, Folder } from "lucide-react";
import { toast } from "sonner";
import { cn } from "@/lib/utils";
import { mbomApi, AssignableEbomRow, MbomTreeResponse, MbomTreeRow } from "@/lib/api/mbom";
import { SmartSelect, SmartSelectOption } from "@/components/common/SmartSelect";
import { apiClient } from "@/lib/api/client";

const PARENT_PRODUCT = "0000001"; // 제품구분 comm_code parent (운영 동일)

interface Props {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  projectObjid: string | null;
  currentEbomObjid?: string | null;             // 이미 할당된 E-BOM (있으면 상단 카드 표시)
  onAssigned: () => void;
}

export function MbomAssignDialog({
  open, onOpenChange, projectObjid, currentEbomObjid, onAssigned,
}: Props) {
  // 현재 할당된 E-BOM 의 상세 정보 (objid 로 검색해서 자체 로드)
  const [currentEbom, setCurrentEbom] = useState<AssignableEbomRow | null>(null);
  // 검색 폼
  const [filter, setFilter] = useState({
    product_cd: "", search_part_no: "", search_part_name: "",
    search_from_date: "", search_to_date: "",
  });
  const [productOpts, setProductOpts] = useState<SmartSelectOption[]>([]);

  // 리스트 / 선택
  const [rows, setRows] = useState<AssignableEbomRow[]>([]);
  const [loading, setLoading] = useState(false);
  const [selectedRow, setSelectedRow] = useState<AssignableEbomRow | null>(null);

  // 미리보기 트리
  const [preview, setPreview] = useState<MbomTreeResponse | null>(null);
  const [previewLoading, setPreviewLoading] = useState(false);

  // 변경 모드 토글 — 할당된 경우 false 가 디폴트, 변경 버튼 클릭 시 true
  const [changeMode, setChangeMode] = useState(false);

  const isAssigned = !!currentEbom;
  const showList = !isAssigned || changeMode;

  // 제품구분 옵션 로드
  useEffect(() => {
    if (!open) return;
    apiClient.get(`/sales/codes/${PARENT_PRODUCT}`)
      .then(r => setProductOpts(r.data?.data ?? []))
      .catch(() => { /* 옵션 실패 무시 */ });
  }, [open]);

  const search = (override?: Partial<typeof filter>) => {
    const f = { ...filter, ...override };
    setLoading(true);
    mbomApi.searchAssignableEboms(f)
      .then(setRows)
      .catch((e: any) => toast.error(e?.response?.data?.message ?? e?.message ?? "E-BOM 조회 실패"))
      .finally(() => setLoading(false));
  };

  // 다이얼로그 오픈/리셋
  useEffect(() => {
    if (!open) {
      setRows([]); setSelectedRow(null); setPreview(null);
      setChangeMode(false); setCurrentEbom(null);
      setFilter({ product_cd: "", search_part_no: "", search_part_name: "", search_from_date: "", search_to_date: "" });
      return;
    }
    // 현재 할당된 E-BOM 상세 로드
    if (currentEbomObjid) {
      mbomApi.searchAssignableEboms({ objid: currentEbomObjid, limit: 1 })
        .then(r => setCurrentEbom(r[0] ?? null))
        .catch(() => setCurrentEbom(null));
    } else {
      // 할당 안 된 경우: 리스트 자동 조회
      search();
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [open, currentEbomObjid]);

  // 변경 모드 진입 시 리스트 자동 조회
  useEffect(() => {
    if (changeMode) search();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [changeMode]);

  // 미리보기 — 선택 변경 시 트리 로드
  useEffect(() => {
    if (!selectedRow?.objid) { setPreview(null); return; }
    let alive = true;
    setPreviewLoading(true);
    mbomApi.previewEbomTree(selectedRow.objid)
      .then(t => { if (alive) setPreview(t); })
      .catch((e: any) => toast.error(e?.response?.data?.message ?? e?.message ?? "미리보기 실패"))
      .finally(() => { if (alive) setPreviewLoading(false); });
    return () => { alive = false; };
  }, [selectedRow?.objid]);

  const handleAssign = async () => {
    if (!projectObjid) return;
    if (!selectedRow?.objid) { toast.error("E-BOM 한 건을 선택해주세요"); return; }
    if (selectedRow.objid === currentEbom?.objid) {
      toast.info("현재 할당된 E-BOM 과 동일합니다");
      return;
    }
    if (!window.confirm(isAssigned
        ? `선택한 E-BOM(${selectedRow.part_no}) 으로 변경하시겠습니까?`
        : `선택한 E-BOM(${selectedRow.part_no}) 을 할당하시겠습니까?`)) return;
    try {
      await mbomApi.assignBom({
        project_obj_id: projectObjid,
        source_bom_type: "EBOM",
        source_bom_obj_id: selectedRow.objid,
      });
      toast.success(isAssigned ? "E-BOM 이 변경되었습니다" : "E-BOM 이 할당되었습니다");
      onAssigned();
      onOpenChange(false);
    } catch (e: any) {
      toast.error(e?.response?.data?.message ?? e?.message ?? "할당 실패");
    }
  };

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="max-w-[1200px] w-[97vw] max-h-[92vh] flex flex-col p-0 overflow-hidden">
        <DialogHeader className="bg-blue-600 px-4 py-3">
          <DialogTitle className="text-white flex items-center gap-2">
            <LinkIcon className="w-4 h-4" />
            {isAssigned ? "E-BOM 상세 및 변경" : "E-BOM 선택"}
            {isAssigned && !changeMode && (
              <Button
                size="sm" variant="secondary" className="ml-auto h-7"
                onClick={() => setChangeMode(true)}
              >
                <RefreshCw className="w-3 h-3 mr-1" />
                E-BOM 변경
              </Button>
            )}
          </DialogTitle>
        </DialogHeader>

        <div className="flex-1 min-h-0 overflow-auto">
          {/* 1. 현재 할당된 E-BOM 정보 카드 */}
          {isAssigned && currentEbom && (
            <div className="border-b bg-emerald-50/50 dark:bg-emerald-950/20 px-4 py-3">
              <div className="text-xs font-semibold mb-2 flex items-center gap-1">
                📋 현재 할당된 E-BOM 정보
              </div>
              <table className="text-xs w-full max-w-[800px]">
                <tbody>
                  <tr>
                    <th className="bg-muted/50 px-2 py-1 text-left w-[100px]">제품구분</th>
                    <td className="px-2 py-1">{currentEbom.product_name ?? ""}</td>
                    <th className="bg-muted/50 px-2 py-1 text-left w-[80px]">품번</th>
                    <td className="px-2 py-1 font-medium">{currentEbom.part_no ?? ""}</td>
                  </tr>
                  <tr>
                    <th className="bg-muted/50 px-2 py-1 text-left">품명</th>
                    <td className="px-2 py-1">{currentEbom.part_name ?? ""}</td>
                    <th className="bg-muted/50 px-2 py-1 text-left">Version</th>
                    <td className="px-2 py-1">{currentEbom.revision ?? ""}</td>
                  </tr>
                  <tr>
                    <th className="bg-muted/50 px-2 py-1 text-left">등록일</th>
                    <td className="px-2 py-1 tabular-nums">{currentEbom.reg_date ?? ""}</td>
                    <th className="bg-muted/50 px-2 py-1 text-left">작성자</th>
                    <td className="px-2 py-1">{currentEbom.dept_name ?? ""} / {currentEbom.writer_name ?? ""}</td>
                  </tr>
                </tbody>
              </table>
              {!changeMode && (
                <p className="text-xs text-muted-foreground mt-2">
                  다른 E-BOM 으로 변경하려면 우상단 <strong>"E-BOM 변경"</strong> 버튼을 클릭하세요.
                </p>
              )}
            </div>
          )}

          {/* 2. 리스트 섹션 (검색 + 그리드) */}
          {showList && (
            <div className="border-b">
              {/* 검색 폼 */}
              <div className="grid grid-cols-[80px_1fr_80px_1fr_80px_1fr_80px_1fr] gap-x-3 gap-y-2 px-4 py-3 items-center text-xs bg-muted/30 border-b">
                <label className="text-right">제품구분</label>
                <SmartSelect
                  options={productOpts}
                  value={filter.product_cd}
                  onValueChange={(v) => setFilter({ ...filter, product_cd: v })}
                />
                <label className="text-right">품번</label>
                <Input className="h-7 text-xs"
                  value={filter.search_part_no}
                  onChange={(e) => setFilter({ ...filter, search_part_no: e.target.value })}
                  onKeyDown={(e) => { if (e.key === "Enter") search(); }} />
                <label className="text-right">품명</label>
                <Input className="h-7 text-xs"
                  value={filter.search_part_name}
                  onChange={(e) => setFilter({ ...filter, search_part_name: e.target.value })}
                  onKeyDown={(e) => { if (e.key === "Enter") search(); }} />
                <label className="text-right">등록일</label>
                <div className="flex items-center gap-1">
                  <Input type="date" className="h-7 text-xs w-[140px]"
                    value={filter.search_from_date}
                    onChange={(e) => setFilter({ ...filter, search_from_date: e.target.value })} />
                  <span>~</span>
                  <Input type="date" className="h-7 text-xs w-[140px]"
                    value={filter.search_to_date}
                    onChange={(e) => setFilter({ ...filter, search_to_date: e.target.value })} />
                </div>
              </div>

              {/* 리스트 헤더 + 액션 버튼 (운영판: 버튼이 리스트 우상단) */}
              <div className="flex items-center justify-between px-4 py-2 bg-muted/10 border-b">
                <h3 className="text-sm font-semibold">E-BOM List <span className="text-xs text-muted-foreground">(상태: Y · 최대 100건 · 총 {rows.length}건)</span></h3>
                <div className="flex gap-2">
                  <Button size="sm" variant="outline" onClick={() => search()} disabled={loading}>
                    {loading ? <Loader2 className="w-3 h-3 mr-1 animate-spin" /> : <Search className="w-3 h-3 mr-1" />}
                    조회
                  </Button>
                  <Button
                    size="sm"
                    className="bg-emerald-600 hover:bg-emerald-700 text-white"
                    onClick={handleAssign}
                    disabled={!selectedRow}
                  >
                    <LinkIcon className="w-3 h-3 mr-1" />
                    E-BOM {isAssigned ? "변경" : "할당"}
                  </Button>
                </div>
              </div>

              {/* 그리드 */}
              <div className="max-h-[320px] overflow-auto">
                <table className="text-xs border-collapse w-full">
                  <thead className="bg-yellow-100 dark:bg-yellow-900/30 sticky top-0">
                    <tr>
                      <th className="border px-2 py-1.5 w-[36px] text-center">선택</th>
                      <th className="border px-2 py-1.5 w-[100px] text-center">제품구분</th>
                      <th className="border px-2 py-1.5 w-[150px] text-left">품번</th>
                      <th className="border px-2 py-1.5 text-left">품명</th>
                      <th className="border px-2 py-1.5 w-[70px]  text-center">Ver</th>
                      <th className="border px-2 py-1.5 w-[100px] text-center">등록일</th>
                      <th className="border px-2 py-1.5 w-[140px] text-center">작성자</th>
                    </tr>
                  </thead>
                  <tbody>
                    {loading && rows.length === 0 ? (
                      <tr><td colSpan={7} className="py-12 text-center"><Loader2 className="inline w-5 h-5 animate-spin" /></td></tr>
                    ) : rows.length === 0 ? (
                      <tr><td colSpan={7} className="py-8 text-center text-muted-foreground">조회된 E-BOM 이 없습니다.</td></tr>
                    ) : rows.map(r => {
                      const isSel = selectedRow?.objid === r.objid;
                      const isCurrent = currentEbom?.objid === r.objid;
                      return (
                        <tr key={r.objid}
                            className={cn("cursor-pointer hover:bg-muted/30",
                              isSel && "bg-blue-100 dark:bg-blue-950/40",
                              !isSel && isCurrent && "bg-emerald-50 dark:bg-emerald-950/20")}
                            onClick={() => setSelectedRow(r)}>
                          <td className="border px-2 py-1 text-center">
                            <input type="radio" checked={isSel} onChange={() => setSelectedRow(r)} />
                          </td>
                          <td className="border px-2 py-1 text-center">{r.product_name ?? ""}</td>
                          <td className="border px-2 py-1 whitespace-nowrap">
                            {r.part_no}
                            {isCurrent && <span className="ml-1 text-[10px] text-emerald-600">(현재)</span>}
                          </td>
                          <td className="border px-2 py-1">{r.part_name}</td>
                          <td className="border px-2 py-1 text-center">{r.revision ?? ""}</td>
                          <td className="border px-2 py-1 text-center tabular-nums">{r.reg_date ?? ""}</td>
                          <td className="border px-2 py-1 text-center">
                            {r.dept_name && r.writer_name
                              ? `${r.dept_name}/${r.writer_name}`
                              : (r.writer_name ?? "")}
                          </td>
                        </tr>
                      );
                    })}
                  </tbody>
                </table>
              </div>
            </div>
          )}

          {/* 3. 미리보기 트리 */}
          {selectedRow && (
            <div className="p-3">
              <div className="text-xs font-semibold mb-2 flex items-center gap-1">
                <Eye className="w-3 h-3" />
                E-BOM 미리보기 (읽기 전용) — {selectedRow.part_no} / {selectedRow.part_name}
              </div>
              <div className="border rounded max-h-[320px] overflow-auto">
                {previewLoading ? (
                  <div className="flex h-32 items-center justify-center"><Loader2 className="w-5 h-5 animate-spin" /></div>
                ) : (
                  <PreviewTree tree={preview} />
                )}
              </div>
            </div>
          )}
        </div>
      </DialogContent>
    </Dialog>
  );
}

// 미리보기 트리 — 운영판 iframe 대체. 간단한 read-only 표시.
function PreviewTree({ tree }: { tree: MbomTreeResponse | null }) {
  const maxLevel = Math.max(1, tree?.max_level ?? 1);
  const rows: MbomTreeRow[] = tree?.rows ?? [];
  const levels = useMemo(() => Array.from({ length: maxLevel }, (_, i) => i + 1), [maxLevel]);

  if (rows.length === 0) {
    return <div className="py-6 text-center text-xs text-muted-foreground">미리보기 트리가 비어있습니다.</div>;
  }
  return (
    <table className="text-xs border-collapse w-full">
      <thead className="bg-muted sticky top-0">
        <tr>
          {levels.map((lv) => (
            <th key={`l${lv}`} className="border px-1 py-1 w-[30px] text-center font-bold">{lv}</th>
          ))}
          <th className="border px-2 py-1 min-w-[120px] text-left">품번</th>
          <th className="border px-2 py-1 min-w-[180px] text-left">품명</th>
          <th className="border px-2 py-1 w-[60px]  text-right">수량</th>
          <th className="border px-2 py-1 w-[60px]  text-center">단위</th>
          <th className="border px-2 py-1 w-[40px]  text-center">3D</th>
          <th className="border px-2 py-1 w-[40px]  text-center">2D</th>
          <th className="border px-2 py-1 w-[40px]  text-center">PDF</th>
        </tr>
      </thead>
      <tbody>
        {rows.map((r, idx) => {
          const lv = Number(r.level ?? 1);
          return (
            <tr key={`${r.objid}_${idx}`} className="hover:bg-muted/30">
              {levels.map(i => (
                <td key={`lc${i}`} className={cn("border px-1 py-0.5 text-center", i === lv && "font-bold")}>
                  {i === lv ? "*" : ""}
                </td>
              ))}
              <td className="border px-2 py-0.5 whitespace-nowrap">{r.part_no}</td>
              <td className="border px-2 py-0.5">{r.part_name}</td>
              <td className="border px-2 py-0.5 text-right tabular-nums">{r.qty ?? ""}</td>
              <td className="border px-2 py-0.5 text-center">{r.unit_title ?? r.unit ?? ""}</td>
              <td className="border px-2 py-0.5 text-center"><FolderMini n={r.cu01_cnt} /></td>
              <td className="border px-2 py-0.5 text-center"><FolderMini n={r.cu02_cnt} /></td>
              <td className="border px-2 py-0.5 text-center"><FolderMini n={r.cu03_cnt} /></td>
            </tr>
          );
        })}
      </tbody>
    </table>
  );
}

function FolderMini({ n }: { n: any }) {
  const has = Number(n ?? 0) > 0;
  return (
    <Folder className={cn("inline w-3.5 h-3.5",
      has ? "fill-[#1a73e8] text-[#1a73e8]" : "fill-white text-muted-foreground/40")} />
  );
}
