"use client";

// INVYONE 스튜디오 진입 페이지 (templates 테이블 기반)
// - 템플릿 목록 + 새 템플릿 생성 → templates 테이블 CRUD
// - URL ?id=<template_id> 로 바로 진입
// - InvyoneStudio 는 template_id 를 통해 templates API 로 저장/로드
import { Suspense, useState, useEffect, useCallback } from "react";
import { useSearchParams, useRouter } from "next/navigation";
import InvyoneStudio from "@/components/screen/InvyoneStudio";
import type { ScreenDefinition } from "@/types/screen";
import { getTemplateList, deleteTemplate } from "@/lib/api/template";
import { createTemplate } from "@/lib/utils/templateAdapter";
import { useAuth } from "@/hooks/useAuth";
import { Plus, LayoutTemplate, Search, FileText, Trash2 } from "lucide-react";
import { Input } from "@/components/ui/input";
import { toast } from "sonner";

const CATEGORIES: { id: string; label: string }[] = [
  { id: "", label: "전체" },
  { id: "sales", label: "영업/CRM" },
  { id: "production", label: "생산/공정" },
  { id: "hr", label: "인사/급여" },
  { id: "inventory", label: "재고/물류" },
  { id: "finance", label: "재무/회계" },
  { id: "admin", label: "관리자" },
  { id: "custom", label: "기타" },
];

function templateToScreenDef(t: Record<string, any>): ScreenDefinition {
  const templateId = t.template_id ?? t.TEMPLATE_ID;
  return {
    // ScreenDesigner 가 screen_id 를 옵셔널하게 참조하도록 undefined 허용
    screen_id: undefined as any,
    screen_name: t.name ?? t.NAME ?? "",
    screen_code: "",
    table_name: t.primary_table ?? t.PRIMARY_TABLE ?? "",
    company_code: (t.company_code ?? t.COMPANY_CODE ?? "") as any,
    description: t.description ?? t.DESCRIPTION ?? "",
    is_active: "Y" as any,
    created_date: new Date(),
    updated_date: new Date(),
    template_id: templateId,
    is_template_mode: true,
    template_category: t.category ?? t.CATEGORY ?? "",
    template_status: (t.status ?? t.STATUS) as any,
  };
}

function TemplateGallery({
  templates,
  onSelect,
  onCreate,
  onDelete,
  loading,
}: {
  templates: Record<string, any>[];
  onSelect: (t: Record<string, any>) => void;
  onCreate: () => void;
  onDelete: (t: Record<string, any>) => void;
  loading: boolean;
}) {
  const [query, setQuery] = useState("");
  const [activeCategory, setActiveCategory] = useState("");

  const filtered = templates.filter((t) => {
    const name = (t.name ?? t.NAME ?? "").toLowerCase();
    const cat = (t.category ?? t.CATEGORY ?? "").toLowerCase();
    const desc = (t.description ?? t.DESCRIPTION ?? "").toLowerCase();
    const q = query.toLowerCase();
    const matchQ = !q || name.includes(q) || desc.includes(q);
    const matchCat = !activeCategory || cat === activeCategory;
    return matchQ && matchCat;
  });

  return (
    <div className="ide-builder h-[calc(100vh-4rem)] w-full overflow-y-auto bg-background px-8 py-10">
      <div className="mx-auto max-w-6xl">
        {/* 헤더 */}
        <div className="mb-8 flex items-end justify-between">
          <div>
            <h1 className="mb-1 text-2xl font-bold text-foreground">템플릿</h1>
            <p className="text-sm text-muted-foreground">
              INVYONE 스튜디오 — 기존 템플릿을 열거나 새로 만드세요
            </p>
          </div>
          <button
            type="button"
            onClick={onCreate}
            className="flex items-center gap-1.5 rounded-md border border-primary/30 bg-primary/10 px-4 py-2 text-sm font-semibold text-primary transition-all hover:bg-primary/15 hover:border-primary/50"
          >
            <Plus size={14} />새 템플릿
          </button>
        </div>

        {/* 검색 + 카테고리 */}
        <div className="mb-6 flex items-center gap-3 flex-wrap">
          <div className="relative max-w-md flex-1 min-w-[200px]">
            <Search
              className="absolute left-3 top-1/2 -translate-y-1/2 text-muted-foreground"
              size={14}
            />
            <Input
              placeholder="템플릿 검색..."
              value={query}
              onChange={(e) => setQuery(e.target.value)}
              className="pl-9 h-9"
            />
          </div>
          <div className="flex items-center gap-1 flex-wrap">
            {CATEGORIES.map((cat) => (
              <button
                key={cat.id}
                type="button"
                onClick={() => setActiveCategory(cat.id)}
                className={
                  activeCategory === cat.id
                    ? "rounded-md border border-primary/40 bg-primary/15 px-3 py-1.5 text-xs font-semibold text-primary"
                    : "rounded-md border border-border/40 bg-card px-3 py-1.5 text-xs text-muted-foreground hover:border-primary/30 hover:text-foreground"
                }
              >
                {cat.label}
              </button>
            ))}
          </div>
        </div>

        {/* 로딩 */}
        {loading && (
          <div className="py-20 text-center text-sm text-muted-foreground">
            불러오는 중...
          </div>
        )}

        {/* 빈 상태 */}
        {!loading && templates.length === 0 && (
          <div className="py-20 text-center">
            <LayoutTemplate
              className="mx-auto mb-4 text-muted-foreground/30"
              size={48}
            />
            <p className="mb-2 text-sm font-medium text-foreground">
              아직 템플릿이 없습니다
            </p>
            <p className="mb-4 text-xs text-muted-foreground">
              첫 템플릿을 만들어보세요
            </p>
            <button
              type="button"
              onClick={onCreate}
              className="rounded-md border border-primary/30 bg-primary/10 px-4 py-2 text-sm font-semibold text-primary hover:bg-primary/15"
            >
              <Plus size={14} className="inline mr-1" />새 템플릿 만들기
            </button>
          </div>
        )}

        {/* 그리드 */}
        {!loading && filtered.length > 0 && (
          <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-3">
            {filtered.map((t) => {
              const tid = t.template_id ?? t.TEMPLATE_ID;
              const name = t.name ?? t.NAME ?? "템플릿";
              const cat = t.category ?? t.CATEGORY ?? "";
              const desc = t.description ?? t.DESCRIPTION ?? "";
              const table = t.primary_table ?? t.PRIMARY_TABLE ?? "";
              return (
                <div
                  key={tid}
                  className="group relative flex flex-col items-start rounded-lg border border-border/40 bg-card p-4 text-left transition-all hover:border-primary/30 hover:shadow-md"
                >
                  <button
                    type="button"
                    onClick={() => onSelect(t)}
                    className="flex w-full flex-col items-start text-left"
                  >
                    <div className="mb-3 flex h-10 w-10 items-center justify-center rounded-md bg-primary/10 text-primary">
                      <FileText size={18} />
                    </div>
                    <h3 className="mb-1 text-sm font-semibold text-foreground line-clamp-1">
                      {name}
                    </h3>
                    <p className="mb-2 text-[0.62rem] text-muted-foreground line-clamp-2">
                      {desc || "설명 없음"}
                    </p>
                    <div className="mt-auto flex items-center gap-1 flex-wrap">
                      {cat && (
                        <span className="rounded-full bg-primary/10 px-2 py-0.5 text-[0.6rem] text-primary">
                          {cat}
                        </span>
                      )}
                      {table && (
                        <span className="rounded-full bg-muted px-2 py-0.5 text-[0.6rem] text-muted-foreground font-mono">
                          {table}
                        </span>
                      )}
                    </div>
                  </button>
                  <button
                    type="button"
                    onClick={(e) => {
                      e.stopPropagation();
                      onDelete(t);
                    }}
                    className="absolute right-2 top-2 rounded-md p-1 text-muted-foreground/60 opacity-0 transition-opacity hover:bg-red-500/10 hover:text-red-500 group-hover:opacity-100"
                    title="삭제"
                  >
                    <Trash2 size={12} />
                  </button>
                </div>
              );
            })}
          </div>
        )}

        {!loading && templates.length > 0 && filtered.length === 0 && (
          <div className="py-12 text-center text-sm text-muted-foreground">
            &ldquo;{query}&rdquo; 검색 결과가 없습니다
          </div>
        )}
      </div>
    </div>
  );
}

function CreateTemplateModal({
  open,
  onClose,
  onCreate,
}: {
  open: boolean;
  onClose: () => void;
  onCreate: (name: string, category: string) => Promise<void>;
}) {
  const [name, setName] = useState("");
  const [category, setCategory] = useState("custom");
  const [creating, setCreating] = useState(false);

  if (!open) return null;

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 backdrop-blur-sm">
      <div className="w-full max-w-md rounded-lg border border-border bg-card p-6 shadow-2xl">
        <h2 className="mb-1 text-lg font-bold text-foreground">새 템플릿</h2>
        <p className="mb-4 text-xs text-muted-foreground">
          템플릿 이름과 카테고리를 입력하세요.
        </p>
        <div className="space-y-3">
          <Input
            autoFocus
            placeholder="예: 사원 관리"
            value={name}
            onChange={(e) => setName(e.target.value)}
            onKeyDown={(e) => {
              if (e.key === "Enter" && name.trim() && !creating) {
                setCreating(true);
                onCreate(name.trim(), category).finally(() => setCreating(false));
              } else if (e.key === "Escape") {
                onClose();
              }
            }}
            className="h-10"
          />
          <select
            value={category}
            onChange={(e) => setCategory(e.target.value)}
            className="w-full rounded-md border border-border bg-background px-3 py-2 text-sm"
          >
            {CATEGORIES.filter((c) => c.id).map((cat) => (
              <option key={cat.id} value={cat.id}>
                {cat.label}
              </option>
            ))}
          </select>
        </div>
        <div className="mt-5 flex justify-end gap-2">
          <button
            type="button"
            onClick={onClose}
            disabled={creating}
            className="rounded-md border border-border px-4 py-2 text-sm text-muted-foreground hover:bg-muted disabled:opacity-50"
          >
            취소
          </button>
          <button
            type="button"
            disabled={!name.trim() || creating}
            onClick={async () => {
              setCreating(true);
              try {
                await onCreate(name.trim(), category);
              } finally {
                setCreating(false);
              }
            }}
            className="rounded-md bg-primary px-4 py-2 text-sm font-semibold text-primary-foreground hover:bg-primary/90 disabled:opacity-50"
          >
            {creating ? "생성 중..." : "만들기"}
          </button>
        </div>
      </div>
    </div>
  );
}

function BuilderInner() {
  const router = useRouter();
  const searchParams = useSearchParams();
  const templateIdParam = searchParams.get("id");
  useAuth();

  const [selectedScreen, setSelectedScreen] = useState<ScreenDefinition | null>(null);
  const [templates, setTemplates] = useState<Record<string, any>[]>([]);
  const [loading, setLoading] = useState(true);
  const [loadError, setLoadError] = useState<string | null>(null);
  const [showCreate, setShowCreate] = useState(false);

  const fetchTemplates = useCallback(async (): Promise<Record<string, any>[]> => {
    try {
      setLoading(true);
      setLoadError(null);
      const result: Record<string, any> = await getTemplateList();
      const list: Record<string, any>[] = result?.list ?? result?.data ?? [];
      setTemplates(list);
      return list;
    } catch (err: any) {
      console.error("[BuilderPage] 템플릿 로드 실패:", err);
      setLoadError(err?.message ?? "템플릿 로드 실패");
      return [];
    } finally {
      setLoading(false);
    }
  }, []);

  // URL ?id=xxx 있으면 해당 템플릿 로드
  useEffect(() => {
    (async () => {
      const list = await fetchTemplates();
      if (templateIdParam) {
        const target = list.find(
          (t) => (t.template_id ?? t.TEMPLATE_ID) === templateIdParam,
        );
        if (target) setSelectedScreen(templateToScreenDef(target));
      }
    })();
  }, [templateIdParam, fetchTemplates]);

  const handleSelectTemplate = useCallback(
    (t: Record<string, any>) => {
      const def = templateToScreenDef(t);
      setSelectedScreen(def);
      router.replace(`/admin/builder?id=${def.template_id}`);
    },
    [router],
  );

  const handleCreateTemplate = useCallback(
    async (name: string, category: string) => {
      try {
        const created = await createTemplate({
          name,
          category,
          description: "",
          primaryTable: "",
        });
        const templateId = created.template_id ?? created.TEMPLATE_ID;
        setShowCreate(false);
        const def = templateToScreenDef({
          template_id: templateId,
          name,
          category,
          description: "",
          primary_table: "",
          status: "draft",
        });
        setSelectedScreen(def);
        router.replace(`/admin/builder?id=${templateId}`);
        toast.success(`"${name}" 템플릿을 만들었습니다`);
      } catch (err: any) {
        console.error("[BuilderPage] 템플릿 생성 실패:", err);
        toast.error(`템플릿 생성 실패: ${err?.message ?? "알 수 없는 오류"}`);
      }
    },
    [router],
  );

  const handleDeleteTemplate = useCallback(
    async (t: Record<string, any>) => {
      const tid = t.template_id ?? t.TEMPLATE_ID;
      const name = t.name ?? t.NAME ?? "템플릿";
      if (!confirm(`"${name}" 템플릿을 삭제합니다.`)) return;
      try {
        await deleteTemplate(tid);
        toast.info(`"${name}" 을(를) 삭제했습니다`);
        await fetchTemplates();
      } catch (err: any) {
        console.error("[BuilderPage] 템플릿 삭제 실패:", err);
        toast.error("삭제 실패");
      }
    },
    [fetchTemplates],
  );

  const handleBackToList = useCallback(() => {
    setSelectedScreen(null);
    router.replace("/admin/builder");
    fetchTemplates();
  }, [fetchTemplates, router]);

  if (loadError) {
    return (
      <div className="flex h-screen flex-col items-center justify-center gap-2 text-slate-500">
        <div className="text-sm">⚠ {loadError}</div>
        <button
          type="button"
          onClick={() => fetchTemplates()}
          className="rounded border border-slate-300 px-3 py-1 text-xs hover:bg-slate-100"
        >
          다시 시도
        </button>
      </div>
    );
  }

  if (!selectedScreen) {
    return (
      <>
        <TemplateGallery
          templates={templates}
          onSelect={handleSelectTemplate}
          onCreate={() => setShowCreate(true)}
          onDelete={handleDeleteTemplate}
          loading={loading}
        />
        <CreateTemplateModal
          open={showCreate}
          onClose={() => setShowCreate(false)}
          onCreate={handleCreateTemplate}
        />
      </>
    );
  }

  return (
    <div className="ide-builder h-[calc(100vh-4rem)] w-full overflow-hidden bg-background">
      <InvyoneStudio
        selectedScreen={selectedScreen}
        onBackToList={handleBackToList}
        onScreenUpdate={(updatedFields) => {
          if (selectedScreen) {
            setSelectedScreen({ ...selectedScreen, ...updatedFields });
          }
        }}
      />
    </div>
  );
}

export default function BuilderPage() {
  return (
    <Suspense
      fallback={
        <div className="flex h-screen items-center justify-center text-slate-500">
          빌더 로딩 중...
        </div>
      }
    >
      <BuilderInner />
    </Suspense>
  );
}
