"use client";

/**
 * OrderRegistDialog — wace orderRegistFormPopup.jsp 1:1 이식
 *
 * 견적요청에서 시작된 행(is_direct_order != 'Y')의 "수주등록/수정" 폼.
 * 통합폼(estimateAndOrderRegistFormPopup)과 분리된 별도 화면.
 *
 * - 헤더 4개: 발주번호 / 발주일* / 견적환종 / 견적환율
 * - 라인: contract_item 자동 로드(읽기전용), ORDER_* 5컬럼만 입력
 * - 라인 추가/삭제 불가
 * - 자동계산: 수량×단가→공급가액, 공급가액×10%→부가세, 공급+부가세→총액
 */

import { useEffect, useMemo, useState } from "react";
import {
  Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle,
} 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 { CommCodeSelect } from "@/components/common/CommCodeSelect";
import { salesOrderMgmtApi, OrderBody, OrderItem } from "@/lib/api/salesOrderMgmt";
import { toast } from "sonner";

export interface OrderRegistDialogProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  contractObjId: string | null;
  contractNo: string | null;
  onSaved?: () => void;
}

const toNum = (v: any) => Number(String(v ?? "0").replace(/,/g, "")) || 0;

export function OrderRegistDialog({ open, onOpenChange, contractObjId, contractNo, onSaved }: OrderRegistDialogProps) {
  const [loading, setLoading] = useState(false);
  const [saving, setSaving] = useState(false);
  const [form, setForm] = useState<OrderBody>({ contract_currency: "KRW", items: [] });

  useEffect(() => {
    if (!open || !contractObjId) return;
    let cancelled = false;
    (async () => {
      setLoading(true);
      try {
        const detail = await salesOrderMgmtApi.detail(contractObjId);
        if (cancelled || !detail) return;
        setForm({
          objid: detail.objid,
          contract_no: detail.contract_no ?? "",
          category_cd: detail.category_cd ?? "",
          customer_objid: detail.customer_objid ?? "",
          product: detail.product ?? "",
          area_cd: detail.area_cd ?? "",
          paid_type: detail.paid_type ?? "paid",
          contract_currency: detail.contract_currency ?? "KRW",
          exchange_rate: detail.exchange_rate ?? "",
          receipt_date: detail.receipt_date ?? "",
          order_date: detail.order_date ?? new Date().toISOString().slice(0, 10),
          approval_required: detail.approval_required ?? "N",
          is_direct_order: detail.is_direct_order ?? "",
          req_del_date: detail.req_del_date ?? "",
          po_no: detail.po_no ?? "",
          contract_result: detail.contract_result ?? "",
          pm_user_id: detail.pm_user_id ?? "",
          customer_request: detail.customer_request ?? "",
          shipping_method: detail.shipping_method ?? "",
          incoterms: detail.incoterms ?? "",
          items: (detail.items ?? []).map((it: any) => ({
            objid: it.objid,
            seq: it.seq,
            product: it.product ?? "",
            part_objid: it.part_objid ?? "",
            part_no: it.master_part_no ?? it.part_no ?? "",
            part_name: it.master_part_name ?? it.part_name ?? "",
            quantity: it.quantity ?? 1,
            due_date: it.due_date ?? "",
            return_reason: it.return_reason ?? "",
            customer_request: it.customer_request ?? "",
            order_quantity: it.order_quantity ?? "",
            order_unit_price: it.order_unit_price ?? "",
            order_supply_price: it.order_supply_price ?? "",
            order_vat: it.order_vat ?? "",
            order_total_amount: it.order_total_amount ?? "",
            cancel_qty: it.cancel_qty ?? "",
            serials: it.serials ?? [],
          })),
        });
      } catch (err: any) {
        toast.error(`수주등록 폼 로드 실패: ${err?.response?.data?.message ?? err.message}`);
      } finally {
        if (!cancelled) setLoading(false);
      }
    })();
    return () => { cancelled = true; };
  }, [open, contractObjId]);

  // wace fn_calculateItemAmount / fn_calculateTotalFromVat 이식
  const updateItemWithCalc = (idx: number, key: keyof OrderItem, val: any) => {
    setForm((prev) => {
      const items = [...(prev.items ?? [])];
      const cur: any = { ...items[idx], [key]: val };
      if (key === "order_quantity" || key === "order_unit_price") {
        const supply = toNum(cur.order_quantity) * toNum(cur.order_unit_price);
        const vat = Math.round(supply * 0.1);
        cur.order_supply_price = String(supply);
        cur.order_vat = String(vat);
        cur.order_total_amount = String(supply + vat);
      } else if (key === "order_vat") {
        cur.order_total_amount = String(toNum(cur.order_supply_price) + toNum(cur.order_vat));
      }
      items[idx] = cur;
      return { ...prev, items };
    });
  };

  const formatNum = (v: any) => {
    const n = Number(String(v ?? "0").replace(/,/g, ""));
    return isNaN(n) ? 0 : n;
  };
  const lineTotal = useMemo(() => {
    const items = form.items ?? [];
    return items.reduce((acc, it) => ({
      qty:    acc.qty    + formatNum(it.order_quantity),
      supply: acc.supply + formatNum(it.order_supply_price),
      vat:    acc.vat    + formatNum(it.order_vat),
      total:  acc.total  + formatNum(it.order_total_amount),
    }), { qty: 0, supply: 0, vat: 0, total: 0 });
  }, [form.items]);

  const handleSave = async () => {
    if (!contractObjId) return;
    if (!form.order_date) { toast.warning("발주일을 입력해주세요."); return; }
    // wace fn_save 검증: 라인별 제품구분 + 수주수량
    for (const it of (form.items ?? [])) {
      if (!it.product) { toast.warning("제품구분을 선택해주세요."); return; }
      const oq = toNum(it.order_quantity);
      if (!oq || oq <= 0) { toast.warning("수주수량을 입력해주세요."); return; }
    }
    setSaving(true);
    try {
      await salesOrderMgmtApi.update(contractObjId, form);
      toast.success("수주등록이 저장되었습니다.");
      onOpenChange(false);
      onSaved?.();
    } catch (err: any) {
      toast.error(`저장 실패: ${err?.response?.data?.message ?? err.message}`);
    } finally {
      setSaving(false);
    }
  };

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent
        className="!max-w-[90vw] w-[90vw] max-h-[92vh] overflow-y-auto"
        onInteractOutside={(e) => e.preventDefault()}
      >
        <DialogHeader>
          <DialogTitle>
            영업관리 _ 주문서관리 _ 수주등록 (영업번호: {contractNo ?? "-"})
          </DialogTitle>
          <DialogDescription className="sr-only">
            견적요청에서 시작된 행의 수주등록 폼 (wace orderRegistFormPopup 1:1)
          </DialogDescription>
        </DialogHeader>

        {loading ? (
          <div className="flex items-center justify-center py-10">
            <Loader2 className="w-5 h-5 animate-spin mr-2" /> 로드 중...
          </div>
        ) : (
          <>
            {/* 수주 기본정보 — wace 헤더 4개 */}
            <fieldset className="border rounded-md p-3">
              <legend className="text-sm font-semibold px-2">수주 기본정보</legend>
              <div className="grid grid-cols-4 gap-3">
                <div>
                  <Label className="text-xs">발주번호</Label>
                  <Input value={form.po_no ?? ""}
                         onChange={(e) => setForm({ ...form, po_no: e.target.value })} />
                </div>
                <div>
                  <Label className="text-xs">발주일 <span className="text-rose-600">*</span></Label>
                  <Input type="date" value={form.order_date ?? ""}
                         onChange={(e) => setForm({ ...form, order_date: e.target.value })} />
                </div>
                <div>
                  <Label className="text-xs">견적환종</Label>
                  <CommCodeSelect groupId="0001533" value={form.contract_currency ?? ""}
                    onValueChange={(v) => setForm({ ...form, contract_currency: v })} />
                </div>
                <div>
                  <Label className="text-xs">견적환율</Label>
                  <Input value={form.exchange_rate ?? ""}
                         onChange={(e) => setForm({ ...form, exchange_rate: e.target.value })} />
                </div>
              </div>
            </fieldset>

            {/* 품목정보 — 견적요청에서 자동 로드 (라인 추가/삭제 불가) */}
            <fieldset className="border rounded-md p-3 mt-3">
              <legend className="text-sm font-semibold px-2">품목정보 (견적요청에서 자동 로드)</legend>
              <div className="overflow-x-auto">
                <table className="w-full text-xs">
                  <thead className="bg-muted/50">
                    <tr>
                      <th className="p-2 w-10 whitespace-nowrap">No</th>
                      <th className="p-2 w-28 whitespace-nowrap">제품구분 <span className="text-rose-600">*</span></th>
                      <th className="p-2 w-32 whitespace-nowrap">품번</th>
                      <th className="p-2 w-48 whitespace-nowrap">품명</th>
                      <th className="p-2 w-36 whitespace-nowrap">S/N</th>
                      <th className="p-2 w-24 whitespace-nowrap text-right">수주수량 <span className="text-rose-600">*</span></th>
                      <th className="p-2 w-28 whitespace-nowrap text-right">수주단가</th>
                      <th className="p-2 w-32 whitespace-nowrap text-right">수주공급가액</th>
                      <th className="p-2 w-28 whitespace-nowrap text-right">수주부가세</th>
                      <th className="p-2 w-32 whitespace-nowrap text-right">수주총액</th>
                      <th className="p-2 w-12 whitespace-nowrap text-center">-</th>
                    </tr>
                  </thead>
                  <tbody>
                    {(form.items ?? []).map((it, idx) => {
                      const serials = (it.serials ?? []) as string[];
                      const snDisplay = serials.length > 1
                        ? `${serials[0]} 외 ${serials.length - 1}개`
                        : (serials[0] ?? "");
                      return (
                        <tr key={idx} className="border-t">
                          <td className="p-1 text-center">{it.seq}</td>
                          <td className="p-1">
                            <CommCodeSelect groupId="0000001"
                              value={it.product ?? ""}
                              onValueChange={(v) => {
                                setForm((prev) => {
                                  const items = [...(prev.items ?? [])];
                                  items[idx] = { ...items[idx], product: v };
                                  return { ...prev, items };
                                });
                              }} />
                          </td>
                          <td className="p-1">
                            <Input className="h-8 bg-muted/30" readOnly value={it.part_no ?? ""} />
                          </td>
                          <td className="p-1">
                            <Input className="h-8 bg-muted/30" readOnly value={it.part_name ?? ""} />
                          </td>
                          <td className="p-1">
                            <Input className="h-8 bg-muted/30" readOnly title={serials.join(", ")} value={snDisplay} />
                          </td>
                          <td className="p-1">
                            <Input className="h-8 text-right" type="number" min={0}
                                   value={it.order_quantity ?? ""}
                                   onChange={(e) => updateItemWithCalc(idx, "order_quantity", e.target.value)} />
                          </td>
                          <td className="p-1">
                            <Input className="h-8 text-right" value={it.order_unit_price ?? ""}
                                   onChange={(e) => updateItemWithCalc(idx, "order_unit_price", e.target.value)} />
                          </td>
                          <td className="p-1">
                            <Input className="h-8 text-right bg-muted/30" readOnly value={it.order_supply_price ?? ""} />
                          </td>
                          <td className="p-1">
                            <Input className="h-8 text-right" value={it.order_vat ?? ""}
                                   onChange={(e) => updateItemWithCalc(idx, "order_vat", e.target.value)} />
                          </td>
                          <td className="p-1">
                            <Input className="h-8 text-right bg-muted/30" readOnly value={it.order_total_amount ?? ""} />
                          </td>
                          <td className="p-1 text-center text-muted-foreground">-</td>
                        </tr>
                      );
                    })}
                    {(!form.items || form.items.length === 0) && (
                      <tr><td colSpan={11} className="p-6 text-center text-muted-foreground">견적요청에 등록된 품목이 없습니다.</td></tr>
                    )}
                  </tbody>
                  {(form.items?.length ?? 0) > 0 && (
                    <tfoot>
                      <tr className="bg-muted/30 font-semibold">
                        <td colSpan={5} className="p-2 text-center">Total</td>
                        <td className="p-2 text-right">{lineTotal.qty.toLocaleString()}</td>
                        <td className="p-2"></td>
                        <td className="p-2 text-right">{lineTotal.supply.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}</td>
                        <td className="p-2 text-right">{lineTotal.vat.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}</td>
                        <td className="p-2 text-right">{lineTotal.total.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}</td>
                        <td className="p-2"></td>
                      </tr>
                    </tfoot>
                  )}
                </table>
              </div>
            </fieldset>
          </>
        )}

        <DialogFooter>
          <Button variant="outline" onClick={() => onOpenChange(false)} disabled={saving}>닫기</Button>
          <Button onClick={handleSave} disabled={saving || loading}>
            {saving ? <Loader2 className="w-4 h-4 mr-1 animate-spin" /> : <Save className="w-4 h-4 mr-1" />}저장
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}
