import { useState } from 'react';
import { Tabs, Tag } from 'antd';
import { ProTable, type ProColumns } from '@ant-design/pro-components';
import PageContainer from '@/components/common/PageContainer';
import { logApi, ApiAccessLogResp, DataChangeLogResp, LoginLogResp } from '@/api/log';

export default function SystemLog() {
  const [tab, setTab] = useState('login');

  return (
    <PageContainer title="시스템 로그" description="로그인 / API 호출 / 데이터 변경 이력">
      <Tabs
        activeKey={tab}
        onChange={setTab}
        items={[
          { key: 'login', label: '로그인 이력', children: <LoginTable /> },
          { key: 'api',   label: 'API 호출',   children: <ApiTable /> },
          { key: 'change', label: '변경 이력', children: <ChangeTable /> },
        ]}
      />
    </PageContainer>
  );
}

function LoginTable() {
  const columns: ProColumns<LoginLogResp>[] = [
    { title: '로그인일시', dataIndex: 'loginAt', width: 170, valueType: 'dateTime' },
    {
      title: '구분', dataIndex: 'loginType', width: 90, valueType: 'select',
      valueEnum: { LOGIN: { text: '로그인' }, LOGOUT: { text: '로그아웃' }, FAIL: { text: '실패' } },
      render: (_, r) => {
        const c = r.loginType === 'LOGIN' ? 'success' : r.loginType === 'FAIL' ? 'error' : 'default';
        return <Tag color={c}>{r.loginType}</Tag>;
      },
    },
    { title: 'ID', dataIndex: 'username', width: 120 },
    { title: 'IP', dataIndex: 'ipAddress', width: 130, search: false },
    { title: 'User-Agent', dataIndex: 'userAgent', ellipsis: true, search: false },
    { title: '실패사유', dataIndex: 'failReason', width: 200, search: false },
  ];
  return (
    <ProTable<LoginLogResp>
      rowKey="logId" columns={columns} dateFormatter="string" scroll={{ x: 1100 }}
      request={async (params) => {
        const { current, pageSize, ...rest } = params as any;
        const res = await logApi.login({ ...rest, pageNum: current, pageSize });
        return { data: res.list, total: res.total, success: true };
      }}
      pagination={{ pageSize: 50, showTotal: (t) => `총 ${t.toLocaleString()}건` }}
      search={{ labelWidth: 'auto', searchText: '검색', resetText: '초기화', collapsed: false, collapseRender: false }}
    />
  );
}

function ApiTable() {
  const columns: ProColumns<ApiAccessLogResp>[] = [
    { title: '시각', dataIndex: 'createdAt', width: 170, valueType: 'dateTime' },
    { title: 'Method', dataIndex: 'requestMethod', width: 80, search: false,
      render: (_, r) => <Tag color="blue">{r.requestMethod}</Tag> },
    { title: 'URL', dataIndex: 'requestUrl', ellipsis: true, search: false },
    { title: 'Status', dataIndex: 'responseStatus', width: 80, align: 'right', search: false,
      render: (_, r) => {
        const s = r.responseStatus ?? 0;
        const c = s >= 500 ? 'error' : s >= 400 ? 'warning' : s >= 300 ? 'processing' : 'success';
        return <Tag color={c}>{s}</Tag>;
      } },
    { title: 'Time(ms)', dataIndex: 'responseTime', width: 90, align: 'right', search: false },
    { title: 'User', dataIndex: 'username', width: 110 },
    { title: 'IP', dataIndex: 'ipAddress', width: 130, search: false },
  ];
  return (
    <ProTable<ApiAccessLogResp>
      rowKey="logId" columns={columns} dateFormatter="string" scroll={{ x: 1200 }}
      request={async (params) => {
        const { current, pageSize, ...rest } = params as any;
        const res = await logApi.api({ ...rest, pageNum: current, pageSize });
        return { data: res.list, total: res.total, success: true };
      }}
      pagination={{ pageSize: 50, showTotal: (t) => `총 ${t.toLocaleString()}건` }}
      search={{ labelWidth: 'auto', searchText: '검색', resetText: '초기화', collapsed: false, collapseRender: false }}
    />
  );
}

function ChangeTable() {
  const columns: ProColumns<DataChangeLogResp>[] = [
    { title: '시각', dataIndex: 'createdAt', width: 170, valueType: 'dateTime' },
    { title: '테이블', dataIndex: 'tableName', width: 150 },
    { title: 'Action', dataIndex: 'actionType', width: 90, search: false,
      render: (_, r) => {
        const c = r.actionType === 'CREATE' ? 'success' : r.actionType === 'DELETE' ? 'error' : 'processing';
        return <Tag color={c}>{r.actionType}</Tag>;
      } },
    { title: 'Record ID', dataIndex: 'recordId', width: 100, search: false },
    { title: '메뉴', dataIndex: 'menuCode', width: 130, search: false },
    { title: '사용자', dataIndex: 'username', width: 110 },
    { title: '사유', dataIndex: 'changeReason', ellipsis: true, search: false },
  ];
  return (
    <ProTable<DataChangeLogResp>
      rowKey="logId" columns={columns} dateFormatter="string" scroll={{ x: 1100 }}
      request={async (params) => {
        const { current, pageSize, ...rest } = params as any;
        const res = await logApi.change({ ...rest, pageNum: current, pageSize });
        return { data: res.list, total: res.total, success: true };
      }}
      pagination={{ pageSize: 50, showTotal: (t) => `총 ${t.toLocaleString()}건` }}
      search={{ labelWidth: 'auto', searchText: '검색', resetText: '초기화', collapsed: false, collapseRender: false }}
    />
  );
}
