'use client';

import React, { useEffect, useState, useCallback } from 'react';
import { Card, Table, DatePicker, Select, Tag, Button, Space, message, Modal, Descriptions, Input } from 'antd';
import { DownloadOutlined, SearchOutlined, EyeOutlined } from '@ant-design/icons';
import dayjs from 'dayjs';
import AdminLayout from '@/components/AdminLayout';
import { getLogs, exportLogs, getClients } from '@/services/api';

const { RangePicker } = DatePicker;

export default function LogsPage() {
  const [data, setData] = useState<any[]>([]);
  const [total, setTotal] = useState(0);
  const [loading, setLoading] = useState(false);
  const [clients, setClients] = useState<any[]>([]);
  const [filters, setFilters] = useState<Record<string, unknown>>({
    page: 1, limit: 50,
  });
  const [detailVisible, setDetailVisible] = useState(false);
  const [currentLog, setCurrentLog] = useState<any>(null);

  useEffect(() => {
    getClients().then(res => setClients(res.data)).catch(() => {});
    fetchLogs();
  }, []);

  const fetchLogs = useCallback(async () => {
    setLoading(true);
    try {
      const res = await getLogs(filters);
      setData(res.data.data);
      setTotal(res.data.total);
    } catch (err) {
      message.error('获取日志失败');
    } finally {
      setLoading(false);
    }
  }, [filters]);

  const handleSearch = () => {
    setFilters(f => ({ ...f, page: 1 }));
    fetchLogs();
  };

  const handleExport = async () => {
    try {
      const res = await exportLogs(filters);
      let csvContent = '';
      let responseText = '';

      if (res.data instanceof Blob) {
        responseText = await res.data.text();
      } else {
        responseText = typeof res.data === 'string' ? res.data : JSON.stringify(res.data);
      }

      try {
        const jsonData = JSON.parse(responseText);
        if (jsonData && jsonData.data && Array.isArray(jsonData.data)) {
          const headers = ['ID', '客户ID', '接口', '响应码', '返回条数', '耗时(ms)', 'IP', '时间'];
          csvContent = headers.join(',') + '\n';

          for (const log of jsonData.data) {
            const row = [
              log.id || '',
              log.client_id || '',
              log.endpoint || '',
              log.response_code || '',
              log.record_count || '',
              log.duration_ms || '',
              log.ip_address || '',
              log.created_at ? dayjs(log.created_at).format('YYYY-MM-DD HH:mm:ss') : '',
            ];
            csvContent += row.map(cell => `"${String(cell).replace(/"/g, '""')}"`).join(',') + '\n';
          }
        } else {
          csvContent = responseText;
        }
      } catch {
        csvContent = responseText;
      }

      const url = window.URL.createObjectURL(new Blob(['\uFEFF' + csvContent], { type: 'text/csv;charset=utf-8' }));
      const link = document.createElement('a');
      link.href = url;
      link.download = `api_logs_${dayjs().format('YYYYMMDD')}.csv`;
      link.click();
      window.URL.revokeObjectURL(url);
    } catch (err) {
      message.error('导出失败');
    }
  };

  const showDetail = (record: any) => {
    setCurrentLog(record);
    setDetailVisible(true);
  };

  const columns = [
    {
      title: '时间', dataIndex: 'created_at', width: 170,
      render: (val: string) => val ? dayjs(val).format('YYYY-MM-DD HH:mm:ss') : '-',
    },
    {
      title: '用户', dataIndex: 'client_id', width: 160,
      render: (val: number) => clients.find(c => c.id === val)?.name || `ID:${val}`,
    },
    {
      title: '接口', dataIndex: 'endpoint', width: 140,
      render: (val: string) => (
        <Tag color={val.includes('chuku') ? 'blue' : 'green'}>
          {val === '/api/v1/chuku' ? '销售' : val === '/api/v1/ruku' ? '入库' : val}
        </Tag>
      ),
    },
    {
      title: '请求参数', dataIndex: 'request_params', width: 200, ellipsis: true,
      render: (val: any) => val ? JSON.stringify(val) : '-',
    },
    {
      title: '响应码', dataIndex: 'response_code', width: 90,
      render: (val: number) => {
        const color = val === 200 ? 'green' : val === 429 ? 'orange' : 'red';
        return <Tag color={color}>{val}</Tag>;
      },
    },
    { title: '返回条数', dataIndex: 'record_count', width: 90 },
    {
      title: '耗时', dataIndex: 'duration_ms', width: 90,
      render: (val: number) => val ? `${val}ms` : '-',
    },
    {
      title: 'IP', dataIndex: 'ip_address', width: 130,
    },
    {
      title: '操作', key: 'action', width: 100, fixed: 'right' as const,
      render: (_: any, record: any) => (
        <Button size="small" icon={<EyeOutlined />} onClick={() => showDetail(record)}>
          详情
        </Button>
      ),
    },
  ];

  return (
    <AdminLayout>
      <Card
        title="API 调用日志审计"
        extra={
          <Space>
            <RangePicker
              onChange={(dates) => {
                setFilters(f => ({
                  ...f,
                  start_date: dates?.[0]?.format('YYYY-MM-DD') || undefined,
                  end_date: dates?.[1]?.format('YYYY-MM-DD') || undefined,
                }));
              }}
            />
            <Input
              placeholder="用户名称"
              style={{ width: 180 }}
              onChange={(e) => setFilters(f => ({ ...f, client_name: e.target.value }))}
              allowClear
            />
            <Select
              placeholder="接口"
              allowClear
              style={{ width: 120 }}
              onChange={(val) => setFilters(f => ({ ...f, endpoint: val }))}
              options={[
                { label: '销售', value: '/api/v1/chuku' },
                { label: '入库', value: '/api/v1/ruku' },
              ]}
            />
            <Select
              placeholder="状态"
              allowClear
              style={{ width: 120 }}
              onChange={(val) => setFilters(f => ({ ...f, status: val }))}
              options={[
                { label: '正常', value: 'success' },
                { label: '错误', value: 'error' },
              ]}
            />
            <Button icon={<SearchOutlined />} onClick={handleSearch}>搜索</Button>
            <Button icon={<DownloadOutlined />} onClick={handleExport}>导出 CSV</Button>
          </Space>
        }
      >
        <Table
          rowKey="id"
          columns={columns}
          dataSource={data}
          loading={loading}
          scroll={{ x: 1100 }}
          pagination={{
            current: filters.page as number,
            pageSize: filters.limit as number,
            total,
            showTotal: (t) => `共 ${t} 条`,
            showSizeChanger: true,
            pageSizeOptions: ['20', '50', '100', '200'],
            onChange: (page, limit) => setFilters(f => ({ ...f, page, limit })),
          }}
        />
      </Card>

      {/* 日志详情 Modal */}
      <Modal
        title="调用日志详情"
        open={detailVisible}
        onCancel={() => setDetailVisible(false)}
        footer={[
          <Button key="close" onClick={() => setDetailVisible(false)}>关闭</Button>,
        ]}
        width={700}
      >
        {currentLog && (
          <Descriptions column={1} bordered size="small">
            <Descriptions.Item label="日志ID">{currentLog.id}</Descriptions.Item>
            <Descriptions.Item label="时间">
              {currentLog.created_at ? dayjs(currentLog.created_at).format('YYYY-MM-DD HH:mm:ss') : '-'}
            </Descriptions.Item>
            <Descriptions.Item label="用户">
              {clients.find(c => c.id === currentLog.client_id)?.name || `ID:${currentLog.client_id}`}
            </Descriptions.Item>
            <Descriptions.Item label="接口">
              <Tag color={currentLog.endpoint?.includes('chuku') ? 'blue' : 'green'}>
                {currentLog.endpoint === '/api/v1/chuku' ? '销售' : currentLog.endpoint === '/api/v1/ruku' ? '入库' : currentLog.endpoint}
              </Tag>
            </Descriptions.Item>
            <Descriptions.Item label="请求参数">
              <pre style={{ margin: 0, whiteSpace: 'pre-wrap', wordBreak: 'break-all', fontSize: 12 }}>
                {currentLog.request_params ? JSON.stringify(currentLog.request_params, null, 2) : '-'}
              </pre>
            </Descriptions.Item>
            <Descriptions.Item label="响应码">
              <Tag color={currentLog.response_code === 200 ? 'green' : currentLog.response_code === 429 ? 'orange' : 'red'}>
                {currentLog.response_code}
              </Tag>
            </Descriptions.Item>
            <Descriptions.Item label="返回条数">{currentLog.record_count ?? '-'}</Descriptions.Item>
            <Descriptions.Item label="耗时">{currentLog.duration_ms ? `${currentLog.duration_ms}ms` : '-'}</Descriptions.Item>
            <Descriptions.Item label="IP地址">{currentLog.ip_address || '-'}</Descriptions.Item>
            <Descriptions.Item label="响应体">
              <pre style={{ margin: 0, whiteSpace: 'pre-wrap', wordBreak: 'break-all', fontSize: 12, maxHeight: 200, overflowY: 'auto' }}>
                {currentLog.response_body ? JSON.stringify(currentLog.response_body, null, 2) : '-'}
              </pre>
            </Descriptions.Item>
            <Descriptions.Item label="执行SQL">
              <pre style={{ margin: 0, whiteSpace: 'pre-wrap', wordBreak: 'break-all', fontSize: 12, maxHeight: 300, overflowY: 'auto', background: '#f5f5f5', padding: 8, borderRadius: 4 }}>
                {currentLog.sql_query || '-'}
              </pre>
            </Descriptions.Item>
            <Descriptions.Item label="错误信息">
              {currentLog.error_message ? (
                <span style={{ color: '#ff4d4f' }}>{currentLog.error_message}</span>
              ) : '-'}
            </Descriptions.Item>
          </Descriptions>
        )}
      </Modal>
    </AdminLayout>
  );
}
