"use client";

// 개발관리 > E-BOM 상태 변경 다이얼로그 — wace structureStatusChangePopup.jsp 1:1
//
// 운영 매퍼 updateStructureStatus 5필드 UPDATE :
//   PRODUCT_CD / PART_NO / PART_NAME / REVISION / STATUS (모두 편집 가능)
// 상태는 Y / N 라디오 (운영판 그대로).
//
// 이전 구현은 read-only 요약 박스 + 상태 select(create/changeDesign/deploy) 였으나
// 운영판과 완전히 달라 정정.

import React, { useEffect, useState } from "react";
import {
  Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter,
} from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Loader2, Save } from "lucide-react";
import { toast } from "sonner";
import { CommCodeSelect } from "@/components/common/CommCodeSelect";
import { devBomApi, BomReportRow } from "@/lib/api/devBom";

const PRODUCT_GROUP = "0000001"; // 제품구분 comm_code

interface Props {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  objid: string | null;
  onSaved: () => void;
}

export function BomReportStatusDialog({ open, onOpenChange, objid, onSaved }: Props) {
  const [productCd, setProductCd] = useState<string>("");
  const [partNo, setPartNo] = useState<string>("");
  const [partName, setPartName] = useState<string>("");
  const [version, setVersion] = useState<string>("");
  const [status, setStatus] = useState<string>("");  // 운영판 Y / N
  const [loading, setLoading] = useState(false);
  const [saving, setSaving] = useState(false);

  useEffect(() => {
    if (!open || !objid) return;
    let alive = true;
    setLoading(true);
    devBomApi.detail(objid)
      .then((data: BomReportRow | null) => {
        if (!alive) return;
        if (!data) {
          toast.error("E-BOM 보고서를 찾을 수 없습니다.");
          onOpenChange(false);
          return;
        }
        setProductCd(data.product_cd ?? "");
        setPartNo(data.part_no ?? "");
        setPartName(data.part_name ?? "");
        setVersion(data.revision ?? "");
        setStatus(data.status ?? "");
      })
      .catch((e: any) => {
        toast.error(e?.response?.data?.message ?? e?.message ?? "조회 실패");
        onOpenChange(false);
      })
      .finally(() => { if (alive) setLoading(false); });
    return () => { alive = false; };
  }, [open, objid, onOpenChange]);

  // wace fn_check 1:1 — 제품구분 / 품번 필수, 상태 필수
  const validate = (): string | null => {
    if (!productCd) return "제품구분은 필수입니다.";
    if (!partNo.trim()) return "품번은 필수입니다.";
    if (!status) return "상태를 선택하세요.";
    return null;
  };

  const handleSave = async () => {
    if (!objid) return;
    const err = validate();
    if (err) return toast.error(err);
    setSaving(true);
    try {
      await devBomApi.updateStatus(objid, {
        product_cd: productCd,
        part_no: partNo,
        part_name: partName,
        version: version || undefined,
        status,
      });
      toast.success("상태가 변경되었습니다.");
      onSaved();
      onOpenChange(false);
    } catch (e: any) {
      toast.error(e?.response?.data?.message ?? e?.message ?? "저장 실패");
    } finally {
      setSaving(false);
    }
  };

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="max-w-md p-0 overflow-hidden">
        <DialogHeader className="bg-blue-600 px-4 py-3">
          <DialogTitle className="text-white">E-BOM 상태 변경</DialogTitle>
        </DialogHeader>

        {loading ? (
          <div className="flex h-48 items-center justify-center">
            <Loader2 className="h-6 w-6 animate-spin" />
          </div>
        ) : (
          <div className="px-4 py-3">
            {/* 운영판 colgroup 1:1 (25% / 75%) */}
            <table className="w-full border-collapse text-sm table-fixed">
              <colgroup>
                <col style={{ width: "25%" }} />
                <col />
              </colgroup>
              <tbody>
                <tr>
                  <Th>제품구분<Req /></Th>
                  <Td>
                    <CommCodeSelect groupId={PRODUCT_GROUP} withAll={false}
                                    value={productCd}
                                    onValueChange={setProductCd} />
                  </Td>
                </tr>
                <tr>
                  <Th>품번<Req /></Th>
                  <Td><Input value={partNo} onChange={(e) => setPartNo(e.target.value)} /></Td>
                </tr>
                <tr>
                  <Th>품명</Th>
                  <Td><Input value={partName} onChange={(e) => setPartName(e.target.value)} /></Td>
                </tr>
                <tr>
                  <Th>Version</Th>
                  <Td><Input value={version} onChange={(e) => setVersion(e.target.value)} /></Td>
                </tr>
                <tr>
                  <Th>상태</Th>
                  <Td>
                    <div className="flex items-center gap-6">
                      <label className="flex items-center gap-1.5 cursor-pointer">
                        <input type="radio" name="status" value="Y"
                               checked={status === "Y"}
                               onChange={() => setStatus("Y")} />
                        <span>Y</span>
                      </label>
                      <label className="flex items-center gap-1.5 cursor-pointer">
                        <input type="radio" name="status" value="N"
                               checked={status === "N"}
                               onChange={() => setStatus("N")} />
                        <span>N</span>
                      </label>
                    </div>
                  </Td>
                </tr>
              </tbody>
            </table>
          </div>
        )}

        <DialogFooter className="border-t bg-muted/20 px-4 py-3 sm:justify-center">
          <Button onClick={handleSave} disabled={saving || loading}>
            {saving ? <Loader2 className="h-4 w-4 animate-spin" /> : <Save className="h-4 w-4" />}
            <span className="ml-1">저장</span>
          </Button>
          <Button variant="outline" onClick={() => onOpenChange(false)} disabled={saving}>
            닫기
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}

function Th({ children }: { children: React.ReactNode }) {
  return (
    <th className="border bg-muted/30 px-3 py-2 text-left align-middle font-medium">
      {children}
    </th>
  );
}
function Td({ children }: { children: React.ReactNode }) {
  return <td className="border px-3 py-1.5">{children}</td>;
}
function Req() {
  return <span className="ml-1 text-red-500">*</span>;
}
