import {
  useState,
  useEffect,
  Card,
  Table,
  Button,
  Space,
  Radio,
  Spin,
  Empty,
  Checkbox,
  Dropdown,
  SettingOutlined,
  Switch,
  Select,
  Input,
  DatePicker,
  RangePicker,
  ExportOutlined,
  ReloadOutlined,
  Modal,
  Tag,
  Text,
  Timeline,
  EyeOutlined,
  FC,
} from '@/imports';
import { OperationLogDataSource } from '@/services/operationLogDataSource';
import type { OperationLogItem, OperationLogQuery } from '@/services/operationLogDataSource';
import dayjs from 'dayjs';
import FilterPanel from './components/FilterPanel';
import DetailModal from './components/DetailModal';

const OperationLogsPage: FC = () => {
  const [data, setData] = useState<OperationLogItem[]>([]);
  const [loading, setLoading] = useState(false);
  const [pagination, setPagination] = useState({ current: 1, pageSize: 50, total: 0 });
  const [query, setQuery] = useState<OperationLogQuery>({});
  const [filters, setFilters] = useState<Partial<OperationLogQuery>>({});
  const [detailModalVisible, setDetailModalVisible] = useState(false);
  const [selectedLog, setSelectedLog] = useState<OperationLogItem | null>(null);
  const [viewMode, setViewMode] = useState<'table' | 'timeline'>('table');
  const [relatedLogs, setRelatedLogs] = useState<OperationLogItem[]>([]);
  const [visibleColumns, setVisibleColumns] = useState<string[]>([
    'created_at', 'actor', 'loop', 'stage', 'action', 'state_change', 'result', 'trace_id', 'user_id', 'actor_id', 'actor_name', 'actions'
  ]);
  const [autoRefresh, setAutoRefresh] = useState(false);
  const [refreshInterval, setRefreshInterval] = useState(30); // 30 seconds

  useEffect(() => {
    loadData();
  }, [pagination.current, query]);

  useEffect(() => {
    let intervalId: NodeJS.Timeout;
    if (autoRefresh) {
      intervalId = setInterval(() => {
        loadData();
      }, refreshInterval * 1000);
    }
    return () => {
      if (intervalId) {
        clearInterval(intervalId);
      }
    };
  }, [autoRefresh, refreshInterval]);

  useEffect(() => {
    const handleKeyDown = (e: KeyboardEvent) => {
      // Ctrl+F: Focus search input
      if (e.ctrlKey && e.key === 'f') {
        e.preventDefault();
        const searchInput = document.querySelector('input[placeholder="搜索模块、操作、操作人等"]') as HTMLInputElement;
        searchInput?.focus();
      }
      // Ctrl+R: Refresh data
      if (e.ctrlKey && e.key === 'r') {
        e.preventDefault();
        loadData();
      }
      // Ctrl+E: Export
      if (e.ctrlKey && e.key === 'e') {
        e.preventDefault();
        handleExport('csv');
      }
      // Escape: Close modal
      if (e.key === 'Escape') {
        setDetailModalVisible(false);
        setColumnSettingVisible(false);
      }
    };

    window.addEventListener('keydown', handleKeyDown);
    return () => {
      window.removeEventListener('keydown', handleKeyDown);
    };
  }, []);

  const loadData = async () => {
    setLoading(true);
    try {
      const result = await OperationLogDataSource.list({
        ...query,
        limit: pagination.pageSize,
        offset: (pagination.current - 1) * pagination.pageSize,
      });
      setData(result.logs);
      setPagination(prev => ({ ...prev, total: result.total }));
    } catch (error: unknown) {
      const errorMessage = error instanceof Error ? error.message : String(error);
      message.error(`加载失败: ${errorMessage}`);
    } finally {
      setLoading(false);
    }
  };

  const handleSearch = () => {
    setPagination(prev => ({ ...prev, current: 1 }));
    setQuery(filters);
  };

  const handleReset = () => {
    setFilters({});
    setQuery({});
    setPagination(prev => ({ ...prev, current: 1 }));
  };

  const handleExport = (format: 'csv' | 'excel' | 'pdf' = 'csv') => {
    if (format === 'pdf') {
      // 简单的PDF导出实现
      window.print();
      return;
    }

    const headers = ['ID', '时间', '闭环', '阶段', '执行者', '操作', '状态', '状态变化', '模块', '租户', '店铺', '用户ID', '执行者ID', 'TraceID', '错误信息'];
    const rows = data.map(log => [
      log.id,
      dayjs(log.created_at).format('YYYY-MM-DD HH:mm:ss'),
      log.loop_name || log.loop || '',
      log.stage_name || log.stage || '',
      log.actor_name || log.actor || '',
      log.action || '',
      log.result || '',
      log.before_state && log.after_state ? `${log.before_state} → ${log.after_state}` : log.after_state || '',
      log.module || '',
      log.tenant_id || '',
      log.shop_id || '',
      log.user_id || '',
      log.actor_id || '',
      log.trace_id || '',
      log.error_message || '',
    ]);

    const csvContent = [
      headers.join(','),
      ...rows.map(row => row.join(','))
    ].join('\n');

    const blob = new Blob(['\ufeff' + csvContent], { type: 'text/csv;charset=utf-8;' });
    const link = document.createElement('a');
    link.href = URL.createObjectURL(blob);
    link.download = `operation_logs_${dayjs().format('YYYY-MM-DD_HH-mm')}.${format === 'excel' ? 'csv' : format}`;
    link.click();
  };

  const loadRelatedLogs = async (traceId: string) => {
    try {
      const logs = await OperationLogDataSource.getByTraceId(traceId);
      setRelatedLogs(logs);
    } catch (error) {
      console.error('Failed to load related logs:', error);
    }
  };

  const showDetail = (log: OperationLogItem) => {
    setSelectedLog(log);
    loadRelatedLogs(log.trace_id);
    setDetailModalVisible(true);
  };

  const renderTimelineView = () => {
    return (
      <Timeline mode="left">
        {data.map((log) => (
          <Timeline.Item
            key={log.id}
            color={log.result === 'success' ? 'green' : 'red'}
            dot={getActorIcon(log.actor)}
            label={dayjs(log.created_at).format('YYYY-MM-DD HH:mm:ss')}
          >
            <Card size="small" style={{ width: '100%' }}>
              <Space direction="vertical" size={8} style={{ width: '100%' }}>
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                  <Text strong>{log.module} - {log.action}</Text>
                  <Tag color={getActorColor(log.actor)}>{log.actor}</Tag>
                </div>
                <div>闭环: {log.loop_name || log.loop}</div>
                <div>阶段: {log.stage_name || log.stage}</div>
                <div>状态: {getStateChange(log)}</div>
                <div>TraceID: <Text copyable>{log.trace_id}</Text></div>
                <div>操作人: {log.actor_name || '未知'}</div>
                {log.error_message && (
                  <Text type="danger">错误: {log.error_message}</Text>
                )}
                <Button 
                  type="link" 
                  size="small" 
                  icon={<EyeOutlined />} 
                  onClick={() => showDetail(log)}
                >
                  查看详情
                </Button>
              </Space>
            </Card>
          </Timeline.Item>
        ))}
      </Timeline>
    );
  };

  const getActorIcon = (actor?: string) => {
    switch (actor) {
      case 'AI': return '💡';
      case 'USER': return '👤';
      case 'SYSTEM': return '🔧';
      default: return '📝';
    }
  };

  const getActorColor = (actor?: string) => {
    switch (actor) {
      case 'AI': return 'blue';
      case 'USER': return 'purple';
      case 'SYSTEM': return 'default';
      default: return 'default';
    }
  };

  const getResultTag = (result: string) => {
    switch (result) {
      case 'success':
        return <Badge status="success" text="成功" />;
      case 'failed':
        return <Badge status="error" text="失败" />;
      default:
        return <Badge status="default" text={result} />;
    }
  };

  const getStateChange = (log: OperationLogItem) => {
    if (log.before_state && log.after_state) {
      return (
        <Space>
          <Tag color="default">{log.before_state}</Tag>
          <span>→</span>
          <Tag color={log.result === 'success' ? 'green' : 'red'}>{log.after_state}</Tag>
        </Space>
      );
    }
    return log.after_state ? <Tag color="blue">{log.after_state}</Tag> : '-';
  };

  const [columnSettingVisible, setColumnSettingVisible] = useState(false);

  const allColumns = [
    { key: 'created_at', title: '时间' },
    { key: 'actor', title: '执行者' },
    { key: 'loop', title: '闭环' },
    { key: 'stage', title: '阶段' },
    { key: 'action', title: '操作' },
    { key: 'state_change', title: '状态变化' },
    { key: 'result', title: '状态' },
    { key: 'trace_id', title: 'TraceID' },
    { key: 'user_id', title: '用户ID' },
    { key: 'actor_id', title: '执行者ID' },
    { key: 'actor_name', title: '操作人' },
    { key: 'actions', title: '操作' },
  ];

  const handleColumnToggle = (key: string, checked: boolean) => {
    if (key === 'actions') return; // 操作列始终显示
    setVisibleColumns(prev => {
      if (checked) {
        return [...prev, key];
      } else {
        return prev.filter(col => col !== key);
      }
    });
  };

  const columns = [
    {
      title: '时间',
      dataIndex: 'created_at',
      key: 'created_at',
      width: 180,
      render: (text: string) => dayjs(text).format('YYYY-MM-DD HH:mm:ss'),
    },
    {
      title: '执行者',
      key: 'actor',
      width: 100,
      render: (_: unknown, record: OperationLogItem) => (
        <Space>
          <span>{getActorIcon(record.actor)}</span>
          <Tag color={getActorColor(record.actor)}>{record.actor || 'USER'}</Tag>
        </Space>
      ),
    },
    {
      title: '闭环',
      key: 'loop',
      width: 120,
      render: (_: unknown, record: OperationLogItem) => (
        <Text strong>{record.loop_name || record.loop || '-'}</Text>
      ),
    },
    {
      title: '阶段',
      key: 'stage',
      width: 120,
      render: (_: unknown, record: OperationLogItem) => (
        <Text>{record.stage_name || record.stage || '-'}</Text>
      ),
    },
    {
      title: '操作',
      dataIndex: 'action',
      key: 'action',
      width: 100,
    },
    {
      title: '状态变化',
      key: 'state_change',
      width: 180,
      render: (_: unknown, record: OperationLogItem) => (
        <div>{getStateChange(record)}</div>
      ),
    },
    {
      title: '状态',
      dataIndex: 'result',
      key: 'result',
      width: 80,
      render: (result: string) => getResultTag(result),
    },
    {
      title: 'TraceID',
      dataIndex: 'trace_id',
      key: 'trace_id',
      width: 150,
      ellipsis: true,
      render: (trace_id: string) => (
        <a onClick={(e) => {
          e.preventDefault();
          setFilters(prev => ({ ...prev, trace_id }));
          handleSearch();
        }} style={{ color: '#1890ff', cursor: 'pointer' }}>{trace_id}</a>
      ),
    },
    {
      title: '用户ID',
      dataIndex: 'user_id',
      key: 'user_id',
      width: 120,
      ellipsis: true,
      render: (user_id: string) => (
        <a onClick={(e) => {
          e.preventDefault();
          setFilters(prev => ({ ...prev, user_id }));
          handleSearch();
        }} style={{ color: '#1890ff', cursor: 'pointer' }}>{user_id}</a>
      ),
    },
    {
      title: '执行者ID',
      dataIndex: 'actor_id',
      key: 'actor_id',
      width: 120,
      ellipsis: true,
      render: (actor_id: string) => (
        <a onClick={(e) => {
          e.preventDefault();
          setFilters(prev => ({ ...prev, actor_id }));
          handleSearch();
        }} style={{ color: '#1890ff', cursor: 'pointer' }}>{actor_id || '-'}</a>
      ),
    },
    {
      title: '操作人',
      dataIndex: 'actor_name',
      key: 'actor_name',
      width: 120,
      ellipsis: true,
    },
    {
      title: '操作',
      key: 'actions',
      width: 80,
      fixed: 'right' as const,
      render: (_: unknown, record: OperationLogItem) => (
        <Button type="link" size="small" icon={<EyeOutlined />} onClick={() => showDetail(record)}>
          详情
        </Button>
      ),
    },
  ].filter(col => visibleColumns.includes(col.key));

  const handleResetColumns = () => {
    setVisibleColumns([
      'created_at', 'actor', 'loop', 'stage', 'action', 'state_change', 'result', 'trace_id', 'user_id', 'actor_id', 'actor_name', 'actions'
    ]);
  };

  return (
    <div style={{ padding: 24 }}>
      <Card
        title="📋 操作日志中心"
        extra={
          <Space>
            <Radio.Group value={viewMode} onChange={(e) => setViewMode(e.target.value as 'table' | 'timeline')}>
              <Radio.Button value="table">表格视图</Radio.Button>
              <Radio.Button value="timeline">时间轴视图</Radio.Button>
            </Radio.Group>
            <Space>
              <Switch
                checked={autoRefresh}
                onChange={setAutoRefresh}
                checkedChildren="自动刷新"
                unCheckedChildren="自动刷新"
              />
              {autoRefresh && (
                <Select
                  value={refreshInterval}
                  onChange={setRefreshInterval}
                  style={{ width: 80 }}
                  options={[
                    { value: 10, label: '10s' },
                    { value: 30, label: '30s' },
                    { value: 60, label: '1min' },
                    { value: 300, label: '5min' },
                  ]}
                />
              )}
            </Space>
            <Button icon={<SettingOutlined />} onClick={() => setColumnSettingVisible(true)}>列设置</Button>
            <Dropdown
              menu={{
                items: [
                  {
                    key: 'csv',
                    label: '导出CSV',
                    onClick: () => handleExport('csv'),
                  },
                  {
                    key: 'excel',
                    label: '导出Excel',
                    onClick: () => handleExport('excel'),
                  },
                  {
                    key: 'pdf',
                    label: '导出PDF',
                    onClick: () => handleExport('pdf'),
                  },
                ],
              }}
            >
              <Button icon={<ExportOutlined />}>导出</Button>
            </Dropdown>
            <Button icon={<ReloadOutlined />} onClick={loadData}>刷新</Button>
          </Space>
        }
      >
        <FilterPanel
          filters={filters}
          onFilterChange={setFilters}
          onSearch={handleSearch}
          onReset={handleReset}
        />

        {viewMode === 'table' ? (
          <Table
            columns={columns}
            dataSource={data}
            rowKey="id"
            loading={loading}
            scroll={{ x: 1200, y: 600 }}
            pagination={{
              ...pagination,
              showSizeChanger: true,
              showQuickJumper: true,
              showTotal: (total) => `共 ${total} 条`,
              onChange: (page, pageSize) => {
                setPagination({ ...pagination, current: page, pageSize });
              },
            }}
            virtual
          />
        ) : (
          <div style={{ padding: 16 }}>
            {loading ? (
              <div style={{ display: 'flex', justifyContent: 'center', padding: 40 }}>
                <Spin size="large" />
              </div>
            ) : data.length > 0 ? (
              renderTimelineView()
            ) : (
              <Empty description="暂无操作日志" />
            )}
          </div>
        )}
      </Card>

      <DetailModal
        visible={detailModalVisible}
        log={selectedLog}
        relatedLogs={relatedLogs}
        onClose={() => setDetailModalVisible(false)}
        getActorIcon={getActorIcon}
        getActorColor={getActorColor}
        getStateChange={getStateChange}
      />

      <Modal
        title="列设置"
        open={columnSettingVisible}
        onCancel={() => setColumnSettingVisible(false)}
        footer={[
          <Button key="reset" onClick={handleResetColumns}>重置默认</Button>,
          <Button key="ok" type="primary" onClick={() => setColumnSettingVisible(false)}>确定</Button>
        ]}
        width={400}
      >
        <div style={{ maxHeight: 300, overflow: 'auto' }}>
          {allColumns.map(column => (
            <div key={column.key} style={{ marginBottom: 8, display: 'flex', alignItems: 'center' }}>
              <Checkbox
                checked={visibleColumns.includes(column.key)}
                onChange={(e) => handleColumnToggle(column.key, e.target.checked)}
                disabled={column.key === 'actions'}
              />
              <span style={{ marginLeft: 8 }}>{column.title}</span>
            </div>
          ))}
        </div>
      </Modal>
    </div>
  );
};

export default OperationLogsPage;