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

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

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

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

const { Title } = Typography;
// 机柜管理页面
export const RackManagePage = () => {
  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_name: '',
    rack_code: '',
    area: ''
  });
  
  // 查询机柜列表
  const { 
    data: rackResult = { data: [], pagination: { total: 0, current: 1, pageSize: 10 } }, 
    isLoading: isFetching,
    refetch
  } = useQuery({
    queryKey: ['racks', searchParams],
    queryFn: () => RackAPI.getRackList(searchParams),
  });
  
  // 提取数据和分页信息
  const rackList = rackResult.data || [];
  const pagination = rackResult.pagination || { total: 0, current: 1, pageSize: 10 };
  
  // 处理表单提交
  const handleSubmit = async (values: Partial<RackInfo>) => {
    try {
      setIsLoading(true);
      if (formMode === 'create') {
        await RackAPI.createRack(values);
        message.success('机柜创建成功');
      } else {
        if (editingId) {
          await RackAPI.updateRack(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 RackAPI.getRack(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 RackAPI.deleteRack(id);
      message.success('机柜删除成功');
      refetch();
    } catch (error: any) {
      message.error(error.response?.data?.error || '删除机柜失败');
    }
  };
  
  // 处理搜索
  const handleSearch = (values: any) => {
    setSearchParams({
      ...searchParams,
      page: 1, // 重置为第一页
      rack_name: values.rack_name,
      rack_code: values.rack_code,
      area: values.area
    });
  };
  
  // 处理页码变化
  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: 80
    },
    { 
      title: '机柜名称', 
      dataIndex: 'rack_name', 
      key: 'rack_name' 
    },
    { 
      title: '机柜编号', 
      dataIndex: 'rack_code', 
      key: 'rack_code' 
    },
    { 
      title: '区域', 
      dataIndex: 'area', 
      key: 'area' 
    },
    { 
      title: '机房', 
      dataIndex: 'room', 
      key: 'room' 
    },
    { 
      title: '容量(U)', 
      dataIndex: 'capacity', 
      key: 'capacity' 
    },
    { 
      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: RackInfo) => (
        <Space>
          <Button size="small" type="primary" onClick={() => handleEdit(record.id)}>编辑</Button>
          <Button size="small" danger onClick={() => 
            Modal.confirm({
              title: '确认删除',
              content: `确定要删除机柜"${record.rack_name}"吗？`,
              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_name" label="机柜名称">
            <Input placeholder="请输入机柜名称" allowClear />
          </Form.Item>
          <Form.Item name="rack_code" label="机柜编号">
            <Input placeholder="请输入机柜编号" allowClear />
          </Form.Item>
          <Form.Item name="area" label="区域">
            <Input placeholder="请输入区域" allowClear />
          </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={rackList}
          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_name"
                  label="机柜名称"
                  rules={[{ required: true, message: '请输入机柜名称' }]}
                >
                  <Input placeholder="请输入机柜名称" />
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item
                  name="rack_code"
                  label="机柜编号"
                  rules={[{ required: true, message: '请输入机柜编号' }]}
                >
                  <Input placeholder="请输入机柜编号" />
                </Form.Item>
              </Col>
            </Row>
            
            <Row gutter={16}>
              <Col span={12}>
                <Form.Item
                  name="area"
                  label="区域"
                >
                  <Input placeholder="请输入区域" />
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item
                  name="room"
                  label="机房"
                >
                  <Input placeholder="请输入机房" />
                </Form.Item>
              </Col>
            </Row>
            
            <Row gutter={16}>
              <Col span={12}>
                <Form.Item
                  name="capacity"
                  label="容量(U)"
                  initialValue={42}
                  rules={[{ required: true, message: '请输入容量' }]}
                >
                  <Input type="number" placeholder="请输入容量" />
                </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>
            
            <Row gutter={16}>
              <Col span={8}>
                <Form.Item
                  name="position_x"
                  label="X轴位置"
                >
                  <Input type="number" placeholder="请输入X轴位置" />
                </Form.Item>
              </Col>
              <Col span={8}>
                <Form.Item
                  name="position_y"
                  label="Y轴位置"
                >
                  <Input type="number" placeholder="请输入Y轴位置" />
                </Form.Item>
              </Col>
              <Col span={8}>
                <Form.Item
                  name="position_z"
                  label="Z轴位置"
                >
                  <Input type="number" placeholder="请输入Z轴位置" />
                </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>
  );
};