"use client";

import { useState, useCallback, useEffect, useMemo } from "react";
import { DataGrid, type GridColumn } from "@/components/grid/data-grid";
import { SearchForm, SearchField } from "@/components/layout/search-form";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import { SearchableCodeSelect } from "@/components/ui/searchable-code-select";
import { SearchableSelect } from "@/components/ui/searchable-select";
import Swal from "sweetalert2";

// 자재관리 > 자재리스트 (원본 /inventoryMng/inventoryMngNewList.do)
export default function InventoryListPage() {
  const [projectNos, setProjectNos] = useState<string[]>([]);
  const [unitCode, setUnitCode] = useState("");
  const [partNo, setPartNo] = useState("");
  const [partName, setPartName] = useState("");
  const [partType, setPartType] = useState("");
  const [location, setLocation] = useState("");

  const [projectOptions, setProjectOptions] = useState<{ value: string; label: string }[]>([]);
  const [unitOptions, setUnitOptions] = useState<{ value: string; label: string }[]>([]);

  const [data, setData] = useState<Record<string, unknown>[]>([]);
  const [selectedRows, setSelectedRows] = useState<Record<string, unknown>[]>([]);
  const [loading, setLoading] = useState(false);

  // 프로젝트 옵션 로드
  useEffect(() => {
    fetch("/api/common/project-list", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({}),
    })
      .then((r) => r.json())
      .then((j) => {
        const list = (j.RESULTLIST || []) as Array<Record<string, unknown>>;
        setProjectOptions(
          list.map((r) => ({
            value: String(r.OBJID || ""),
            label: String(r.LABEL || r.PROJECT_NO || ""),
          })),
        );
      })
      .catch(() => setProjectOptions([]));
  }, []);

  // 프로젝트 선택 변경 시 유닛 로드 (단일/다중 모두 대응 — 첫 번째 프로젝트 기준)
  useEffect(() => {
    setUnitCode("");
    if (projectNos.length === 0) {
      setUnitOptions([]);
      return;
    }
    const first = projectNos[0];
    fetch("/api/common/unit-list", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ contract_objid: first }),
    })
      .then((r) => r.json())
      .then((j) => {
        const list = (j.RESULTLIST || []) as Array<Record<string, unknown>>;
        setUnitOptions(
          list.map((r) => ({
            value: String(r.OBJID || ""),
            label: String(r.UNIT_NAME || ""),
          })),
        );
      })
      .catch(() => setUnitOptions([]));
  }, [projectNos]);

  const openHistoryPopup = useCallback((objId: string) => {
    const w = 730;
    const h = 400;
    const left = (window.screen.width - w) / 2;
    const top = (window.screen.height - h) / 2;
    window.open(
      `/inventory/request/history?objId=${encodeURIComponent(objId)}`,
      "inventoryRequestHistoryPopUp",
      `width=${w},height=${h},left=${left},top=${top}`,
    );
  }, []);

  const columns: GridColumn[] = useMemo(
    () => [
      {
        title: "자재목록",
        headerHozAlign: "center",
        columns: [
          { title: "프로젝트번호", field: "PROJECT_NO", width: 100, hozAlign: "left", headerHozAlign: "center" },
          { title: "유닛명", field: "UNIT_NAME", width: 200, hozAlign: "left", headerHozAlign: "center" },
          { title: "품번", field: "PART_NO", width: 180, hozAlign: "left", headerHozAlign: "center" },
          { title: "품명", field: "PART_NAME", width: 180, hozAlign: "left", headerHozAlign: "center" },
          { title: "재질", field: "MATERIAL", width: 180, hozAlign: "left", headerHozAlign: "center" },
          { title: "사양(규격)", field: "SPEC", width: 200, hozAlign: "left", headerHozAlign: "center" },
          { title: "PART구분", field: "PART_TYPE_NAME", width: 120, hozAlign: "center", headerHozAlign: "center" },
          { title: "보유수량", field: "USE_CNT", width: 100, hozAlign: "center", headerHozAlign: "center", formatter: "money" },
          { title: "보유수량(전체)", field: "USE_CNT_ALL", width: 120, hozAlign: "center", headerHozAlign: "center", formatter: "money" },
          { title: "Location", field: "LOCATION_NAME", width: 120, hozAlign: "left", headerHozAlign: "center" },
        ],
      },
      {
        title: "불출이력",
        headerHozAlign: "center",
        columns: [
          {
            title: "불출이력",
            field: "REQUEST_QTY",
            width: 80,
            hozAlign: "center",
            headerHozAlign: "center",
            formatter: (cell, row) => {
              const v = Number(cell || 0);
              if (v === 0) return "0";
              return (
                <a
                  href="#"
                  onClick={(e) => {
                    e.preventDefault();
                    openHistoryPopup(String(row.OBJID || ""));
                  }}
                  className="text-blue-600 underline"
                >
                  {v.toLocaleString()}
                </a>
              );
            },
          },
          { title: "비고", field: "REMARK", width: 200, hozAlign: "left", headerHozAlign: "center" },
        ],
      },
    ],
    [openHistoryPopup],
  );

  const fetchData = useCallback(async () => {
    setLoading(true);
    try {
      const res = await fetch("/api/inventory/list", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          project_nos: projectNos.join(","),
          unit_code: unitCode,
          part_no: partNo,
          part_name: partName,
          part_type: partType,
          location,
        }),
      });
      if (res.ok) {
        const json = await res.json();
        setData(json.RESULTLIST || []);
      }
    } finally {
      setLoading(false);
    }
  }, [projectNos, unitCode, partNo, partName, partType, location]);

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

  // 등록 팝업 (inventoryFormPopUp)
  const handleRegister = () => {
    const w = 850;
    const h = 500;
    const left = (window.screen.width - w) / 2;
    const top = (window.screen.height - h) / 2;
    window.open(
      "/inventory/list/form",
      "inventoryFormPopUp",
      `width=${w},height=${h},left=${left},top=${top}`,
    );
  };

  // 자재이동 (materialMoveFormPopUp)
  const handleMove = () => {
    if (selectedRows.length === 0) {
      Swal.fire("알림", "선택된 데이터가 없습니다.", "warning");
      return;
    }
    for (const r of selectedRows) {
      if (Number(r.USE_CNT || 0) === 0) {
        alert("보유수량이 0일 경우 이동이 불가능합니다.");
        return;
      }
    }
    const checkArr = selectedRows.map((r) => String(r.OBJID)).join(",");
    const w = 1600;
    const h = 700;
    const left = (window.screen.width - w) / 2;
    const top = (window.screen.height - h) / 2;
    window.open(
      `/inventory/move/form?checkArr=${encodeURIComponent(checkArr)}`,
      "materialMoveFormPopUp",
      `width=${w},height=${h},left=${left},top=${top}`,
    );
  };

  // 불출의뢰 (materialRequestFormPopUp)
  const handleRequest = () => {
    if (selectedRows.length === 0) {
      Swal.fire("알림", "선택된 데이터가 없습니다.", "warning");
      return;
    }
    for (const r of selectedRows) {
      if (Number(r.USE_CNT || 0) === 0) {
        alert("보유수량이 0일 경우 불출의뢰가 불가능합니다.");
        return;
      }
    }
    const checkArr = selectedRows.map((r) => String(r.OBJID)).join(",");
    const w = 1800;
    const h = 700;
    const left = (window.screen.width - w) / 2;
    const top = (window.screen.height - h) / 2;
    window.open(
      `/inventory/request/form?checkArr=${encodeURIComponent(checkArr)}`,
      "inventoryRequestPopUp",
      `width=${w},height=${h},left=${left},top=${top}`,
    );
  };

  return (
    <div>
      <div className="flex items-center justify-between mb-4">
        <h2 className="text-lg font-bold text-gray-800">자재관리_자재리스트</h2>
        <div className="flex gap-2">
          <Button size="sm" onClick={handleRegister}>
            등록
          </Button>
          <Button size="sm" variant="secondary" onClick={handleMove}>
            자재이동
          </Button>
          <Button size="sm" variant="secondary" onClick={handleRequest}>
            불출의뢰
          </Button>
          <Button size="sm" variant="secondary" onClick={fetchData}>
            조회
          </Button>
        </div>
      </div>

      <SearchForm onSearch={fetchData}>
        <SearchField label="프로젝트번호">
          <MultiSelect
            options={projectOptions}
            value={projectNos}
            onChange={setProjectNos}
            placeholder="선택"
            className="w-[300px]"
          />
        </SearchField>
        <SearchField label="유닛명">
          <SearchableSelect
            options={unitOptions}
            value={unitCode}
            onChange={setUnitCode}
            placeholder="선택"
            className="w-[230px]"
          />
        </SearchField>
        <SearchField label="품번">
          <Input
            value={partNo}
            onChange={(e) => setPartNo(e.target.value)}
            placeholder="품번"
            className="w-[150px]"
          />
        </SearchField>
        <SearchField label="품명">
          <Input
            value={partName}
            onChange={(e) => setPartName(e.target.value)}
            placeholder="품명"
            className="w-[170px]"
          />
        </SearchField>
        <SearchField label="PART 구분">
          <SearchableCodeSelect
            codeId="0000062"
            value={partType}
            onChange={setPartType}
            className="w-[120px]"
          />
        </SearchField>
        <SearchField label="Location">
          <SearchableCodeSelect
            codeId="0000262"
            value={location}
            onChange={setLocation}
            className="w-[230px]"
          />
        </SearchField>
      </SearchForm>

      <DataGrid
        columns={columns}
        data={data}
        showCheckbox
        loading={loading}
        onSelectionChange={setSelectedRows}
      />
    </div>
  );
}

// 간단한 다중 선택 — 선택된 라벨을 태그로 표시 + 드롭다운
function MultiSelect({
  options,
  value,
  onChange,
  placeholder,
  className,
}: {
  options: { value: string; label: string }[];
  value: string[];
  onChange: (v: string[]) => void;
  placeholder?: string;
  className?: string;
}) {
  const [open, setOpen] = useState(false);
  const [search, setSearch] = useState("");

  const filtered = options.filter((o) => {
    if (!search) return true;
    const s = search.toLowerCase();
    return o.label.toLowerCase().includes(s) || o.value.toLowerCase().includes(s);
  });

  const toggle = (v: string) => {
    if (value.includes(v)) onChange(value.filter((x) => x !== v));
    else onChange([...value, v]);
  };

  const selectedLabels = value
    .map((v) => options.find((o) => o.value === v)?.label || v)
    .join(", ");

  return (
    <div className={`relative ${className || ""}`}>
      <button
        type="button"
        onClick={() => setOpen((p) => !p)}
        className="h-9 w-full text-left rounded border border-gray-300 bg-white px-2 text-sm truncate pr-6"
        title={selectedLabels}
      >
        {selectedLabels || <span className="text-gray-400">{placeholder || "선택"}</span>}
      </button>
      {value.length > 0 && (
        <button
          type="button"
          onClick={() => onChange([])}
          className="absolute right-2 top-1/2 -translate-y-1/2 text-gray-400 hover:text-gray-700 text-sm"
          tabIndex={-1}
        >
          ×
        </button>
      )}
      {open && (
        <>
          <div className="fixed inset-0 z-40" onClick={() => setOpen(false)} />
          <div className="absolute z-50 mt-1 w-full bg-white border border-gray-300 rounded shadow max-h-64 overflow-y-auto">
            <div className="sticky top-0 bg-white border-b p-1">
              <input
                autoFocus
                type="text"
                value={search}
                onChange={(e) => setSearch(e.target.value)}
                placeholder="검색"
                className="w-full px-2 py-1 text-sm border rounded"
              />
            </div>
            {filtered.length === 0 ? (
              <div className="p-2 text-xs text-gray-400 text-center">결과 없음</div>
            ) : (
              filtered.map((o) => {
                const selected = value.includes(o.value);
                return (
                  <button
                    key={o.value}
                    type="button"
                    onClick={() => toggle(o.value)}
                    className={`w-full text-left px-2 py-1.5 text-sm hover:bg-blue-50 flex items-center gap-2 ${
                      selected ? "bg-blue-50" : ""
                    }`}
                  >
                    <input
                      type="checkbox"
                      checked={selected}
                      readOnly
                      className="pointer-events-none"
                    />
                    <span className="truncate">{o.label}</span>
                  </button>
                );
              })
            )}
          </div>
        </>
      )}
    </div>
  );
}
