"use client";

import { useQuery } from "@tanstack/react-query";
import { UserCircle2, Shield, User } from "lucide-react";
import { getCompanyMembers } from "@/lib/api/provisioning";

const TYPE_STYLE: Record<string, { color: string; bg: string; label: string }> = {
  COMPANY_ADMIN: { color: "var(--v5-primary)", bg: "rgba(var(--v5-primary-rgb), 0.1)", label: "관리자" },
  ADMIN:         { color: "var(--v5-cyan)",    bg: "rgba(var(--v5-cyan-rgb), 0.1)",    label: "부관리자" },
  USER:          { color: "var(--v5-text-sec)", bg: "var(--v5-bg-subtle)",              label: "일반" },
};

export default function MembersTab({ companyCode, open }: { companyCode: string; open: boolean }) {
  const { data, isLoading } = useQuery({
    queryKey: ["company-members", companyCode],
    queryFn: () => getCompanyMembers(companyCode),
    enabled: open,
    staleTime: 10_000,
  });

  const members: Record<string, any>[] = data?.members || [];

  if (isLoading) {
    return <EmptyBox>구성원 조회 중...</EmptyBox>;
  }
  if (members.length === 0) {
    return <EmptyBox>등록된 구성원이 없습니다.</EmptyBox>;
  }

  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 6 }}>
      <div style={{
        display: "grid",
        gridTemplateColumns: "minmax(160px, 1fr) minmax(140px, 1fr) 100px 90px 140px",
        gap: "0.8rem",
        padding: "0.4rem 0.7rem",
        fontSize: "0.7rem",
        color: "var(--v5-text-sec)",
        fontFamily: "var(--v5-font-mono)",
        letterSpacing: "0.05em",
        textTransform: "uppercase",
        fontWeight: 700,
        borderBottom: "1px solid var(--v5-border)",
      }}>
        <span>ID</span>
        <span>이름</span>
        <span>권한</span>
        <span>상태</span>
        <span>생성일</span>
      </div>
      {members.map((m) => {
        const typeStyle = TYPE_STYLE[m.user_type] || TYPE_STYLE.USER;
        const Icon = m.user_type === "COMPANY_ADMIN" ? Shield : m.user_type === "ADMIN" ? UserCircle2 : User;
        return (
          <div
            key={m.user_id}
            style={{
              display: "grid",
              gridTemplateColumns: "minmax(160px, 1fr) minmax(140px, 1fr) 100px 90px 140px",
              gap: "0.8rem",
              padding: "0.5rem 0.7rem",
              fontSize: "0.78rem",
              alignItems: "center",
              borderRadius: 6,
              background: "var(--v5-surface-solid)",
              border: "1px solid var(--v5-border)",
            }}
          >
            <span style={{ fontFamily: "var(--v5-font-mono)", color: "var(--v5-text)", fontWeight: 500, display: "inline-flex", alignItems: "center", gap: 6 }}>
              <Icon size={12} strokeWidth={1.75} color={typeStyle.color} />
              {m.user_id}
            </span>
            <span style={{ color: "var(--v5-text)" }}>{m.user_name || "—"}</span>
            <span>
              <span style={{
                fontSize: "0.68rem",
                padding: "2px 7px",
                borderRadius: 4,
                background: typeStyle.bg,
                color: typeStyle.color,
                fontWeight: 700,
                fontFamily: "var(--v5-font-mono)",
              }}>
                {typeStyle.label}
              </span>
            </span>
            <span>
              <span style={{
                fontSize: "0.68rem",
                padding: "2px 7px",
                borderRadius: 4,
                background: m.status === "active" ? "rgba(var(--v5-green-rgb),0.1)" : "var(--v5-bg-subtle)",
                color: m.status === "active" ? "rgb(var(--v5-green-rgb))" : "var(--v5-text-muted)",
                fontWeight: 600,
              }}>
                {m.status || "—"}
              </span>
            </span>
            <span style={{ color: "var(--v5-text-sec)", fontFamily: "var(--v5-font-mono)", fontSize: "0.7rem" }}>
              {formatDate(m.created_date)}
            </span>
          </div>
        );
      })}
      <div style={{ fontSize: "0.7rem", color: "var(--v5-text-muted)", textAlign: "right", marginTop: 4 }}>
        총 <b style={{ color: "var(--v5-text)" }}>{members.length}</b> 명
      </div>
    </div>
  );
}

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>
  );
}

function formatDate(v: any): string {
  if (!v) return "—";
  try {
    const d = new Date(String(v));
    if (isNaN(d.getTime())) return String(v);
    return d.toISOString().slice(0, 10);
  } catch {
    return String(v);
  }
}
