"use client";

import {
  Users,
  FileText,
  Database,
  Clock,
  CalendarDays,
  PhoneOutgoing,
  Workflow,
  TrendingUp,
  AlertTriangle,
  History,
  Boxes,
  Settings as SettingsIcon,
  Shield,
  Building2,
  ChevronRight,
  Sparkles,
} from "lucide-react";
import Link from "next/link";
import { useEffect, useState } from "react";
import { useAuth } from "@/hooks/useAuth";

/**
 * 관리자 홈 — Admin Dashboard
 *
 * 참고 시안: notes/gbpark/invion admin-home layout v1 (2026-04-23)
 * 구성:
 *   1) Welcome banner (인사 + 요약 + 액션)
 *   2) Top stats × 4 (큰 숫자)
 *   3) System status × 4 (아이콘 + 상태)
 *   4) 회사별 활동 + 최근 변경 (2:1 grid)
 *   5) 빠른 진입 × 4
 *
 * ※ 현재는 mock 데이터. 실데이터 배선은 후속 작업.
 */
export default function AdminPage() {
  const { user } = useAuth();
  const [now, setNow] = useState<Date | null>(null);
  useEffect(() => {
    setNow(new Date());
  }, []);

  const userName =
    (user as any)?.user_name ||
    (user as any)?.userNameEng ||
    "슈퍼 관리자";
  const userInitial = userName[0] || "김";

  const greeting = (() => {
    const h = now?.getHours() ?? 10;
    if (h < 6) return "늦은 밤입니다";
    if (h < 12) return "좋은 아침입니다";
    if (h < 18) return "오후입니다";
    return "좋은 저녁입니다";
  })();

  const dateStr = now
    ? `${now.getFullYear()}년 ${now.getMonth() + 1}월 ${now.getDate()}일 ${
        ["일", "월", "화", "수", "목", "금", "토"][now.getDay()]
      }요일`
    : "";

  return (
    <div className="min-h-full bg-background">
      <div className="mx-auto w-full max-w-[1680px] space-y-5 p-5">
        {/* ===== 1) Welcome banner ===== */}
        <section
          className="relative overflow-hidden rounded-2xl border border-border px-6 py-5"
          style={{
            background:
              "linear-gradient(135deg, rgba(var(--v5-primary-rgb),0.12), rgba(var(--v5-cyan-rgb),0.08) 50%, transparent 90%)",
            boxShadow: "var(--v5-glow-sm)",
          }}
        >
          <div className="flex items-center justify-between gap-4 flex-wrap">
            <div className="flex items-center gap-4 min-w-0">
              <div
                className="flex h-[60px] w-[60px] shrink-0 items-center justify-center rounded-2xl text-xl font-bold text-white"
                style={{
                  background:
                    "linear-gradient(135deg, rgb(var(--v5-cyan-rgb)), rgb(var(--v5-primary-rgb)))",
                  boxShadow: "var(--v5-glow-md)",
                }}
              >
                {userInitial}
              </div>
              <div className="min-w-0 space-y-1">
                <div className="flex items-center gap-2 text-[0.72rem] text-muted-foreground">
                  <Sparkles
                    size={11}
                    style={{ color: "rgb(var(--v5-cyan-rgb))" }}
                  />
                  <span className="font-medium">{greeting}</span>
                  <span>·</span>
                  <span>{dateStr}</span>
                </div>
                <h1 className="text-[1.35rem] font-bold text-foreground leading-tight truncate">
                  환영합니다,{" "}
                  <span style={{ color: "rgb(var(--v5-primary-rgb))" }}>
                    {userName}
                  </span>
                  <span className="text-foreground"> 슈퍼 관리자님</span>
                </h1>
                <p className="text-[0.78rem] text-muted-foreground">
                  오늘도 좋은 하루 되십시오. 탑실 (COMPANY_27) · 오늘{" "}
                  <b className="text-foreground">1,248건</b>의 변경이 기록됐고,{" "}
                  <b style={{ color: "rgb(var(--v5-pink-rgb))" }}>2건</b>의
                  배치 오류가 주의를 기다리고 있습니다.
                </p>
              </div>
            </div>
            <div className="flex items-center gap-2 shrink-0">
              <AdminPill icon={<History size={12} />} label="전체 이력" />
              <AdminPill icon={<CalendarDays size={12} />} label="배치" />
              <AdminPill
                icon={<Boxes size={12} />}
                label="관리 화면"
                tone="primary"
              />
            </div>
          </div>
        </section>

        {/* ===== 2) Top stats × 4 ===== */}
        <section className="grid grid-cols-1 gap-3 sm:grid-cols-2 lg:grid-cols-4">
          <StatCard
            label="활성 사용자"
            value="148"
            caption="전체 172 · 이번달 +4"
            tone="primary"
            trend="+4"
          />
          <StatCard
            label="회사 · 활성/전체"
            value="6"
            unit="/6"
            caption="최근 접속 2분 전 · 이번달 +1"
            tone="primary"
          />
          <StatCard
            label="오늘 audit"
            value="1,248"
            caption="이번주 8,412"
            tone="primary"
          />
          <StatCard
            label="배치 실패 (24h)"
            value="2"
            caption="성공 184 · 예정 12"
            tone="danger"
          />
        </section>

        {/* ===== 3) System status × 4 ===== */}
        <section className="grid grid-cols-1 gap-3 sm:grid-cols-2 lg:grid-cols-4">
          <StatusCard
            icon={<Database size={14} />}
            title="PostgreSQL"
            status="green"
            headline="정상"
            caption="142.6 GB · QPS 218 · CPU 38%"
          />
          <StatusCard
            icon={<Clock size={14} />}
            title="배치 스케줄러"
            status="amber"
            headline="3 실행"
            caption="24h 성공 184 · 실패 2 · 예정 12"
          />
          <StatusCard
            icon={<PhoneOutgoing size={14} />}
            title="외부 호출"
            status="green"
            headline="4,218"
            caption="오늘 · 실패율 0.4% · 평균 412ms"
          />
          <StatusCard
            icon={<Workflow size={14} />}
            title="워크플로우"
            status="green"
            headline="36 활성"
            caption="오늘 실행 318 · 실패 2"
          />
        </section>

        {/* ===== 4) 회사별 활동 + 최근 변경 ===== */}
        <section className="grid grid-cols-1 gap-4 lg:grid-cols-[minmax(0,2fr)_minmax(260px,1fr)]">
          {/* 회사별 활동 */}
          <div
            className="rounded-xl border border-border p-4"
            style={{ background: "var(--v5-surface-solid)" }}
          >
            <div className="mb-3 flex items-center justify-between">
              <div>
                <div className="text-[0.9rem] font-bold text-foreground">
                  회사별 활동
                </div>
                <div className="text-[0.7rem] text-muted-foreground">6개 회사</div>
              </div>
              <AdminPill
                icon={<ChevronRight size={12} />}
                label="전체"
                reverse
              />
            </div>
            <div className="space-y-1">
              {COMPANY_ACTIVITY.map((r) => (
                <CompanyRow key={r.code} row={r} />
              ))}
            </div>
          </div>

          {/* 최근 변경 */}
          <div
            className="rounded-xl border border-border p-4"
            style={{ background: "var(--v5-surface-solid)" }}
          >
            <div className="mb-3 flex items-center justify-between">
              <div>
                <div className="text-[0.9rem] font-bold text-foreground">
                  최근 변경
                </div>
                <div className="text-[0.7rem] text-muted-foreground">오늘</div>
              </div>
              <AdminPill
                icon={<ChevronRight size={12} />}
                label="더보기"
                reverse
              />
            </div>
            <ul className="space-y-3">
              {RECENT_CHANGES.map((e, i) => (
                <ChangeItem key={i} item={e} />
              ))}
            </ul>
          </div>
        </section>

        {/* ===== 5) 빠른 진입 ===== */}
        <section>
          <div className="mb-3">
            <div className="text-[0.9rem] font-bold text-foreground">
              빠른 진입
            </div>
            <div className="text-[0.7rem] text-muted-foreground">
              자주 쓰는 관리 화면
            </div>
          </div>
          <div className="grid grid-cols-1 gap-3 sm:grid-cols-2 lg:grid-cols-4">
            <QuickLink
              href="/admin/userMng"
              icon={<Users size={16} />}
              label="사용자관리"
            />
            <QuickLink
              href="/admin/menu"
              icon={<FileText size={16} />}
              label="메뉴관리"
            />
            <QuickLink
              href="/admin/systemMng/roleMng"
              icon={<Shield size={16} />}
              label="권한관리"
            />
            <QuickLink
              href="/admin/systemMng/companyMng"
              icon={<Building2 size={16} />}
              label="회사관리"
            />
          </div>
        </section>
      </div>
    </div>
  );
}

/* ────────────────────────────────────────────────────────── */
/*   Sub components                                           */
/* ────────────────────────────────────────────────────────── */

function AdminPill({
  icon,
  label,
  tone,
  reverse,
}: {
  icon?: React.ReactNode;
  label: string;
  tone?: "primary";
  reverse?: boolean;
}) {
  const isPrimary = tone === "primary";
  return (
    <button
      type="button"
      className="inline-flex items-center gap-1.5 rounded-lg border px-2.5 py-1.5 text-[0.72rem] font-semibold transition-all hover:-translate-y-0.5"
      style={{
        background: isPrimary
          ? "rgb(var(--v5-primary-rgb))"
          : "var(--v5-surface-solid)",
        borderColor: isPrimary
          ? "rgb(var(--v5-primary-rgb))"
          : "var(--v5-border)",
        color: isPrimary ? "#fff" : "var(--foreground)",
        boxShadow: isPrimary ? "var(--v5-glow-sm)" : "none",
      }}
    >
      {!reverse && icon}
      <span>{label}</span>
      {reverse && icon}
    </button>
  );
}

function StatCard({
  label,
  value,
  unit,
  caption,
  tone,
  trend: _trend,
}: {
  label: string;
  value: string;
  unit?: string;
  caption: string;
  tone?: "primary" | "danger";
  trend?: string;
}) {
  const color =
    tone === "danger"
      ? "rgb(var(--v5-pink-rgb))"
      : "rgb(var(--v5-primary-rgb))";
  return (
    <div
      className="rounded-xl border border-border p-4 transition-all hover:-translate-y-0.5"
      style={{
        background: "var(--v5-surface-solid)",
        boxShadow: "0 0 0 1px transparent",
      }}
    >
      <div className="text-[0.8rem] font-semibold text-foreground leading-tight">
        {label}
      </div>
      <div className="mt-2 flex items-end gap-0.5 leading-none">
        <span
          className="text-[2.25rem] font-black"
          style={{ color, textShadow: `0 0 14px ${color}40` }}
        >
          {value}
        </span>
        {unit && (
          <span
            className="pb-1 text-[1.1rem] font-bold text-muted-foreground"
          >
            {unit}
          </span>
        )}
      </div>
      <div className="mt-1.5 text-[0.68rem] text-muted-foreground">
        {caption}
      </div>
    </div>
  );
}

function StatusCard({
  icon,
  title,
  status,
  headline,
  caption,
}: {
  icon: React.ReactNode;
  title: string;
  status: "green" | "amber" | "red";
  headline: string;
  caption: string;
}) {
  const dotColor = {
    green: "#22c55e",
    amber: "#f59e0b",
    red: "rgb(var(--v5-pink-rgb))",
  }[status];
  return (
    <div
      className="relative rounded-xl border border-border p-4 transition-all hover:-translate-y-0.5"
      style={{ background: "var(--v5-surface-solid)" }}
    >
      <span
        className="absolute right-4 top-4 h-1.5 w-1.5 rounded-full"
        style={{ background: dotColor, boxShadow: `0 0 8px ${dotColor}` }}
      />
      <div className="flex items-center gap-2 text-[0.72rem] text-muted-foreground">
        <span
          className="flex h-6 w-6 items-center justify-center rounded-md"
          style={{
            background: "rgba(var(--v5-primary-rgb), 0.1)",
            color: "rgb(var(--v5-primary-rgb))",
          }}
        >
          {icon}
        </span>
        <span className="font-medium">{title}</span>
      </div>
      <div className="mt-3 text-[1.25rem] font-bold text-foreground">
        {headline}
      </div>
      <div className="mt-0.5 text-[0.68rem] text-muted-foreground">
        {caption}
      </div>
    </div>
  );
}

type CompanyRowData = {
  code: string;
  name: string;
  users: number;
  menus: number;
  roles: number;
  lastSeen: string;
};

const COMPANY_ACTIVITY: CompanyRowData[] = [
  { code: "COMPANY_27", name: "탑실", users: 84, menus: 92, roles: 6, lastSeen: "2분 전" },
  { code: "COMPANY_9", name: "이멕스02", users: 42, menus: 92, roles: 4, lastSeen: "12분 전" },
  { code: "COMPANY_10", name: "큐엔씨", users: 16, menus: 48, roles: 3, lastSeen: "1시간 전" },
  { code: "COMPANY_7", name: "탑실 R3", users: 4, menus: 38, roles: 2, lastSeen: "4시간 전" },
  { code: "COMPANY_8", name: "실본드", users: 2, menus: 28, roles: 2, lastSeen: "어제" },
];

function CompanyRow({ row }: { row: CompanyRowData }) {
  return (
    <div className="grid grid-cols-[120px_minmax(0,1fr)_auto_auto_auto_auto] items-center gap-4 rounded-lg px-2 py-2 text-[0.74rem] hover:bg-muted/40">
      <span className="font-mono text-[0.68rem] text-muted-foreground">
        {row.code}
      </span>
      <span className="truncate font-medium text-foreground">{row.name}</span>
      <span
        className="font-bold"
        style={{ color: "rgb(var(--v5-primary-rgb))" }}
      >
        {row.users}{" "}
        <span className="font-normal text-muted-foreground">명</span>
      </span>
      <span>
        {row.menus}{" "}
        <span className="text-muted-foreground">메뉴</span>
      </span>
      <span>
        {row.roles}{" "}
        <span className="text-muted-foreground">권한</span>
      </span>
      <span className="min-w-[56px] text-right text-[0.66rem] text-muted-foreground">
        {row.lastSeen}
      </span>
    </div>
  );
}

type ChangeEvent = {
  dot: "green" | "amber" | "red";
  title: string;
  detail: string;
  timestamp: string;
  actor: string;
};

const RECENT_CHANGES: ChangeEvent[] = [
  {
    dot: "green",
    title: "메뉴 추가",
    detail: "COMPANY_27 / 생산관리 / 품목정보",
    timestamp: "14:22",
    actor: "mhkim",
  },
  {
    dot: "green",
    title: "권한 변경",
    detail: "ROLE_PROD_MGR (+2 사용자)",
    timestamp: "14:18",
    actor: "mhkim",
  },
  {
    dot: "green",
    title: "공통코드 추가",
    detail: "ITEM_TYPE / RAW_ADD (첨가제)",
    timestamp: "14:05",
    actor: "wace",
  },
  {
    dot: "red",
    title: "배치 실패",
    detail: "BATCH_EXPORT_INVOICE (timeout 30s)",
    timestamp: "13:54",
    actor: "system",
  },
  {
    dot: "amber",
    title: "사용자 잠금해제",
    detail: "khlee (로그인 5회 실패)",
    timestamp: "13:48",
    actor: "mhkim",
  },
  {
    dot: "green",
    title: "메뉴 순서 변경",
    detail: "COMPANY_9 / 구매 (seq 3 → 1)",
    timestamp: "13:34",
    actor: "mhkim",
  },
];

function ChangeItem({ item }: { item: ChangeEvent }) {
  const dotColor = {
    green: "#22c55e",
    amber: "#f59e0b",
    red: "rgb(var(--v5-pink-rgb))",
  }[item.dot];
  return (
    <li className="flex gap-2.5">
      <span
        className="mt-1.5 h-2 w-2 shrink-0 rounded-full"
        style={{ background: dotColor, boxShadow: `0 0 6px ${dotColor}` }}
      />
      <div className="min-w-0 flex-1">
        <div className="text-[0.78rem] font-semibold text-foreground">
          {item.title}
        </div>
        <div className="text-[0.7rem] text-muted-foreground truncate">
          {item.detail}
        </div>
        <div className="text-[0.65rem] text-muted-foreground/80 mt-0.5">
          {item.timestamp} · {item.actor}
        </div>
      </div>
    </li>
  );
}

function QuickLink({
  href,
  icon,
  label,
}: {
  href: string;
  icon: React.ReactNode;
  label: string;
}) {
  return (
    <Link
      href={href}
      className="group flex items-center justify-between rounded-xl border border-border px-4 py-3.5 transition-all hover:-translate-y-0.5 hover:border-[rgb(var(--v5-primary-rgb))]"
      style={{ background: "var(--v5-surface-solid)" }}
    >
      <span className="flex items-center gap-2.5">
        <span
          className="flex h-8 w-8 items-center justify-center rounded-lg"
          style={{
            background: "rgba(var(--v5-primary-rgb), 0.12)",
            color: "rgb(var(--v5-primary-rgb))",
          }}
        >
          {icon}
        </span>
        <span className="text-[0.85rem] font-semibold text-foreground">
          {label}
        </span>
      </span>
      <ChevronRight
        size={14}
        className="text-muted-foreground transition-transform group-hover:translate-x-0.5 group-hover:text-foreground"
      />
    </Link>
  );
}
