"use client";

import { useQuery } from "@tanstack/react-query";
import { useState } from "react";
import { Layers, Copy, Check, ChevronDown, ChevronRight } from "lucide-react";
import { getInstalledGroups } from "@/lib/api/provisioning";
import RecopyTemplatesModal from "../modals/RecopyTemplatesModal";

export default function TemplatesTab({
  companyCode,
  companyName,
  dbName,
  open,
}: {
  companyCode: string;
  companyName?: string;
  dbName: string;
  open: boolean;
}) {
  const { data = [], isLoading, refetch } = useQuery({
    queryKey: ["installed-groups", companyCode],
    queryFn: () => getInstalledGroups(companyCode),
    enabled: open,
    staleTime: 30_000,
  });
  const [recopyOpen, setRecopyOpen] = useState(false);
  const [expandedKeys, setExpandedKeys] = useState<Set<string>>(new Set());

  if (isLoading) return <EmptyBox>조회 중...</EmptyBox>;

  const installed = data.filter((g) => g.installed);
  const notInstalled = data.filter((g) => !g.installed);

  return (
    <>
      <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
        <div style={{
          display: "flex",
          alignItems: "center",
          justifyContent: "space-between",
          fontSize: "0.75rem",
          color: "var(--v5-text-sec)",
          fontWeight: 600,
        }}>
          <span>
            설치된 템플릿 그룹 <b style={{ color: "var(--v5-text)" }}>{installed.length}</b> · 전체 {data.length}
          </span>
          <button
            onClick={() => setRecopyOpen(true)}
            className="prov-hbtn prov-hbtn-secondary"
            style={{
              display: "inline-flex",
              alignItems: "center",
              gap: 6,
              height: 30,
              padding: "0 0.75rem",
              borderRadius: 6,
              fontSize: "0.75rem",
              fontWeight: 600,
              border: "1px solid var(--v5-border)",
              background: "var(--v5-surface-solid)",
              color: "var(--v5-text)",
              cursor: "pointer",
              fontFamily: "inherit",
            }}
          >
            <Copy size={12} strokeWidth={1.75} /> 템플릿 재복제
          </button>
        </div>

        <div style={{ display: "flex", flexDirection: "column", gap: 6 }}>
          {data.map((g) => {
            const expanded = expandedKeys.has(g.id);
            const tables: string[] = g.tables || [];
            return (
              <div
                key={g.id}
                style={{
                  border: "1px solid var(--v5-border)",
                  borderRadius: 7,
                  background: g.installed ? "var(--v5-surface-solid)" : "var(--v5-bg-subtle)",
                  overflow: "hidden",
                  opacity: g.installed ? 1 : 0.65,
                }}
              >
                <button
                  onClick={() => {
                    const next = new Set(expandedKeys);
                    if (expanded) next.delete(g.id); else next.add(g.id);
                    setExpandedKeys(next);
                  }}
                  style={{
                    width: "100%",
                    display: "grid",
                    gridTemplateColumns: "16px 1fr 100px 80px",
                    gap: 10,
                    alignItems: "center",
                    padding: "0.55rem 0.75rem",
                    background: "transparent",
                    border: 0,
                    cursor: "pointer",
                    textAlign: "left",
                    fontFamily: "inherit",
                  }}
                >
                  {expanded ? (
                    <ChevronDown size={14} color="var(--v5-text-muted)" strokeWidth={1.75} />
                  ) : (
                    <ChevronRight size={14} color="var(--v5-text-muted)" strokeWidth={1.75} />
                  )}
                  <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
                    <Layers size={13} color="var(--v5-primary)" strokeWidth={1.75} />
                    <span style={{ fontSize: "0.82rem", fontWeight: 700, color: "var(--v5-text)" }}>{g.label}</span>
                    {g.required && (
                      <span style={{
                        fontSize: "0.62rem",
                        padding: "2px 6px",
                        borderRadius: 3,
                        background: "var(--v5-bg-subtle)",
                        color: "var(--v5-text-sec)",
                        fontFamily: "var(--v5-font-mono)",
                        fontWeight: 700,
                        letterSpacing: "0.04em",
                      }}>
                        필수
                      </span>
                    )}
                  </div>
                  <span style={{
                    fontSize: "0.7rem",
                    color: "var(--v5-text-sec)",
                    fontFamily: "var(--v5-font-mono)",
                  }}>
                    {tables.length} 테이블
                  </span>
                  <span style={{ justifySelf: "flex-end" }}>
                    {g.installed ? (
                      <span style={{
                        display: "inline-flex",
                        alignItems: "center",
                        gap: 4,
                        fontSize: "0.7rem",
                        color: "rgb(var(--v5-green-rgb))",
                        fontWeight: 700,
                      }}>
                        <Check size={11} strokeWidth={2} /> 설치됨
                      </span>
                    ) : (
                      <span style={{ fontSize: "0.7rem", color: "var(--v5-text-muted)", fontWeight: 600 }}>
                        미설치
                      </span>
                    )}
                  </span>
                </button>
                {expanded && (
                  <div style={{
                    padding: "0.5rem 0.8rem 0.7rem 2.2rem",
                    borderTop: "1px solid var(--v5-border)",
                    background: "var(--v5-bg-subtle)",
                    display: "flex",
                    flexWrap: "wrap",
                    gap: 5,
                  }}>
                    {tables.map((t: string) => (
                      <span
                        key={t}
                        style={{
                          fontSize: "0.7rem",
                          padding: "2px 7px",
                          borderRadius: 3,
                          background: "var(--v5-surface-solid)",
                          border: "1px solid var(--v5-border)",
                          color: "var(--v5-text-sec)",
                          fontFamily: "var(--v5-font-mono)",
                        }}
                      >
                        {t}
                      </span>
                    ))}
                  </div>
                )}
              </div>
            );
          })}
        </div>
      </div>
      {recopyOpen && (
        <RecopyTemplatesModal
          companyCode={companyCode}
          companyName={companyName}
          dbName={dbName}
          installedGroups={data}
          onClose={() => setRecopyOpen(false)}
          onSuccess={() => {
            setRecopyOpen(false);
            refetch();
          }}
        />
      )}
    </>
  );
}

function EmptyBox({ children }: { children: React.ReactNode }) {
  return (
    <div
      style={{
        padding: "1.2rem",
        textAlign: "center",
        border: "1px dashed var(--v5-border)",
        borderRadius: 6,
        color: "var(--v5-text-muted)",
        fontSize: "0.8125rem",
      }}
    >
      {children}
    </div>
  );
}
