"use client";

// 자재관리 > 자재리스트 — 재고등록(입고) 다이얼로그
// wace 1:1: inventoryFormPopUp.jsp / saveinventoryForm.do
//   1) inventory_mgmt 동일 (project+unit+part+location) 행 존재 시 재사용, 없으면 INSERT
//   2) inventory_mgmt_in 입고 라인 1건 INSERT

import React, { useEffect, useMemo, useState } from "react";
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter, DialogDescription } from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { Label } from "@/components/ui/label";
import { Save, X } from "lucide-react";
import { toast } from "sonner";
import { SmartSelect } from "@/components/common/SmartSelect";
import { NumberInput } from "@/components/common/NumberInput";
import { DateInput } from "@/components/common/DateInput";
import { Input } from "@/components/ui/input";
import { inventoryMngApi, OptionItem } from "@/lib/api/inventoryMng";

interface Props {
  open: boolean;
  onClose: () => void;
  onSaved: () => void;
}

interface FormState {
  project_objid: string;
  unit: string;
  part_objid: string;
  part_no: string;
  part_name: string;
  qty: number | "";
  price: string;
  location: string;
  sub_location: string;
  receipt_date: string;
}

const EMPTY: FormState = {
  project_objid: "", unit: "", part_objid: "",
  part_no: "", part_name: "",
  qty: "", price: "", location: "", sub_location: "",
  receipt_date: new Date().toISOString().slice(0, 10),
};

export function StockRegisterDialog({ open, onClose, onSaved }: Props) {
  const [form, setForm] = useState<FormState>(EMPTY);
  const [projectOpts, setProjectOpts] = useState<OptionItem[]>([]);
  const [unitOpts, setUnitOpts] = useState<OptionItem[]>([]);
  const [partKw, setPartKw] = useState("");
  const [partOpts, setPartOpts] = useState<OptionItem[]>([]);
  const [saving, setSaving] = useState(false);

  useEffect(() => {
    if (!open) return;
    setForm(EMPTY);
    setPartKw("");
    setPartOpts([]);
    (async () => {
      try { setProjectOpts(await inventoryMngApi.projects()); } catch { /* skip */ }
    })();
  }, [open]);

  useEffect(() => {
    if (!form.project_objid) { setUnitOpts([]); return; }
    (async () => {
      try { setUnitOpts(await inventoryMngApi.units(form.project_objid)); } catch { /* skip */ }
    })();
  }, [form.project_objid]);

  useEffect(() => {
    const id = setTimeout(async () => {
      if (!partKw || partKw.length < 1) { setPartOpts([]); return; }
      try { setPartOpts(await inventoryMngApi.parts(partKw, 30)); } catch { /* skip */ }
    }, 250);
    return () => clearTimeout(id);
  }, [partKw]);

  const partSelectOpts = useMemo(
    () => partOpts.map((p) => ({ code: p.code, label: `${p.label} ${p.part_name ? `· ${p.part_name}` : ""}` })),
    [partOpts],
  );

  const handleSave = async () => {
    if (!form.project_objid) return toast.info("프로젝트를 선택해주세요.");
    if (!form.part_objid)    return toast.info("품번을 선택해주세요.");
    if (form.qty === "" || Number(form.qty) <= 0) return toast.info("수량을 입력해주세요.");
    if (!form.location)      return toast.info("Location 을 입력해주세요.");
    setSaving(true);
    try {
      await inventoryMngApi.saveStock({
        project_objid: form.project_objid,
        unit: form.unit,
        part_objid: form.part_objid,
        qty: Number(form.qty),
        price: form.price,
        location: form.location,
        sub_location: form.sub_location,
        receipt_date: form.receipt_date,
      });
      toast.success("재고가 등록되었습니다.");
      onSaved();
      onClose();
    } catch (e: any) {
      toast.error(e?.response?.data?.message ?? e?.message ?? "저장 실패");
    } finally {
      setSaving(false);
    }
  };

  return (
    <Dialog open={open} onOpenChange={(v) => !v && onClose()}>
      <DialogContent className="max-w-2xl">
        <DialogHeader>
          <DialogTitle>재고 등록</DialogTitle>
          <DialogDescription>자재 마스터에 입고분을 추가합니다.</DialogDescription>
        </DialogHeader>

        <div className="grid grid-cols-2 gap-3 text-xs">
          <div className="space-y-1">
            <Label>프로젝트 *</Label>
            <SmartSelect options={projectOpts} value={form.project_objid}
              onValueChange={(v) => setForm({ ...form, project_objid: v, unit: "" })} />
          </div>
          <div className="space-y-1">
            <Label>유닛(WBS)</Label>
            <SmartSelect options={unitOpts} value={form.unit}
              onValueChange={(v) => setForm({ ...form, unit: v })} />
          </div>
          <div className="space-y-1 col-span-2">
            <Label>품번 검색</Label>
            <Input placeholder="품번/품명 일부 입력"
              value={partKw}
              onChange={(e) => setPartKw(e.target.value)} />
            <SmartSelect options={partSelectOpts} value={form.part_objid}
              onValueChange={(v) => {
                const found = partOpts.find((p) => p.code === v);
                setForm({
                  ...form,
                  part_objid: v,
                  part_no: found?.label ?? "",
                  part_name: found?.part_name ?? "",
                });
              }} />
            {form.part_no && (
              <div className="text-[11px] text-muted-foreground">
                선택: <b>{form.part_no}</b> {form.part_name ? `· ${form.part_name}` : ""}
              </div>
            )}
          </div>
          <div className="space-y-1">
            <Label>수량 *</Label>
            <NumberInput value={form.qty} onChange={(v) => setForm({ ...form, qty: v })} />
          </div>
          <div className="space-y-1">
            <Label>단가</Label>
            <Input value={form.price} onChange={(e) => setForm({ ...form, price: e.target.value })} />
          </div>
          <div className="space-y-1">
            <Label>Location *</Label>
            <Input value={form.location} onChange={(e) => setForm({ ...form, location: e.target.value })} />
          </div>
          <div className="space-y-1">
            <Label>Sub Location</Label>
            <Input value={form.sub_location} onChange={(e) => setForm({ ...form, sub_location: e.target.value })} />
          </div>
          <div className="space-y-1">
            <Label>입고일</Label>
            <DateInput value={form.receipt_date} onChange={(v) => setForm({ ...form, receipt_date: v })} />
          </div>
        </div>

        <DialogFooter>
          <Button size="sm" variant="ghost" onClick={onClose} disabled={saving}>
            <X className="h-3.5 w-3.5 mr-1" /> 취소
          </Button>
          <Button size="sm" onClick={handleSave} disabled={saving}>
            <Save className="h-3.5 w-3.5 mr-1" /> {saving ? "저장중..." : "저장"}
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}
