import {
  useState,
  useEffect,
  Card,
  Table,
  Button,
  Space,
  Switch,
  Tag,
  message,
  Row,
  Col,
  Statistic,
  Badge,
  Typography,
  Divider,
  Alert,
  Spin,
  Tabs,
  Modal,
  Progress,
  ReloadOutlined,
  CheckCircleOutlined,
  CloseCircleOutlined,
  ThunderboltOutlined,
  DashboardOutlined,
  WarningOutlined,
  Title,
  Text,
  FC,
} from '@/imports';
import type { TabsProps } from 'antd';
import type { ColumnsType } from 'antd/es/table';
import { serviceManagerDataSource, ServiceInfo, ServiceStats, ServicePreset } from '@/services/serviceManagerDataSource';

const MEMORY_IMPACT_COLORS: Record<string, string> = {
  low: 'green',
  medium: 'orange',
  high: 'red',
};

const MEMORY_IMPACT_TEXT: Record<string, string> = {
  low: '低',
  medium: '中',
  high: '高',
};

const ServiceManager: FC = () => {
  const [services, setServices] = useState<ServiceInfo[]>([]);
  const [groupedServices, setGroupedServices] = useState<Record<string, ServiceInfo[]>>({});
  const [stats, setStats] = useState<ServiceStats | null>(null);
  const [presets, setPresets] = useState<ServicePreset[]>([]);
  const [categories, setCategories] = useState<Record<string, { label: string; color: string }>>({});
  const [loading, setLoading] = useState(true);
  const [presetModalVisible, setPresetModalVisible] = useState(false);
  const [selectedCategory, setSelectedCategory] = useState<string>('all');

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

  const loadData = async () => {
    setLoading(true);
    try {
      const [listData, presetsData, categoriesData] = await Promise.all([
        serviceManagerDataSource.list(),
        serviceManagerDataSource.getPresets(),
        serviceManagerDataSource.getCategories(),
      ]);
      setServices(listData.services);
      setGroupedServices(listData.groupedServices);
      setStats(listData.stats);
      setPresets(presetsData);
      setCategories(categoriesData);
    } catch (error: unknown) {
      const errorMessage = error instanceof Error ? error.message : String(error);
      message.error(`加载失败: ${errorMessage}`);
    } finally {
      setLoading(false);
    }
  };

  const handleToggle = async (name: string, enabled: boolean) => {
    try {
      const result = await serviceManagerDataSource.toggle(name, enabled);
      message.success(result.message);
      loadData();
    } catch (error: unknown) {
      const errorMessage = error instanceof Error ? error.message : String(error);
      message.error(`操作失败: ${errorMessage}`);
    }
  };

  const handleApplyPreset = async (preset: string) => {
    try {
      const result = await serviceManagerDataSource.applyPreset(preset);
      message.success(result.message);
      setPresetModalVisible(false);
      loadData();
    } catch (error: unknown) {
      const errorMessage = error instanceof Error ? error.message : String(error);
      message.error(`应用预设失败: ${errorMessage}`);
    }
  };

  const handleBatchToggle = async (category: string, enabled: boolean) => {
    const categoryServices = groupedServices[category] || [];
    const serviceNames = categoryServices.map(s => s.name);
    
    Modal.confirm({
      title: `确认${enabled ? '启用' : '禁用'}所有 ${categories[category]?.label || category} 服务？`,
      content: `将影响 ${serviceNames.length} 个服务`,
      onOk: async () => {
        try {
          const result = await serviceManagerDataSource.batchToggle(serviceNames, enabled);
          message.success(result.message);
          loadData();
        } catch (error: unknown) {
          const errorMessage = error instanceof Error ? error.message : String(error);
          message.error(`批量操作失败: ${errorMessage}`);
        }
      },
    });
  };

  const columns: ColumnsType<ServiceInfo> = [
    {
      title: '服务名称',
      dataIndex: 'name',
      key: 'name',
      width: 200,
      render: (name: string) => <Text strong>{name}</Text>,
    },
    {
      title: '描述',
      dataIndex: ['config', 'description'],
      key: 'description',
      width: 250,
    },
    {
      title: '分类',
      dataIndex: ['config', 'category'],
      key: 'category',
      width: 120,
      render: (category: string) => {
        const config = categories[category] || { color: 'default', label: category };
        return <Tag color={config.color}>{config.label}</Tag>;
      },
    },
    {
      title: '内存影响',
      dataIndex: ['config', 'memoryImpact'],
      key: 'memoryImpact',
      width: 100,
      render: (impact: string) => (
        <Tag color={MEMORY_IMPACT_COLORS[impact]}>
          {MEMORY_IMPACT_TEXT[impact]}
        </Tag>
      ),
    },
    {
      title: '状态',
      dataIndex: 'initialized',
      key: 'status',
      width: 100,
      render: (initialized: boolean, record: ServiceInfo) => {
        if (record.error) {
          return <Badge status="error" text="错误" />;
        }
        if (!record.enabled) {
          return <Badge status="default" text="已禁用" />;
        }
        if (initialized) {
          return <Badge status="success" text="已启动" />;
        }
        return <Badge status="processing" text="启动中" />;
      },
    },
    {
      title: '开关',
      key: 'toggle',
      width: 80,
      render: (_, record: ServiceInfo) => (
        <Switch
          checked={record.enabled}
          onChange={(checked) => handleToggle(record.name, checked)}
          checkedChildren="开"
          unCheckedChildren="关"
        />
      ),
    },
  ];

  const filteredServices = selectedCategory === 'all' 
    ? services 
    : groupedServices[selectedCategory] || [];

  const tabItems: TabsProps['items'] = [
    {
      key: 'all',
      label: `全部 (${services.length})`,
    },
    ...Object.entries(groupedServices).map(([category, categoryServices]) => ({
      key: category,
      label: `${categories[category]?.label || category} (${categoryServices.length})`,
    })),
  ];

  return (
    <div>
      <Title level={4}>服务管理</Title>
      <Text type="secondary">管理系统后台服务，控制内存占用</Text>
      
      <Divider />
      
      {stats && (
        <Row gutter={16} style={{ marginBottom: 24 }}>
          <Col span={4}>
            <Card>
              <Statistic 
                title="总服务数" 
                value={stats.total} 
                prefix={<DashboardOutlined />}
              />
            </Card>
          </Col>
          <Col span={4}>
            <Card>
              <Statistic 
                title="已启用" 
                value={stats.enabled} 
                valueStyle={{ color: '#3f8600' }}
                prefix={<CheckCircleOutlined />}
              />
            </Card>
          </Col>
          <Col span={4}>
            <Card>
              <Statistic 
                title="已禁用" 
                value={stats.disabled} 
                valueStyle={{ color: '#999' }}
                prefix={<CloseCircleOutlined />}
              />
            </Card>
          </Col>
          <Col span={4}>
            <Card>
              <Statistic 
                title="已启动" 
                value={stats.initialized} 
                valueStyle={{ color: '#1890ff' }}
                prefix={<ThunderboltOutlined />}
              />
            </Card>
          </Col>
          <Col span={4}>
            <Card>
              <Statistic 
                title="启动失败" 
                value={stats.failed} 
                valueStyle={{ color: stats.failed > 0 ? '#cf1322' : '#999' }}
                prefix={<WarningOutlined />}
              />
            </Card>
          </Col>
          <Col span={4}>
            <Card>
              <Statistic 
                title="内存影响(高)" 
                value={stats.byMemoryImpact?.high?.enabled || 0}
                suffix={`/ ${stats.byMemoryImpact?.high?.total || 0}`}
                valueStyle={{ color: (stats.byMemoryImpact?.high?.enabled || 0) > 0 ? '#cf1322' : '#999' }}
              />
            </Card>
          </Col>
        </Row>
      )}

      <Alert
        message="提示：修改服务配置后需要重启服务器才能生效"
        type="info"
        showIcon
        style={{ marginBottom: 16 }}
      />

      <Card>
        <div style={{ marginBottom: 16 }}>
          <Space>
            <Button 
              type="primary" 
              icon={<ThunderboltOutlined />}
              onClick={() => setPresetModalVisible(true)}
            >
              应用预设
            </Button>
            <Button 
              icon={<ReloadOutlined />}
              onClick={loadData}
            >
              刷新
            </Button>
          </Space>
        </div>

        <Spin spinning={loading}>
          <Tabs 
            activeKey={selectedCategory} 
            onChange={setSelectedCategory}
            items={tabItems}
          />

          <Table 
            columns={columns} 
            dataSource={filteredServices} 
            rowKey="name"
            pagination={{ pageSize: 20 }}
            size="small"
          />
        </Spin>
      </Card>

      <Modal
        title="选择预设配置"
        open={presetModalVisible}
        onCancel={() => setPresetModalVisible(false)}
        footer={null}
        width={600}
      >
        <Row gutter={[16, 16]}>
          {presets.map(preset => (
            <Col span={12} key={preset.id}>
              <Card
                hoverable
                onClick={() => handleApplyPreset(preset.id)}
                style={{ cursor: 'pointer' }}
              >
                <Title level={5}>{preset.name}</Title>
                <Text type="secondary">{preset.description}</Text>
                <Divider style={{ margin: '12px 0' }} />
                <Progress 
                  percent={Math.round((preset.serviceCount / (stats?.total || 100)) * 100)} 
                  format={() => `${preset.serviceCount} 个服务`}
                  strokeColor={preset.id === 'minimal' ? '#52c41a' : preset.id === 'full' ? '#f5222d' : '#1890ff'}
                />
              </Card>
            </Col>
          ))}
        </Row>
      </Modal>
    </div>
  );
};

export default ServiceManager;
