"use client";

import { useState, useEffect, Suspense, useCallback } from "react";
import { useSearchParams } from "next/navigation";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { SearchableCodeSelect } from "@/components/ui/searchable-code-select";
import Swal from "sweetalert2";

const CHARGER_TYPE_CODE = "0000329";

interface Charger {
  rowKey: string;
  OBJID?: string;
  charger_type: string;
  charger_name: string;
  phone: string;
  tel: string;
  fax: string;
  email: string;
}

function SupplyForm() {
  const searchParams = useSearchParams();
  const objid = searchParams.get("objid") || "";
  const isNew = !objid;

  const [form, setForm] = useState<Record<string, string>>({});
  const [chargers, setChargers] = useState<Charger[]>([]);
  const [loading, setLoading] = useState(false);
  const set = (k: string, v: string) => setForm((p) => ({ ...p, [k]: v }));

  const newKey = () => Math.random().toString(36).slice(2, 10) + Date.now();

  const loadDetail = useCallback(async () => {
    if (!objid) return;
    const res = await fetch("/api/admin/supply/detail", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ objid }),
    });
    const json = await res.json();
    if (json.success && json.info) {
      const info = json.info as Record<string, unknown>;
      setForm({
        objid: String(info.OBJID || ""),
        supply_code: String(info.SUPPLY_CODE || ""),
        supply_name: String(info.SUPPLY_NAME || ""),
        area_cd: String(info.AREA_CD || ""),
        charge_user_name: String(info.CHARGE_USER_NAME || ""),
        bus_reg_no: String(info.BUS_REG_NO || ""),
        reg_no: String(info.REG_NO || ""),
        supply_busname: String(info.SUPPLY_BUSNAME || ""),
        supply_stockname: String(info.SUPPLY_STOCKNAME || ""),
        supply_address: String(info.SUPPLY_ADDRESS || ""),
        supply_tel_no: String(info.SUPPLY_TEL_NO || ""),
        email: String(info.EMAIL || ""),
        office_no: String(info.OFFICE_NO || ""),
        supply_fax_no: String(info.SUPPLY_FAX_NO || ""),
      });
      const rows = (json.chargers || []) as Record<string, unknown>[];
      setChargers(
        rows.map((r) => ({
          rowKey: newKey(),
          OBJID: String(r.OBJID || ""),
          charger_type: String(r.CHARGER_TYPE || ""),
          charger_name: String(r.CHARGER_NAME || ""),
          phone: String(r.PHONE || ""),
          tel: String(r.TEL || ""),
          fax: String(r.FAX || ""),
          email: String(r.EMAIL || ""),
        }))
      );
    }
  }, [objid]);

  useEffect(() => { loadDetail(); }, [loadDetail]);

  const addCharger = () => {
    setChargers((prev) => [
      ...prev,
      { rowKey: newKey(), charger_type: "", charger_name: "", phone: "", tel: "", fax: "", email: "" },
    ]);
  };

  const removeCharger = (rowKey: string) => {
    setChargers((prev) => prev.filter((c) => c.rowKey !== rowKey));
  };

  const updateCharger = (rowKey: string, field: keyof Charger, value: string) => {
    setChargers((prev) => prev.map((c) => (c.rowKey === rowKey ? { ...c, [field]: value } : c)));
  };

  const handleSave = async () => {
    if (!form.supply_name) {
      Swal.fire("알림", "고객명을 입력하세요.", "warning");
      return;
    }
    const r = await Swal.fire({
      title: "저장하시겠습니까?",
      icon: "question",
      showCancelButton: true,
      confirmButtonText: "저장",
      cancelButtonText: "취소",
    });
    if (!r.isConfirmed) return;
    setLoading(true);
    try {
      const res = await fetch("/api/admin/supply/save", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ ...form, objid: isNew ? "" : objid, chargers }),
      });
      const data = await res.json();
      if (data.success) {
        await Swal.fire({ icon: "success", title: data.message || "저장되었습니다.", timer: 1200, showConfirmButton: false });
        if (window.opener) try { window.opener.location.reload(); } catch {}
        window.close();
      } else {
        Swal.fire("오류", data.message || "저장 실패", "error");
      }
    } catch {
      Swal.fire("오류", "서버 오류", "error");
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="p-4 bg-gray-50 min-h-screen">
      <h2 className="text-base font-bold text-gray-800 mb-3 flex items-center gap-1">
        <span className="text-blue-500">●</span> 공급업체 등록/수정
      </h2>

      <div className="flex gap-4">
        {/* 좌: 공급업체 정보 */}
        <section className="w-[340px] shrink-0 bg-white border rounded p-3">
          <h4 className="text-sm font-bold text-gray-700 mb-2 border-b pb-1">공급업체 정보</h4>
          <table className="w-full text-xs">
            <tbody>
              <FieldRow label="구분">
                <SearchableCodeSelect codeId="0000167" value={form.supply_code || ""} onChange={(v) => set("supply_code", v)} className="[&_input]:h-7" />
              </FieldRow>
              <FieldRow label="고객명" required>
                <Input className="h-7" value={form.supply_name || ""} onChange={(e) => set("supply_name", e.target.value)} />
              </FieldRow>
              <FieldRow label="지역">
                <SearchableCodeSelect codeId="0000172" value={form.area_cd || ""} onChange={(v) => set("area_cd", v)} className="[&_input]:h-7" />
              </FieldRow>
              <FieldRow label="대표자명">
                <Input className="h-7" value={form.charge_user_name || ""} onChange={(e) => set("charge_user_name", e.target.value)} />
              </FieldRow>
              <FieldRow label="사업자등록번호">
                <Input className="h-7" value={form.bus_reg_no || ""} onChange={(e) => set("bus_reg_no", e.target.value)} />
              </FieldRow>
              <FieldRow label="법인/주민번호">
                <Input className="h-7" value={form.reg_no || ""} onChange={(e) => set("reg_no", e.target.value)} />
              </FieldRow>
              <FieldRow label="업태">
                <Input className="h-7" value={form.supply_busname || ""} onChange={(e) => set("supply_busname", e.target.value)} />
              </FieldRow>
              <FieldRow label="업종">
                <Input className="h-7" value={form.supply_stockname || ""} onChange={(e) => set("supply_stockname", e.target.value)} />
              </FieldRow>
              <FieldRow label="주소">
                <textarea
                  value={form.supply_address || ""}
                  onChange={(e) => set("supply_address", e.target.value)}
                  className="w-full h-12 rounded border border-gray-300 bg-white px-2 py-1 text-xs resize-none"
                />
              </FieldRow>
              <FieldRow label="핸드폰">
                <Input className="h-7" value={form.supply_tel_no || ""} onChange={(e) => set("supply_tel_no", e.target.value)} />
              </FieldRow>
              <FieldRow label="E-MAIL">
                <Input className="h-7" value={form.email || ""} onChange={(e) => set("email", e.target.value)} />
              </FieldRow>
              <FieldRow label="OFFICE NO">
                <Input className="h-7" value={form.office_no || ""} onChange={(e) => set("office_no", e.target.value)} />
              </FieldRow>
              <FieldRow label="FAX NO">
                <Input className="h-7" value={form.supply_fax_no || ""} onChange={(e) => set("supply_fax_no", e.target.value)} />
              </FieldRow>
            </tbody>
          </table>
        </section>

        {/* 우: 담당자 정보 */}
        <section className="flex-1 bg-white border rounded p-3">
          <div className="flex items-center justify-between mb-2 border-b pb-1">
            <h4 className="text-sm font-bold text-gray-700">담당자 정보</h4>
            <div className="flex gap-1">
              <Button size="sm" onClick={addCharger}>추가</Button>
              <Button size="sm" variant="secondary" onClick={() => setChargers([])}>전체 삭제</Button>
            </div>
          </div>

          <div className="overflow-auto" style={{ maxHeight: "calc(100vh - 180px)" }}>
            <table className="w-full text-xs border-collapse">
              <thead className="bg-gray-100 sticky top-0">
                <tr className="border-b">
                  <th className="p-1 w-8"></th>
                  <th className="p-1 w-10 text-center">No</th>
                  <th className="p-1 w-[100px] text-center">담당 구분</th>
                  <th className="p-1 text-center">담당자</th>
                  <th className="p-1 text-center">HP</th>
                  <th className="p-1 text-center">Tel</th>
                  <th className="p-1 text-center">Fax</th>
                  <th className="p-1 text-center">email</th>
                </tr>
              </thead>
              <tbody>
                {chargers.map((c, i) => (
                  <tr key={c.rowKey} className="border-t">
                    <td className="p-1 text-center">
                      <button
                        type="button"
                        onClick={() => removeCharger(c.rowKey)}
                        className="text-red-500 hover:text-red-700 text-xs"
                        title="삭제"
                      >
                        ×
                      </button>
                    </td>
                    <td className="p-1 text-center text-gray-500">{i + 1}</td>
                    <td className="p-1">
                      <SearchableCodeSelect
                        codeId={CHARGER_TYPE_CODE}
                        value={c.charger_type}
                        onChange={(v) => updateCharger(c.rowKey, "charger_type", v)}
                      />
                    </td>
                    <td className="p-1">
                      <Input value={c.charger_name} onChange={(e) => updateCharger(c.rowKey, "charger_name", e.target.value)} />
                    </td>
                    <td className="p-1">
                      <Input value={c.phone} onChange={(e) => updateCharger(c.rowKey, "phone", e.target.value)} />
                    </td>
                    <td className="p-1">
                      <Input value={c.tel} onChange={(e) => updateCharger(c.rowKey, "tel", e.target.value)} />
                    </td>
                    <td className="p-1">
                      <Input value={c.fax} onChange={(e) => updateCharger(c.rowKey, "fax", e.target.value)} />
                    </td>
                    <td className="p-1">
                      <Input value={c.email} onChange={(e) => updateCharger(c.rowKey, "email", e.target.value)} />
                    </td>
                  </tr>
                ))}
                {chargers.length === 0 && (
                  <tr>
                    <td colSpan={8} className="p-4 text-center text-gray-400">담당자가 없습니다. "추가" 버튼으로 등록하세요.</td>
                  </tr>
                )}
              </tbody>
            </table>
          </div>
        </section>
      </div>

      <div className="flex justify-center gap-2 mt-4">
        <Button onClick={handleSave} disabled={loading}>{loading ? "저장 중..." : "저장"}</Button>
        <Button variant="secondary" onClick={() => window.close()}>닫기</Button>
      </div>
    </div>
  );
}

function FieldRow({ label, required, children }: { label: string; required?: boolean; children: React.ReactNode }) {
  return (
    <tr>
      <th className="bg-[#5c6d97] text-white font-medium text-center py-1 px-2 w-[95px] border border-white whitespace-nowrap">
        {label}
        {required && <span className="text-red-300 ml-1">*</span>}
      </th>
      <td className="border border-gray-200 p-[3px] align-middle">{children}</td>
    </tr>
  );
}

export default function Page() {
  return (
    <Suspense fallback={<div className="p-8 text-center text-gray-400">로딩 중...</div>}>
      <SupplyForm />
    </Suspense>
  );
}
