"use client";

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

export interface FormField {
  key: string;
  label: string;
  type?: "text" | "number" | "date" | "textarea" | "codeselect";
  codeId?: string;
  required?: boolean;
  disabled?: boolean;
  defaultValue?: string;
}

interface SimpleFormPopupProps {
  title: string;
  fields: FormField[];
  detailUrl?: string; // /api/xxx/detail
  saveUrl: string;    // /api/xxx/save
  titleField?: string; // header에 표시할 필드 (번호 등)
  onBeforeSave?: (form: Record<string, string>) => Record<string, string> | null;
}

export default function SimpleFormPopup({
  title, fields, detailUrl, saveUrl, titleField, onBeforeSave,
}: SimpleFormPopupProps) {
  const searchParams = useSearchParams();
  const objId = searchParams.get("objId") || "";
  const isNew = !objId;

  const [form, setForm] = useState<Record<string, string>>(() => {
    const init: Record<string, string> = {};
    fields.forEach((f) => { if (f.defaultValue !== undefined) init[f.key] = f.defaultValue; });
    return init;
  });
  const [loading, setLoading] = useState(false);
  const set = (k: string, v: string) => setForm((p) => ({ ...p, [k]: v }));

  const fetchDetail = useCallback(async () => {
    if (!objId || !detailUrl) return;
    const res = await fetch(detailUrl, {
      method: "POST", headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ objId }),
    });
    const json = await res.json();
    if (json.success && json.data) {
      const data = json.data as Record<string, unknown>;
      // 대문자/소문자 양쪽 지원하여 form에 매핑
      const next: Record<string, string> = {};
      fields.forEach((f) => {
        const upper = f.key.toUpperCase();
        const lower = f.key.toLowerCase();
        next[f.key] = String(data[upper] ?? data[lower] ?? data[f.key] ?? "");
      });
      setForm((prev) => ({ ...prev, ...next, objId }));
    }
  }, [objId, detailUrl, fields]);

  useEffect(() => { if (!isNew) fetchDetail(); }, [isNew, fetchDetail]);

  const handleSave = async () => {
    for (const f of fields) {
      if (f.required && !form[f.key]) {
        Swal.fire("알림", `${f.label}을(를) 입력하세요.`, "warning");
        return;
      }
    }
    setLoading(true);
    try {
      let payload: Record<string, string> = {
        ...form,
        actionType: isNew ? "regist" : "update",
      };
      if (!isNew) payload.objId = objId;
      if (onBeforeSave) {
        const r = onBeforeSave(payload);
        if (!r) { setLoading(false); return; }
        payload = r;
      }
      const res = await fetch(saveUrl, {
        method: "POST", headers: { "Content-Type": "application/json" },
        body: JSON.stringify(payload),
      });
      const json = await res.json();
      if (json.success) {
        Swal.fire({ icon: "success", title: json.message, timer: 1500, showConfirmButton: false });
        if (window.opener) { try { window.opener.location.reload(); } catch { /* */ } }
        if (isNew) {
          setTimeout(() => window.close(), 1500);
        }
      } else {
        Swal.fire("오류", json.message || "저장 실패", "error");
      }
    } catch {
      Swal.fire("오류", "저장 중 오류가 발생했습니다.", "error");
    } finally { setLoading(false); }
  };

  const renderField = (f: FormField) => {
    const v = form[f.key] || "";
    if (f.type === "codeselect" && f.codeId) {
      return <CodeSelect codeId={f.codeId} value={v} onChange={(val) => set(f.key, val)} disabled={f.disabled} />;
    }
    if (f.type === "textarea") {
      return <textarea value={v} onChange={(e) => set(f.key, e.target.value)} disabled={f.disabled}
        className="flex min-h-[60px] w-full rounded border border-gray-300 bg-white px-3 py-1 text-sm disabled:opacity-50" />;
    }
    return <Input type={f.type || "text"} value={v} onChange={(e) => set(f.key, e.target.value)} disabled={f.disabled} />;
  };

  return (
    <div className="p-5 max-w-[800px] mx-auto">
      <h2 className="text-lg font-bold text-gray-800 mb-4">
        {isNew ? `${title} 등록` : `${title} 수정`}
        {titleField && form[titleField] && ` (${form[titleField]})`}
      </h2>
      <div className="text-sm">
        {fields.map((f) => (
          <div key={f.key} className="flex items-start gap-2 mb-3">
            <label className="w-[120px] text-xs font-medium text-gray-600 shrink-0 pt-2">
              {f.label} {f.required && <span className="text-red-400">*</span>}
            </label>
            <div className="flex-1">{renderField(f)}</div>
          </div>
        ))}
      </div>
      <div className="flex justify-center gap-3 mt-5 pt-4 border-t">
        <Button onClick={handleSave} disabled={loading}>{loading ? "저장 중..." : "저장"}</Button>
        <Button variant="secondary" onClick={() => window.close()}>닫기</Button>
      </div>
    </div>
  );
}
