import React, { useState } from 'react';
import { 
Button, Table, Space,
  Form, Input, Select, message, Modal,
  Card, Row, Col, Typography, Badge
} from 'antd';
import { 
  useQuery
} from '@tanstack/react-query';
import dayjs from 'dayjs';
import 'dayjs/locale/zh-cn';
import type { 
  ZichanInfo, RackInfo, RackServer
} from '../share/monitorTypes.ts';

import {
  ServerType, ServerTypeNameMap
} from '../share/monitorTypes.ts';

import { EnableStatus } from '../share/types.ts'

import { RackAPI, RackServerAPI , ZichanAPI} from './api/index.ts';

const { Title } = Typography;

// 机柜服务器管理页面
export const RackServerPage = () => {
  const [form] = Form.useForm();
  const [formMode, setFormMode] = useState<'create' | 'edit'>('create');
  const [editingId, setEditingId] = useState<number | null>(null);
  const [modalVisible, setModalVisible] = useState(false);
  const [isLoading, setIsLoading] = useState(false);
  const [searchParams, setSearchParams] = useState({
    page: 1,
    limit: 10,
    rack_id: undefined as number | undefined,
    server_type: undefined as string | undefined
  });
  
  // 获取机柜列表用于下拉选择
  const { data: rackOptions = [] } = useQuery({
    queryKey: ['rackOptions'],
    queryFn: async () => {
      try {
        const response = await RackAPI.getRackList({ limit: 100 });
        return response.data.map((rack: RackInfo) => ({
          label: `${rack.rack_name || ''} (${rack.rack_code || ''})`,
          value: rack.id
        }));
      } catch (error) {
        console.error('获取机柜列表失败:', error);
        return [];
      }
    }
  });
  
  // 获取资产列表用于下拉选择
  const { data: assetOptions = [] } = useQuery({
    queryKey: ['assetOptions'],
    queryFn: async () => {
      try {
        const response = await ZichanAPI.getZichanList({ limit: 100 });
        return response.data.map((asset: ZichanInfo) => ({
          label: `${asset.asset_name || ''} (ID:${asset.id})`,
          value: asset.id
        }));
      } catch (error) {
        console.error('获取资产列表失败:', error);
        return [];
      }
    }
  });
  
  // 服务器类型选项
  const serverTypeOptions = [
    { label: ServerTypeNameMap[ServerType.STANDARD], value: ServerType.STANDARD },
    { label: ServerTypeNameMap[ServerType.NETWORK], value: ServerType.NETWORK },
    { label: ServerTypeNameMap[ServerType.STORAGE], value: ServerType.STORAGE },
    { label: ServerTypeNameMap[ServerType.SPECIAL], value: ServerType.SPECIAL }
  ];
  
  // 查询机柜服务器列表
  const { 
    data: rackServerResult = { data: [], pagination: { total: 0, current: 1, pageSize: 10 } }, 
    isLoading: isFetching,
    refetch
  } = useQuery({
    queryKey: ['rackServers', searchParams],
    queryFn: () => RackServerAPI.getRackServerList(searchParams),
  });
  
  // 提取数据和分页信息
  const rackServerList = rackServerResult.data || [];
  const pagination = rackServerResult.pagination || { total: 0, current: 1, pageSize: 10 };
  
  // 处理表单提交
  const handleSubmit = async (values: Partial<RackServer>) => {
    try {
      setIsLoading(true);
      if (formMode === 'create') {
        await RackServerAPI.createRackServer(values);
        message.success('机柜服务器创建成功');
      } else {
        if (editingId) {
          await RackServerAPI.updateRackServer(editingId, values);
          message.success('机柜服务器更新成功');
        }
      }
      setModalVisible(false);
      refetch();
    } catch (error: any) {
      message.error(error.response?.data?.error || '操作失败');
    } finally {
      setIsLoading(false);
    }
  };
  
  // 处理编辑
  const handleEdit = async (id: number) => {
    try {
      setIsLoading(true);
      const data = await RackServerAPI.getRackServer(id);
      form.setFieldsValue(data);
      setEditingId(id);
      setFormMode('edit');
      setModalVisible(true);
    } catch (error: any) {
      message.error(error.response?.data?.error || '获取机柜服务器详情失败');
    } finally {
      setIsLoading(false);
    }
  };
  
  // 处理删除
  const handleDelete = async (id: number) => {
    try {
      await RackServerAPI.deleteRackServer(id);
      message.success('机柜服务器删除成功');
      refetch();
    } catch (error: any) {
      message.error(error.response?.data?.error || '删除机柜服务器失败');
    }
  };
  
  // 处理搜索
  const handleSearch = (values: any) => {
    setSearchParams({
      ...searchParams,
      page: 1, // 重置为第一页
      rack_id: values.rack_id,
      server_type: values.server_type
    });
  };
  
  // 处理页码变化
  const handlePageChange = (page: number, pageSize?: number) => {
    setSearchParams({
      ...searchParams,
      page,
      limit: pageSize || 10
    });
  };
  
  // 处理新增
  const handleAdd = () => {
    form.resetFields();
    setFormMode('create');
    setEditingId(null);
    setModalVisible(true);
  };
  
  // 表格列定义
  const columns = [
    { 
      title: 'ID', 
      dataIndex: 'id', 
      key: 'id',
      width: 60
    },
    { 
      title: '机柜', 
      dataIndex: 'rack_id', 
      key: 'rack_id',
      render: (rackId: number) => {
        const rack = rackOptions.find((r: any) => r.value === rackId);
        return rack ? rack.label : `ID:${rackId}`;
      }
    },
    { 
      title: '资产', 
      dataIndex: 'asset_id', 
      key: 'asset_id',
      render: (assetId: number) => {
        const asset = assetOptions.find((a: any) => a.value === assetId);
        return asset ? asset.label : `ID:${assetId}`;
      }
    },
    { 
      title: '起始U位', 
      dataIndex: 'start_position', 
      key: 'start_position' 
    },
    { 
      title: '占用U数', 
      dataIndex: 'size', 
      key: 'size' 
    },
    { 
      title: '服务器类型', 
      dataIndex: 'server_type', 
      key: 'server_type',
      render: (type: ServerType) => ServerTypeNameMap[type] || '未知类型'
    },
    { 
      title: '状态', 
      dataIndex: 'is_disabled', 
      key: 'is_disabled',
      render: (status: EnableStatus) => (
        <Badge 
          status={status === EnableStatus.ENABLED ? 'success' : 'error'} 
          text={status === EnableStatus.ENABLED ? '正常' : '禁用'}
        />
      )
    },
    { 
      title: '创建时间', 
      dataIndex: 'created_at', 
      key: 'created_at',
      render: (date: string) => date ? dayjs(date).format('YYYY-MM-DD HH:mm:ss') : '-'
    },
    {
      title: '操作',
      key: 'action',
      width: 200,
      render: (_: any, record: RackServer) => (
        <Space>
          <Button size="small" type="primary" onClick={() => handleEdit(record.id)}>编辑</Button>
          <Button size="small" danger onClick={() => 
            Modal.confirm({
              title: '确认删除',
              content: '确定要删除此机柜服务器记录吗？',
              onOk: () => handleDelete(record.id)
            })
          }>删除</Button>
        </Space>
      )
    }
  ];
  
  return (
    <div>
      <Title level={2}>机柜服务器管理</Title>
      <Card>
        <Form layout="inline" onFinish={handleSearch} style={{ marginBottom: 16 }}>
          <Form.Item name="rack_id" label="机柜">
            <Select
              placeholder="请选择机柜"
              style={{ width: 200 }}
              allowClear
              options={rackOptions}
              showSearch
              filterOption={(input, option) =>
                (String(option?.label ?? '')).toLowerCase().includes(input.toLowerCase())
              }
            />
          </Form.Item>
          <Form.Item name="server_type" label="服务器类型">
            <Select
              placeholder="请选择服务器类型"
              style={{ width: 160 }}
              allowClear
              options={serverTypeOptions}
            />
          </Form.Item>
          <Form.Item>
            <Button type="primary" htmlType="submit">查询</Button>
          </Form.Item>
          <Form.Item>
            <Button type="primary" onClick={handleAdd}>添加服务器</Button>
          </Form.Item>
        </Form>
        
        <Table
          columns={columns}
          dataSource={rackServerList}
          rowKey="id"
          loading={isFetching}
          pagination={{
            current: pagination.current,
            pageSize: pagination.pageSize,
            total: pagination.total,
            onChange: handlePageChange,
            showSizeChanger: true,
            showTotal: (total) => `共 ${total} 条记录`
          }}
        />
        
        <Modal
          title={formMode === 'create' ? '添加机柜服务器' : '编辑机柜服务器'}
          open={modalVisible}
          onCancel={() => setModalVisible(false)}
          footer={null}
          width={700}
        >
          <Form
            form={form}
            layout="vertical"
            onFinish={handleSubmit}
          >
            <Row gutter={16}>
              <Col span={12}>
                <Form.Item
                  name="rack_id"
                  label="选择机柜"
                  rules={[{ required: true, message: '请选择机柜' }]}
                >
                  <Select
                    placeholder="请选择机柜"
                    options={rackOptions}
                    showSearch
                    filterOption={(input, option) =>
                      (String(option?.label ?? '')).toLowerCase().includes(input.toLowerCase())
                    }
                  />
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item
                  name="asset_id"
                  label="选择资产"
                  rules={[{ required: true, message: '请选择资产' }]}
                >
                  <Select
                    placeholder="请选择资产"
                    options={assetOptions}
                    showSearch
                    filterOption={(input, option) =>
                      (String(option?.label ?? '')).toLowerCase().includes(input.toLowerCase())
                    }
                  />
                </Form.Item>
              </Col>
            </Row>
            
            <Row gutter={16}>
              <Col span={12}>
                <Form.Item
                  name="start_position"
                  label="起始U位"
                  rules={[{ required: true, message: '请输入起始U位' }]}
                >
                  <Input type="number" placeholder="请输入起始U位" />
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item
                  name="size"
                  label="占用U数"
                  initialValue={1}
                  rules={[{ required: true, message: '请输入占用U数' }]}
                >
                  <Input type="number" placeholder="请输入占用U数" />
                </Form.Item>
              </Col>
            </Row>
            
            <Row gutter={16}>
              <Col span={12}>
                <Form.Item
                  name="server_type"
                  label="服务器类型"
                  initialValue={ServerType.STANDARD}
                >
                  <Select
                    placeholder="请选择服务器类型"
                    options={serverTypeOptions}
                  />
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item
                  name="is_disabled"
                  label="状态"
                  initialValue={EnableStatus.ENABLED}
                >
                  <Select>
                    <Select.Option value={EnableStatus.ENABLED}>正常</Select.Option>
                    <Select.Option value={EnableStatus.DISABLED}>禁用</Select.Option>
                  </Select>
                </Form.Item>
              </Col>
            </Row>
            
            <Form.Item
              name="remark"
              label="备注信息"
            >
              <Input.TextArea rows={3} placeholder="请输入备注信息" />
            </Form.Item>
            
            <Form.Item>
              <Space>
                <Button type="primary" htmlType="submit" loading={isLoading}>
                  {formMode === 'create' ? '创建' : '保存'}
                </Button>
                <Button onClick={() => setModalVisible(false)}>取消</Button>
              </Space>
            </Form.Item>
          </Form>
        </Modal>
      </Card>
    </div>
  );
};