"use client";

import React, { useState, useEffect, useCallback } from "react";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Badge } from "@/components/ui/badge";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogDescription,
} from "@/components/ui/dialog";
import {
  Command,
  CommandEmpty,
  CommandGroup,
  CommandInput,
  CommandItem,
  CommandList,
} from "@/components/ui/command";
import {
  Popover,
  PopoverContent,
  PopoverTrigger,
} from "@/components/ui/popover";
import { cn } from "@/lib/utils";
import {
  Layout,
  Monitor,
  GitBranch,
  User,
  Database,
  Shield,
  Search,
  ChevronLeft,
  ChevronRight,
  Clock,
  Filter,
  Building2,
  Hash,
  FileText,
  RefreshCw,
  Check,
  ChevronsUpDown,
} from "lucide-react";
import {
  getAuditLogs,
  getAuditLogStats,
  getAuditLogUsers,
  AuditLogEntry,
  AuditLogFilters,
  AuditLogStats,
  AuditLogUser,
} from "@/lib/api/auditLog";
import { getCompanyList } from "@/lib/api/company";
import { useAuth } from "@/hooks/useAuth";
import { Company } from "@/types/company";

const RESOURCE_TYPE_CONFIG: Record<
  string,
  { label: string; icon: React.ElementType; color: string }
> = {
  MENU: { label: "메뉴", icon: Layout, color: "bg-primary/10 text-primary" },
  SCREEN: { label: "화면", icon: Monitor, color: "bg-purple-100 text-purple-700" },
  SCREEN_LAYOUT: { label: "레이아웃", icon: Monitor, color: "bg-purple-100 text-purple-700" },
  FLOW: { label: "플로우", icon: GitBranch, color: "bg-emerald-100 text-emerald-700" },
  FLOW_STEP: { label: "플로우 스텝", icon: GitBranch, color: "bg-emerald-100 text-emerald-700" },
  NODE_FLOW: { label: "플로우 제어", icon: GitBranch, color: "bg-teal-100 text-teal-700" },
  USER: { label: "사용자", icon: User, color: "bg-amber-100 text-orange-700" },
  ROLE: { label: "권한", icon: Shield, color: "bg-destructive/10 text-destructive" },
  COMPANY: { label: "회사", icon: Building2, color: "bg-indigo-100 text-indigo-700" },
  CODE_CATEGORY: { label: "코드 카테고리", icon: Hash, color: "bg-cyan-100 text-cyan-700" },
  CODE: { label: "코드", icon: Hash, color: "bg-cyan-100 text-cyan-700" },
  DATA: { label: "데이터", icon: Database, color: "bg-muted text-foreground" },
  TABLE: { label: "테이블", icon: Database, color: "bg-muted text-foreground" },
  NUMBERING_RULE: { label: "채번 규칙", icon: FileText, color: "bg-amber-100 text-amber-700" },
};

const ACTION_CONFIG: Record<string, { label: string; color: string }> = {
  CREATE: { label: "생성", color: "bg-emerald-100 text-emerald-700" },
  UPDATE: { label: "수정", color: "bg-primary/10 text-primary" },
  DELETE: { label: "삭제", color: "bg-destructive/10 text-destructive" },
  COPY: { label: "복사", color: "bg-violet-100 text-violet-700" },
  LOGIN: { label: "로그인", color: "bg-muted text-foreground" },
  STATUS_CHANGE: { label: "상태변경", color: "bg-amber-100 text-amber-700" },
  BATCH_CREATE: { label: "배치생성", color: "bg-emerald-100 text-emerald-700" },
  BATCH_UPDATE: { label: "배치수정", color: "bg-primary/10 text-primary" },
  BATCH_DELETE: { label: "배치삭제", color: "bg-destructive/10 text-destructive" },
};

function formatDateTime(dateStr: string): string {
  const d = new Date(dateStr);
  return d.toLocaleString("ko-KR", {
    year: "numeric",
    month: "2-digit",
    day: "2-digit",
    hour: "2-digit",
    minute: "2-digit",
    second: "2-digit",
  });
}

function formatTime(dateStr: string): string {
  const d = new Date(dateStr);
  return d.toLocaleTimeString("ko-KR", {
    hour: "2-digit",
    minute: "2-digit",
  });
}

const FIELD_NAME_MAP: Record<string, string> = {
  status: "상태",
  menuUrl: "메뉴 URL",
  menu_url: "메뉴 URL",
  menuNameKor: "메뉴명",
  menu_name_kor: "메뉴명",
  menuNameEng: "메뉴명(영)",
  menu_name_eng: "메뉴명(영)",
  screenName: "화면명",
  screen_name: "화면명",
  tableName: "테이블명",
  table_name: "테이블명",
  description: "설명",
  isActive: "활성 여부",
  is_active: "활성 여부",
  userName: "사용자명",
  user_name: "사용자명",
  userId: "사용자 ID",
  user_id: "사용자 ID",
  deptName: "부서명",
  dept_name: "부서명",
  authName: "권한명",
  authCode: "권한코드",
  companyCode: "회사코드",
  company_code: "회사코드",
  company_name: "회사명",
  name: "이름",
  user_password: "비밀번호",
  prefix: "접두사",
  ruleName: "규칙명",
  stepName: "스텝명",
  stepOrder: "스텝 순서",
  sourceScreenId: "원본 화면 ID",
  targetCompanyCode: "대상 회사코드",
  mainScreenName: "메인 화면명",
  screenCode: "화면코드",
  menuObjid: "메뉴 ID",
  deleteReason: "삭제 사유",
  force: "강제 삭제",
  deletedMenus: "삭제된 메뉴",
  failedMenuIds: "실패한 메뉴",
  deletedCount: "삭제 건수",
  items: "항목 수",
};

function formatFieldValue(value: unknown): string {
  if (value === null || value === undefined) return "(없음)";
  if (typeof value === "boolean") return value ? "예" : "아니오";
  if (Array.isArray(value)) return value.length > 0 ? `${value.length}건` : "(없음)";
  if (typeof value === "object") return JSON.stringify(value);
  return String(value);
}

function renderChanges(changes: Record<string, unknown>) {
  const before = (changes.before as Record<string, unknown>) || {};
  const after = (changes.after as Record<string, unknown>) || {};
  const fields = (changes.fields as string[]) || [];

  const allKeys = new Set([
    ...Object.keys(before),
    ...Object.keys(after),
    ...fields,
  ]);

  if (allKeys.size === 0) return null;

  const rows = Array.from(allKeys)
    .filter((key) => key !== "deletedMenus" && key !== "failedMenuIds")
    .map((key) => ({
      field: FIELD_NAME_MAP[key] || key,
      beforeVal: key in before ? formatFieldValue(before[key]) : null,
      afterVal: key in after ? formatFieldValue(after[key]) : null,
      isSensitive: fields.includes(key) && !(key in before) && !(key in after),
    }));

  const hasBefore = Object.keys(before).length > 0;
  const hasAfter = Object.keys(after).length > 0;

  return (
    <div className="overflow-hidden rounded border">
      <table className="w-full text-xs">
        <thead>
          <tr className="bg-muted/50">
            <th className="px-3 py-1.5 text-left font-medium">항목</th>
            {hasBefore && (
              <th className="px-3 py-1.5 text-left font-medium text-destructive">
                변경 전
              </th>
            )}
            {hasAfter && (
              <th className="px-3 py-1.5 text-left font-medium text-primary">
                변경 후
              </th>
            )}
          </tr>
        </thead>
        <tbody>
          {rows.map((row, i) => (
            <tr key={i} className="border-t">
              <td className="text-muted-foreground px-3 py-1.5 font-medium">
                {row.field}
              </td>
              {row.isSensitive ? (
                <td
                  colSpan={
                    (hasBefore ? 1 : 0) + (hasAfter ? 1 : 0)
                  }
                  className="px-3 py-1.5 italic text-amber-600"
                >
                  (보안 항목 - 값 비공개)
                </td>
              ) : (
                <>
                  {hasBefore && (
                    <td className="px-3 py-1.5">
                      {row.beforeVal !== null ? (
                        <span className="rounded bg-destructive/10 px-1.5 py-0.5 text-destructive">
                          {row.beforeVal}
                        </span>
                      ) : (
                        <span className="text-muted-foreground">-</span>
                      )}
                    </td>
                  )}
                  {hasAfter && (
                    <td className="px-3 py-1.5">
                      {row.afterVal !== null ? (
                        <span className="rounded bg-primary/10 px-1.5 py-0.5 text-primary">
                          {row.afterVal}
                        </span>
                      ) : (
                        <span className="text-muted-foreground">-</span>
                      )}
                    </td>
                  )}
                </>
              )}
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );
}

function formatDateGroup(dateStr: string): string {
  const d = new Date(dateStr);
  const today = new Date();
  const yesterday = new Date(today);
  yesterday.setDate(yesterday.getDate() - 1);

  if (d.toDateString() === today.toDateString()) return "오늘";
  if (d.toDateString() === yesterday.toDateString()) return "어제";

  return d.toLocaleDateString("ko-KR", {
    year: "numeric",
    month: "long",
    day: "numeric",
    weekday: "short",
  });
}

function groupByDate(entries: AuditLogEntry[]): Map<string, AuditLogEntry[]> {
  const groups = new Map<string, AuditLogEntry[]>();
  for (const entry of entries) {
    const dateKey = new Date(entry.created_at).toDateString();
    if (!groups.has(dateKey)) groups.set(dateKey, []);
    groups.get(dateKey)!.push(entry);
  }
  return groups;
}

export default function AuditLogPage() {
  const { user } = useAuth();
  const isSuperAdmin = user?.companyCode === "*" || user?.company_code === "*";

  const [entries, setEntries] = useState<AuditLogEntry[]>([]);
  const [total, setTotal] = useState(0);
  const [loading, setLoading] = useState(false);
  const [filters, setFilters] = useState<AuditLogFilters>({
    page: 1,
    limit: 50,
  });
  const [stats, setStats] = useState<AuditLogStats | null>(null);
  const [selectedEntry, setSelectedEntry] = useState<AuditLogEntry | null>(null);
  const [detailOpen, setDetailOpen] = useState(false);
  const [userComboOpen, setUserComboOpen] = useState(false);
  const [companyComboOpen, setCompanyComboOpen] = useState(false);
  const [companies, setCompanies] = useState<Company[]>([]);
  const [auditUsers, setAuditUsers] = useState<AuditLogUser[]>([]);

  const fetchCompanies = useCallback(async () => {
    if (!isSuperAdmin) return;
    try {
      const list = await getCompanyList({ status: "Y" });
      setCompanies(list);
    } catch (error) {
      console.error("회사 목록 조회 실패:", error);
    }
  }, [isSuperAdmin]);

  const fetchAuditUsers = useCallback(async () => {
    try {
      const result = await getAuditLogUsers(filters.companyCode);
      if (result.success) {
        setAuditUsers(result.data);
      }
    } catch (error) {
      console.error("사용자 목록 조회 실패:", error);
    }
  }, [filters.companyCode]);

  const fetchLogs = useCallback(async () => {
    setLoading(true);
    try {
      const result = await getAuditLogs(filters);
      if (result.success) {
        setEntries(result.data);
        setTotal(result.total);
      }
    } catch (error) {
      console.error("감사 로그 조회 실패:", error);
    } finally {
      setLoading(false);
    }
  }, [filters]);

  const fetchStats = useCallback(async () => {
    try {
      const result = await getAuditLogStats(filters.companyCode, 30);
      if (result.success) {
        setStats(result.data);
      }
    } catch (error) {
      console.error("통계 조회 실패:", error);
    }
  }, [filters.companyCode]);

  useEffect(() => {
    fetchCompanies();
  }, [fetchCompanies]);

  useEffect(() => {
    fetchAuditUsers();
  }, [fetchAuditUsers]);

  useEffect(() => {
    fetchLogs();
  }, [fetchLogs]);

  useEffect(() => {
    fetchStats();
  }, [fetchStats]);

  const totalPages = Math.ceil(total / (filters.limit || 50));

  const dateGroups = groupByDate(entries);

  const handleFilterChange = (key: keyof AuditLogFilters, value: string) => {
    const updates: Partial<AuditLogFilters> = { [key]: value || undefined, page: 1 };
    if (key === "companyCode") {
      updates.userId = undefined;
    }
    setFilters((prev) => ({ ...prev, ...updates }));
  };

  const handleSearch = (e: React.FormEvent) => {
    e.preventDefault();
    fetchLogs();
  };

  const openDetail = (entry: AuditLogEntry) => {
    setSelectedEntry(entry);
    setDetailOpen(true);
  };

  return (
    <div className="flex h-full flex-col gap-4 p-4 md:p-6">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold">통합 변경 이력</h1>
          <p className="text-muted-foreground text-sm">
            시스템 전체 변경 사항을 추적합니다
          </p>
        </div>
        <Button
          variant="outline"
          size="sm"
          onClick={() => {
            fetchLogs();
            fetchStats();
          }}
          disabled={loading}
        >
          <RefreshCw className={`mr-2 h-4 w-4 ${loading ? "animate-spin" : ""}`} />
          새로고침
        </Button>
      </div>

      {stats && (
        <div className="grid grid-cols-2 gap-3 md:grid-cols-4">
          <Card>
            <CardContent className="p-4">
              <p className="text-muted-foreground text-xs">최근 30일 총 변경</p>
              <p className="text-2xl font-bold">
                {stats.dailyCounts.reduce((s, d) => s + d.count, 0).toLocaleString()}건
              </p>
            </CardContent>
          </Card>
          <Card>
            <CardContent className="p-4">
              <p className="text-muted-foreground text-xs">리소스 유형</p>
              <p className="text-2xl font-bold">{stats.resourceTypeCounts.length}종</p>
            </CardContent>
          </Card>
          <Card>
            <CardContent className="p-4">
              <p className="text-muted-foreground text-xs">활동 사용자</p>
              <p className="text-2xl font-bold">{stats.topUsers.length}명</p>
            </CardContent>
          </Card>
          <Card>
            <CardContent className="p-4">
              <p className="text-muted-foreground text-xs">오늘 변경</p>
              <p className="text-2xl font-bold">
                {(
                  stats.dailyCounts.find(
                    (d) =>
                      new Date(d.date).toDateString() ===
                      new Date().toDateString()
                  )?.count || 0
                ).toLocaleString()}건
              </p>
            </CardContent>
          </Card>
        </div>
      )}

      <Card>
        <CardContent className="p-4">
          <form
            onSubmit={handleSearch}
            className="flex flex-col gap-3 sm:flex-wrap sm:flex-row sm:items-end"
          >
            <div className="w-full sm:min-w-[120px] sm:flex-1">
              <label className="text-xs font-medium">검색어</label>
              <div className="relative">
                <Search className="text-muted-foreground absolute left-2.5 top-2.5 h-4 w-4" />
                <Input
                  placeholder="이름, 요약, 사용자..."
                  value={filters.search || ""}
                  onChange={(e) => handleFilterChange("search", e.target.value)}
                  className="h-9 pl-8 text-sm"
                />
              </div>
            </div>

            <div className="w-full sm:w-[130px]">
              <label className="text-xs font-medium">유형</label>
              <Select
                value={filters.resourceType || "all"}
                onValueChange={(v) =>
                  handleFilterChange("resourceType", v === "all" ? "" : v)
                }
              >
                <SelectTrigger className="h-9 text-xs">
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="all">전체</SelectItem>
                  {Object.entries(RESOURCE_TYPE_CONFIG).map(([key, cfg]) => (
                    <SelectItem key={key} value={key}>
                      {cfg.label}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>

            <div className="w-full sm:w-[120px]">
              <label className="text-xs font-medium">동작</label>
              <Select
                value={filters.action || "all"}
                onValueChange={(v) =>
                  handleFilterChange("action", v === "all" ? "" : v)
                }
              >
                <SelectTrigger className="h-9 text-xs">
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="all">전체</SelectItem>
                  {Object.entries(ACTION_CONFIG).map(([key, cfg]) => (
                    <SelectItem key={key} value={key}>
                      {cfg.label}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>

            {isSuperAdmin && (
              <div className="w-full sm:w-[160px]">
                <label className="text-xs font-medium">회사</label>
                <Popover open={companyComboOpen} onOpenChange={setCompanyComboOpen}>
                  <PopoverTrigger asChild>
                    <Button
                      variant="outline"
                      role="combobox"
                      aria-expanded={companyComboOpen}
                      className="h-9 w-full justify-between text-xs"
                    >
                      {filters.companyCode
                        ? companies.find((c) => c.company_code === filters.companyCode)
                            ?.company_name || filters.companyCode
                        : "전체 회사"}
                      <ChevronsUpDown className="ml-2 h-3 w-3 shrink-0 opacity-50" />
                    </Button>
                  </PopoverTrigger>
                  <PopoverContent
                    className="p-0"
                    style={{ width: "var(--radix-popover-trigger-width)" }}
                    align="start"
                  >
                    <Command>
                      <CommandInput placeholder="회사 검색..." className="text-xs" />
                      <CommandList>
                        <CommandEmpty className="py-3 text-center text-xs">
                          회사를 찾을 수 없습니다
                        </CommandEmpty>
                        <CommandGroup>
                          <CommandItem
                            value="__all_companies__"
                            onSelect={() => {
                              handleFilterChange("companyCode", "");
                              setCompanyComboOpen(false);
                            }}
                            className="text-xs"
                          >
                            <Check
                              className={cn(
                                "mr-2 h-3 w-3",
                                !filters.companyCode ? "opacity-100" : "opacity-0"
                              )}
                            />
                            전체 회사
                          </CommandItem>
                          {companies.map((company) => (
                            <CommandItem
                              key={company.company_code}
                              value={`${company.company_name} ${company.company_code}`}
                              onSelect={() => {
                                handleFilterChange(
                                  "companyCode",
                                  filters.companyCode === company.company_code
                                    ? ""
                                    : company.company_code
                                );
                                setCompanyComboOpen(false);
                              }}
                              className="text-xs"
                            >
                              <Check
                                className={cn(
                                  "mr-2 h-3 w-3",
                                  filters.companyCode === company.company_code
                                    ? "opacity-100"
                                    : "opacity-0"
                                )}
                              />
                              <div className="flex flex-col">
                                <span className="font-medium">{company.company_name}</span>
                                <span className="text-muted-foreground text-[10px]">
                                  {company.company_code}
                                </span>
                              </div>
                            </CommandItem>
                          ))}
                        </CommandGroup>
                      </CommandList>
                    </Command>
                  </PopoverContent>
                </Popover>
              </div>
            )}

            <div className="w-full sm:w-[160px]">
              <label className="text-xs font-medium">사용자</label>
              <Popover open={userComboOpen} onOpenChange={setUserComboOpen}>
                <PopoverTrigger asChild>
                  <Button
                    variant="outline"
                    role="combobox"
                    aria-expanded={userComboOpen}
                    className="h-9 w-full justify-between text-xs"
                  >
                    {filters.userId
                      ? auditUsers.find((u) => u.user_id === filters.userId)
                          ?.user_name || filters.userId
                      : "전체"}
                    <ChevronsUpDown className="ml-2 h-3 w-3 shrink-0 opacity-50" />
                  </Button>
                </PopoverTrigger>
                <PopoverContent
                  className="p-0"
                  style={{ width: "var(--radix-popover-trigger-width)" }}
                  align="start"
                >
                  <Command>
                    <CommandInput placeholder="사용자 검색..." className="text-xs" />
                    <CommandList>
                      <CommandEmpty className="py-3 text-center text-xs">
                        사용자를 찾을 수 없습니다
                      </CommandEmpty>
                      <CommandGroup>
                        <CommandItem
                          value="__all_users__"
                          onSelect={() => {
                            handleFilterChange("userId", "");
                            setUserComboOpen(false);
                          }}
                          className="text-xs"
                        >
                          <Check
                            className={cn(
                              "mr-2 h-3 w-3",
                              !filters.userId ? "opacity-100" : "opacity-0"
                            )}
                          />
                          전체
                        </CommandItem>
                        {auditUsers.map((u) => (
                          <CommandItem
                            key={u.user_id}
                            value={`${u.user_name} ${u.user_id}`}
                            onSelect={() => {
                              handleFilterChange(
                                "userId",
                                filters.userId === u.user_id ? "" : u.user_id
                              );
                              setUserComboOpen(false);
                            }}
                            className="text-xs"
                          >
                            <Check
                              className={cn(
                                "mr-2 h-3 w-3",
                                filters.userId === u.user_id
                                  ? "opacity-100"
                                  : "opacity-0"
                              )}
                            />
                            <div className="flex flex-col">
                              <span className="font-medium">{u.user_name}</span>
                              <span className="text-muted-foreground text-[10px]">
                                {u.user_id} ({u.count}건)
                              </span>
                            </div>
                          </CommandItem>
                        ))}
                      </CommandGroup>
                    </CommandList>
                  </Command>
                </PopoverContent>
              </Popover>
            </div>

            <div className="w-full sm:w-[130px]">
              <label className="text-xs font-medium">시작일</label>
              <Input
                type="date"
                value={filters.dateFrom || ""}
                onChange={(e) => handleFilterChange("dateFrom", e.target.value)}
                className="h-9 text-xs"
              />
            </div>

            <div className="w-full sm:w-[130px]">
              <label className="text-xs font-medium">종료일</label>
              <Input
                type="date"
                value={filters.dateTo || ""}
                onChange={(e) => handleFilterChange("dateTo", e.target.value)}
                className="h-9 text-xs"
              />
            </div>

            <Button type="submit" size="sm" className="h-9 w-full sm:w-auto">
              <Filter className="mr-1 h-4 w-4" />
              필터 적용
            </Button>
          </form>
        </CardContent>
      </Card>

      <Card className="flex-1 overflow-hidden">
        <CardHeader className="border-b px-4 py-3">
          <div className="flex items-center justify-between">
            <CardTitle className="text-base">
              변경 이력 ({total.toLocaleString()}건)
            </CardTitle>
            <div className="flex items-center gap-2 text-sm">
              <Button
                variant="ghost"
                size="icon"
                className="h-8 w-8"
                disabled={filters.page === 1}
                onClick={() =>
                  setFilters((prev) => ({
                    ...prev,
                    page: (prev.page || 1) - 1,
                  }))
                }
              >
                <ChevronLeft className="h-4 w-4" />
              </Button>
              <span className="text-muted-foreground text-xs">
                {filters.page || 1} / {totalPages || 1}
              </span>
              <Button
                variant="ghost"
                size="icon"
                className="h-8 w-8"
                disabled={(filters.page || 1) >= totalPages}
                onClick={() =>
                  setFilters((prev) => ({
                    ...prev,
                    page: (prev.page || 1) + 1,
                  }))
                }
              >
                <ChevronRight className="h-4 w-4" />
              </Button>
            </div>
          </div>
        </CardHeader>
        <CardContent className="overflow-auto p-0" style={{ maxHeight: "calc(100vh - 400px)" }}>
          {loading ? (
            <div className="flex items-center justify-center py-12">
              <RefreshCw className="text-muted-foreground h-6 w-6 animate-spin" />
            </div>
          ) : entries.length === 0 ? (
            <div className="flex flex-col items-center justify-center py-12 text-center">
              <Clock className="text-muted-foreground mb-3 h-10 w-10" />
              <p className="text-muted-foreground text-sm">
                변경 이력이 없습니다
              </p>
            </div>
          ) : (
            <div className="divide-y">
              {Array.from(dateGroups.entries()).map(([dateKey, items]) => (
                <div key={dateKey}>
                  <div className="bg-muted/50 sticky top-0 z-10 border-b px-4 py-2">
                    <span className="text-xs font-semibold">
                      {formatDateGroup(items[0].created_at)}
                    </span>
                    <span className="text-muted-foreground ml-2 text-xs">
                      {items.length}건
                    </span>
                  </div>
                  {items.map((entry) => {
                    const rtConfig =
                      RESOURCE_TYPE_CONFIG[entry.resource_type] ||
                      RESOURCE_TYPE_CONFIG.DATA;
                    const actConfig =
                      ACTION_CONFIG[entry.action] || ACTION_CONFIG.UPDATE;
                    const IconComp = rtConfig.icon;

                    return (
                      <div
                        key={entry.id}
                        className="hover:bg-muted/30 flex cursor-pointer items-start gap-3 px-4 py-3 transition-colors"
                        onClick={() => openDetail(entry)}
                      >
                        <div
                          className={`mt-0.5 flex h-8 w-8 shrink-0 items-center justify-center rounded-full ${rtConfig.color}`}
                        >
                          <IconComp className="h-4 w-4" />
                        </div>
                        <div className="min-w-0 flex-1">
                          <div className="flex items-center gap-2">
                            <span className="text-sm font-medium">
                              {entry.user_name || entry.user_id}
                            </span>
                            <Badge
                              variant="secondary"
                              className={`text-[10px] ${rtConfig.color}`}
                            >
                              {rtConfig.label}
                            </Badge>
                            <Badge
                              variant="secondary"
                              className={`text-[10px] ${actConfig.color}`}
                            >
                              {actConfig.label}
                            </Badge>
                            {entry.company_code && entry.company_code !== "*" && (
                              <span className="text-muted-foreground text-[10px]">
                                [{entry.company_name || entry.company_code}]
                              </span>
                            )}
                          </div>
                          <p className="text-muted-foreground mt-0.5 truncate text-xs">
                            {entry.summary || entry.resource_name || "-"}
                          </p>
                        </div>
                        <span className="text-muted-foreground shrink-0 text-xs">
                          {formatTime(entry.created_at)}
                        </span>
                      </div>
                    );
                  })}
                </div>
              ))}
            </div>
          )}
        </CardContent>
      </Card>

      <Dialog open={detailOpen} onOpenChange={setDetailOpen}>
        <DialogContent className="max-w-[95vw] sm:max-w-[600px]">
          <DialogHeader>
            <DialogTitle className="text-base sm:text-lg">
              변경 상세 정보
            </DialogTitle>
            <DialogDescription className="text-xs sm:text-sm">
              {selectedEntry &&
                formatDateTime(selectedEntry.created_at)}
            </DialogDescription>
          </DialogHeader>
          {selectedEntry && (
            <div className="space-y-3 text-sm">
              <div className="grid grid-cols-2 gap-3">
                <div>
                  <label className="text-muted-foreground text-xs">
                    사용자
                  </label>
                  <p className="font-medium">
                    {selectedEntry.user_name || selectedEntry.user_id}
                  </p>
                </div>
                <div>
                  <label className="text-muted-foreground text-xs">
                    회사
                  </label>
                  <p className="font-medium">
                    {selectedEntry.company_name || selectedEntry.company_code}
                  </p>
                </div>
                <div>
                  <label className="text-muted-foreground text-xs">
                    리소스 유형
                  </label>
                  <p className="font-medium">
                    {RESOURCE_TYPE_CONFIG[selectedEntry.resource_type]?.label ||
                      selectedEntry.resource_type}
                  </p>
                </div>
                <div>
                  <label className="text-muted-foreground text-xs">동작</label>
                  <p className="font-medium">
                    {ACTION_CONFIG[selectedEntry.action]?.label ||
                      selectedEntry.action}
                  </p>
                </div>
                {selectedEntry.resource_name && (
                  <div className="col-span-2">
                    <label className="text-muted-foreground text-xs">
                      리소스명
                    </label>
                    <p className="font-medium">{selectedEntry.resource_name}</p>
                  </div>
                )}
                {selectedEntry.table_name && (
                  <div>
                    <label className="text-muted-foreground text-xs">
                      테이블명
                    </label>
                    <p className="font-medium">{selectedEntry.table_name}</p>
                  </div>
                )}
                {selectedEntry.ip_address && (
                  <div>
                    <label className="text-muted-foreground text-xs">
                      IP 주소
                    </label>
                    <p className="font-medium">{selectedEntry.ip_address}</p>
                  </div>
                )}
              </div>

              {selectedEntry.summary && (
                <div>
                  <label className="text-muted-foreground text-xs">요약</label>
                  <p className="bg-muted rounded p-2 text-xs">
                    {selectedEntry.summary}
                  </p>
                </div>
              )}

              {selectedEntry.changes && (
                <div>
                  <label className="text-muted-foreground text-xs">
                    변경 내역
                  </label>
                  <div className="mt-1">
                    {renderChanges(
                      selectedEntry.changes as Record<string, unknown>
                    )}
                  </div>
                </div>
              )}

              {selectedEntry.request_path && (
                <div>
                  <label className="text-muted-foreground text-xs">
                    API 경로
                  </label>
                  <p className="text-muted-foreground text-xs">
                    {selectedEntry.request_path}
                  </p>
                </div>
              )}
            </div>
          )}
        </DialogContent>
      </Dialog>
    </div>
  );
}
