"use client";

import React, { useEffect, useState } from "react";
import { SmartSelect, SmartSelectOption } from "@/components/common/SmartSelect";
import { apiClient } from "@/lib/api/client";

interface CustomerSelectProps {
  /** contract_mgmt.customer_objid 형식 ('C_{customer_code}') — 운영 데이터 호환 */
  value: string;
  onValueChange: (value: string) => void;
  placeholder?: string;
  disabled?: boolean;
  className?: string;
}

let cached: SmartSelectOption[] | null = null;
let inflight: Promise<SmartSelectOption[]> | null = null;

// 운영 wace 데이터: contract_mgmt.customer_objid = 'C_' + customer_mng.customer_code
// (이전엔 customer_mng.id padded로 매핑했으나 운영 데이터와 어긋났음 — 26C-0801 라온기술/정림유리 미스매치 사례)
export const fetchCustomers = async (): Promise<SmartSelectOption[]> => {
  if (cached) return cached;
  if (inflight) return inflight;
  inflight = (async () => {
    const res = await apiClient.get("/sales/customers");
    const rows = (res.data?.data ?? []) as any[];
    cached = rows
      .filter((r) => r.customer_code && r.customer_name)
      .map((r) => ({
        code: `C_${r.customer_code}`,
        label: String(r.customer_name),
      }));
    return cached!;
  })();
  try {
    return await inflight;
  } finally {
    inflight = null;
  }
};

export function CustomerSelect({
  value, onValueChange, placeholder = "거래처 선택", disabled, className,
}: CustomerSelectProps) {
  const [options, setOptions] = useState<SmartSelectOption[]>(cached ?? []);

  useEffect(() => {
    let alive = true;
    fetchCustomers().then((opts) => { if (alive) setOptions(opts); }).catch(() => {});
    return () => { alive = false; };
  }, []);

  return (
    <SmartSelect
      options={options}
      value={value}
      onValueChange={onValueChange}
      placeholder={placeholder}
      disabled={disabled}
      className={className}
    />
  );
}
