import { useState } from 'react';
import {
  Card,
  Table,
  Tag,
  Button,
  Space,
  Select,
  DatePicker,
  Drawer,
  Descriptions,
  Typography,
  Spin,
} from 'antd';
import { ReloadOutlined } from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table';
import dayjs from 'dayjs';
import type { Dayjs } from 'dayjs';
import {
  useAuditLogs,
  useAuditActionTypes,
  useAuditEntityTypes,
  type AuditLogQueryParams,
} from '../../application';
import type { AuditLogDto } from '../../infrastructure';

const { Title, Text } = Typography;
const { RangePicker } = DatePicker;

const RESULT_COLORS: Record<string, string> = {
  SUCCESS: 'success',
  FAILED: 'error',
};

const ACTOR_TYPE_LABELS: Record<string, string> = {
  USER: '用户',
  ADMIN: '管理员',
  SYSTEM: '系统',
};

export function AuditPage() {
  // Filter state
  const [filters, setFilters] = useState<AuditLogQueryParams>({
    page: 1,
    pageSize: 20,
  });
  const [dateRange, setDateRange] = useState<[Dayjs, Dayjs] | null>(null);

  // Detail drawer
  const [drawerOpen, setDrawerOpen] = useState(false);
  const [selectedLog, setSelectedLog] = useState<AuditLogDto | null>(null);

  // Queries
  const { data: logsData, isLoading, refetch } = useAuditLogs({
    ...filters,
    startDate: dateRange?.[0]?.format('YYYY-MM-DD'),
    endDate: dateRange?.[1]?.format('YYYY-MM-DD'),
  });
  const { data: actionTypesData } = useAuditActionTypes();
  const { data: entityTypesData } = useAuditEntityTypes();

  const showDetail = (log: AuditLogDto) => {
    setSelectedLog(log);
    setDrawerOpen(true);
  };

  const handleFilterChange = (key: keyof AuditLogQueryParams, value: string | undefined) => {
    setFilters((prev) => ({
      ...prev,
      [key]: value,
      page: 1, // Reset to first page when filter changes
    }));
  };

  const handleReset = () => {
    setFilters({ page: 1, pageSize: 20 });
    setDateRange(null);
  };

  const columns: ColumnsType<AuditLogDto> = [
    {
      title: '时间',
      dataIndex: 'createdAt',
      key: 'createdAt',
      width: 180,
      render: (v) => dayjs(v).format('YYYY-MM-DD HH:mm:ss'),
    },
    {
      title: '操作者类型',
      dataIndex: 'actorType',
      key: 'actorType',
      width: 100,
      render: (v) => ACTOR_TYPE_LABELS[v] || v,
    },
    {
      title: '操作者',
      dataIndex: 'actorName',
      key: 'actorName',
      width: 120,
      render: (v) => v || '-',
    },
    {
      title: '操作',
      dataIndex: 'action',
      key: 'action',
      width: 180,
    },
    {
      title: '实体类型',
      dataIndex: 'entityType',
      key: 'entityType',
      width: 120,
    },
    {
      title: '实体ID',
      dataIndex: 'entityId',
      key: 'entityId',
      width: 120,
      ellipsis: true,
      render: (v) => v || '-',
    },
    {
      title: '描述',
      dataIndex: 'description',
      key: 'description',
      ellipsis: true,
      render: (v) => v || '-',
    },
    {
      title: '结果',
      dataIndex: 'result',
      key: 'result',
      width: 80,
      render: (v) => (
        <Tag color={RESULT_COLORS[v]}>{v === 'SUCCESS' ? '成功' : '失败'}</Tag>
      ),
    },
    {
      title: '操作',
      key: 'action',
      width: 80,
      render: (_, record) => (
        <Button size="small" onClick={() => showDetail(record)}>
          详情
        </Button>
      ),
    },
  ];

  return (
    <div className="p-6">
      <div className="flex items-center justify-between mb-6">
        <Title level={4} className="mb-0">审计日志</Title>
        <Button icon={<ReloadOutlined />} onClick={() => refetch()}>
          刷新
        </Button>
      </div>

      {/* Filters */}
      <Card className="mb-4">
        <Space wrap>
          <span>操作类型：</span>
          <Select
            value={filters.action}
            onChange={(v) => handleFilterChange('action', v)}
            options={[
              { value: undefined, label: '全部' },
              ...(actionTypesData?.actions || []).map((a) => ({ value: a, label: a })),
            ]}
            style={{ width: 180 }}
            allowClear
            placeholder="全部"
          />

          <span className="ml-4">实体类型：</span>
          <Select
            value={filters.entityType}
            onChange={(v) => handleFilterChange('entityType', v)}
            options={[
              { value: undefined, label: '全部' },
              ...(entityTypesData?.entityTypes || []).map((e) => ({ value: e, label: e })),
            ]}
            style={{ width: 150 }}
            allowClear
            placeholder="全部"
          />

          <span className="ml-4">操作者类型：</span>
          <Select
            value={filters.actorType}
            onChange={(v) => handleFilterChange('actorType', v)}
            options={[
              { value: undefined, label: '全部' },
              { value: 'USER', label: '用户' },
              { value: 'ADMIN', label: '管理员' },
              { value: 'SYSTEM', label: '系统' },
            ]}
            style={{ width: 120 }}
            allowClear
            placeholder="全部"
          />

          <span className="ml-4">结果：</span>
          <Select
            value={filters.result}
            onChange={(v) => handleFilterChange('result', v)}
            options={[
              { value: undefined, label: '全部' },
              { value: 'SUCCESS', label: '成功' },
              { value: 'FAILED', label: '失败' },
            ]}
            style={{ width: 100 }}
            allowClear
            placeholder="全部"
          />

          <span className="ml-4">日期范围：</span>
          <RangePicker
            value={dateRange}
            onChange={(dates) => {
              if (dates && dates[0] && dates[1]) {
                setDateRange([dates[0], dates[1]]);
              } else {
                setDateRange(null);
              }
              setFilters((prev) => ({ ...prev, page: 1 }));
            }}
          />

          <Button onClick={handleReset}>重置</Button>
        </Space>
      </Card>

      {/* Logs Table */}
      <Card>
        <Spin spinning={isLoading}>
          <Table
            columns={columns}
            dataSource={logsData?.items || []}
            rowKey="id"
            pagination={{
              current: filters.page,
              pageSize: filters.pageSize,
              total: logsData?.total || 0,
              showSizeChanger: true,
              showQuickJumper: true,
              showTotal: (total) => `共 ${total} 条`,
              onChange: (page, pageSize) => {
                setFilters((prev) => ({ ...prev, page, pageSize }));
              },
            }}
            scroll={{ x: 1200 }}
          />
        </Spin>
      </Card>

      {/* Detail Drawer */}
      <Drawer
        title="审计日志详情"
        open={drawerOpen}
        onClose={() => setDrawerOpen(false)}
        width={600}
      >
        {selectedLog && (
          <div>
            <Descriptions bordered column={1} size="small">
              <Descriptions.Item label="日志ID">{selectedLog.id}</Descriptions.Item>
              <Descriptions.Item label="时间">
                {dayjs(selectedLog.createdAt).format('YYYY-MM-DD HH:mm:ss')}
              </Descriptions.Item>
              <Descriptions.Item label="操作者类型">
                {ACTOR_TYPE_LABELS[selectedLog.actorType] || selectedLog.actorType}
              </Descriptions.Item>
              <Descriptions.Item label="操作者ID">
                {selectedLog.actorId || '-'}
              </Descriptions.Item>
              <Descriptions.Item label="操作者名称">
                {selectedLog.actorName || '-'}
              </Descriptions.Item>
              <Descriptions.Item label="操作">{selectedLog.action}</Descriptions.Item>
              <Descriptions.Item label="实体类型">
                {selectedLog.entityType}
              </Descriptions.Item>
              <Descriptions.Item label="实体ID">
                {selectedLog.entityId || '-'}
              </Descriptions.Item>
              <Descriptions.Item label="描述">
                {selectedLog.description || '-'}
              </Descriptions.Item>
              <Descriptions.Item label="结果">
                <Tag color={RESULT_COLORS[selectedLog.result]}>
                  {selectedLog.result === 'SUCCESS' ? '成功' : '失败'}
                </Tag>
              </Descriptions.Item>
              {selectedLog.errorMessage && (
                <Descriptions.Item label="错误信息">
                  <Text type="danger">{selectedLog.errorMessage}</Text>
                </Descriptions.Item>
              )}
              <Descriptions.Item label="IP地址">
                {selectedLog.ipAddress || '-'}
              </Descriptions.Item>
              <Descriptions.Item label="请求ID">
                {selectedLog.requestId || '-'}
              </Descriptions.Item>
            </Descriptions>

            {/* Changed Fields */}
            {selectedLog.changedFields && selectedLog.changedFields.length > 0 && (
              <div className="mt-4">
                <Text strong>变更字段</Text>
                <div className="mt-2 p-3 bg-gray-50 rounded">
                  {selectedLog.changedFields.map((field) => (
                    <Tag key={field} className="mb-1">
                      {field}
                    </Tag>
                  ))}
                </div>
              </div>
            )}

            {/* Old Values */}
            {selectedLog.oldValues && Object.keys(selectedLog.oldValues).length > 0 && (
              <div className="mt-4">
                <Text strong>原值</Text>
                <pre className="mt-2 p-3 bg-gray-50 rounded text-sm overflow-auto max-h-48">
                  {JSON.stringify(selectedLog.oldValues, null, 2)}
                </pre>
              </div>
            )}

            {/* New Values */}
            {selectedLog.newValues && Object.keys(selectedLog.newValues).length > 0 && (
              <div className="mt-4">
                <Text strong>新值</Text>
                <pre className="mt-2 p-3 bg-gray-50 rounded text-sm overflow-auto max-h-48">
                  {JSON.stringify(selectedLog.newValues, null, 2)}
                </pre>
              </div>
            )}

            {/* User Agent */}
            {selectedLog.userAgent && (
              <div className="mt-4">
                <Text strong>User Agent</Text>
                <div className="mt-2 p-3 bg-gray-50 rounded text-sm break-all">
                  {selectedLog.userAgent}
                </div>
              </div>
            )}
          </div>
        )}
      </Drawer>
    </div>
  );
}
