import React, { useEffect, useState, useMemo } from 'react';
import {
  Modal,
  Form,
  Select,
  Grid,
  Slider,
  Switch,
  Input,
  InputNumber,
  Message,
  Button,
  Spin
} from '@arco-design/web-react';
import EditableTable from '@/components/EditableTable';
import { containerRegister, getContainerConfig, getContainerLimit } from '@/api/userContainer';
import { getNetworkMode } from '@/api/componentDeploy';

const FormItem = Form.Item;
const Option = Select.Option;

const netType = [
  {
    label: '桥接模式',
    value: 'bridge'
  },
  {
    label: '主机模式',
    value: 'host'
  },
  {
    label: '禁用网络',
    value: 'null'
  }
];
const portColumns = [
  {
    title: '主机端口',
    dataIndex: 'hostPort',
    editable: true,
    renderEdit: ({ value, onChange }) => (
      <InputNumber
        value={value}
        onChange={onChange}
        min={1}
        max={65535}
        precision={0}
        placeholder="请输入端口号"
        style={{ width: '100%' }}
      />
    )
  },
  {
    title: '容器端口',
    dataIndex: 'containerPort',
    editable: true,
    renderEdit: ({ value, onChange }) => (
      <InputNumber
        value={value}
        onChange={onChange}
        min={1}
        max={65535}
        precision={0}
        placeholder="请输入端口号"
        style={{ width: '100%' }}
      />
    )
  },
  {
    title: '备注',
    dataIndex: 'remake',
    editable: true
  }
];
const directoryColumns = [
  {
    title: '主机路径',
    dataIndex: 'hostPath',
    editable: true
  },
  {
    title: '容器路径',
    dataIndex: 'containerPath',
    editable: true
  },
  {
    title: '备注',
    dataIndex: 'remake',
    editable: true
  }
];
const deviceColumns = [
  {
    title: '主机路径',
    dataIndex: 'hostPath',
    editable: true
  },
  {
    title: '容器路径',
    dataIndex: 'containerPath',
    editable: true
  },
  {
    title: '权限',
    dataIndex: 'permissions',
    editable: true,
    renderEdit: ({ value, onChange }) => (
      <Select
        value={value}
        onChange={onChange}
        placeholder="请选择权限"
        style={{ width: '100%' }}
      >
        <Option value="rwm">rwm (读写+mknod)</Option>
        <Option value="rw">rw (读写)</Option>
        <Option value="r">r (只读)</Option>
      </Select>
    )
  },
  {
    title: '备注',
    dataIndex: 'remake',
    editable: true
  }
];

const ContainerModal = ({ addItem, visible, envType, setVisible, onSuccess }) => {
  const [form] = Form.useForm();
  const [envTypeOptions, setEnvTypeOptions] = useState([]);
  const [portMappingData, setPortMappingData] = useState([]); // 端口映射数据
  const [directoryMountData, setDirectoryMountData] = useState([]); // 目录挂载数据
  const [deviceMountData, setDeviceMountData] = useState([]); // 设备挂载数据
  const [networkTypeList, setNetworkTypeList] = useState([]); // 网卡数据列表
  const [selectedNetworkType, setSelectedNetworkType] = useState([]); // 选择的网卡数据
  const [loading, setLoading] = useState(false);

  const [currentNetworkCard, setCurrentNetworkCard] = useState(''); // 当前选择的网卡
  const [currentIp, setCurrentIp] = useState(''); // 当前输入的IP
  const [containerConfig, setContainerConfig] = useState<{
    maxCpuCores: number,
    maxMemoryMiB: number
  }>({ maxCpuCores: 4, maxMemoryMiB: 4096 }); // 容器配置数据
  const [configLoaded, setConfigLoaded] = useState(false); // 容器配置是否已加载
  const [configLoading, setConfigLoading] = useState(false); // 容器配置加载中

  // 处理取消
  const handleCancel = () => {
    form.resetFields();
    setPortMappingData([]);
    setDirectoryMountData([]);
    setDeviceMountData([]);
    setNetworkTypeList([]);
    setSelectedNetworkType([]);
    setCurrentNetworkCard('');
    setCurrentIp('');
    setConfigLoaded(false);
    setConfigLoading(false);
    setVisible(false);
  };

  const fetchNetworkMode = async (type: string, deployEnvId: string) => {
    // 切换网络模式时清除网卡和IP数据
    form.setFieldValue('networkType', undefined);
    form.setFieldValue('ip', '');
    setCurrentNetworkCard('');
    setCurrentIp('');
    setSelectedNetworkType([]);
    setNetworkTypeList([]);

    const res: any = await getNetworkMode(type, deployEnvId);
    if (res.code === 200) {
      setNetworkTypeList(res.data);
    }
  };

  // 处理确认
  const handleOk = async () => {
    try {
      setLoading(true);
      const values = await form.validate();

      // 组装提交数据
      const submitData = {
        ...values,
        deployEnvId: addItem.id,
        environment: addItem.type,
        ports: portMappingData, // 端口映射
        volumes: directoryMountData, // 目录挂载
        devices: deviceMountData, // 设备挂载
        // 下面是暂时写死的数据,
        'restartPolicy': 'always'
      };

      const res: any = await containerRegister(submitData);
      if (res.code === 200) {
        Message.success('容器配置成功');
        handleCancel();
        onSuccess?.();
      }
      else {
        Message.error('容器配置失败: ' + res.message);
      }

    } catch (error) {
      console.error('表单校验失败：', error);
      Message.error('请检查表单必填项');
    } finally {
      setLoading(false);
    }
  };

  const getLimit = async () => {
    setConfigLoading(true);
    try {
      const res: any = await getContainerLimit(addItem.id);
      if (res.code === 200) {
        setContainerConfig(res.data);
        setConfigLoaded(true);
        // 设置表单默认值
        form.setFieldsValue({
          cpuCount: 1,
          memory: 2048,
          useGpu: false
        });
      }
    } finally {
      setConfigLoading(false);
    }
  };

  const getConfig = async () => {
    const res: any = await getContainerConfig(addItem.id);
    if (res.code === 200 && res.data) {
      const data = res.data;

      // 回显表单数据
      form.setFieldsValue({
        cpuCount: data.cpuCount || 1,
        memory: data.memory || 2048,
        useGpu: data.deviceRequests?.length > 0,
        networkMode: data.networkMode,
        networkType: data.networkType,
        ip: data.ipv4Address
      });

      // 回显网卡相关数据
      if (data.networkMode) {
        const networkRes: any = await getNetworkMode(data.networkMode, addItem.id);
        if (networkRes.code === 200) {
          setNetworkTypeList(networkRes.data);
          if (data.networkType) {
            setCurrentNetworkCard(data.networkType);
            const selectedCard = networkRes.data.find(item => item.name === data.networkType);
            setSelectedNetworkType(selectedCard ? [selectedCard] : []);
          }
        }
      }
      setCurrentIp(data.ipv4Address || '');

      // 回显端口映射数据
      if (data.ports?.length > 0) {
        setPortMappingData(data.ports.map((port, index) => ({
          key: index.toString(),
          hostPort: port.hostPort,
          containerPort: port.containerPort,
          remake: port.remake || ''
        })));
      }

      // 回显目录挂载数据
      if (data.volumes?.length > 0) {
        setDirectoryMountData(data.volumes.map((vol, index) => ({
          key: index.toString(),
          hostPath: vol.hostPath,
          containerPath: vol.containerPath,
          remake: vol.remake || ''
        })));
      }

      // 回显设备挂载数据
      if (data.devices?.length > 0) {
        setDeviceMountData(data.devices.map((device, index) => ({
          key: index.toString(),
          hostPath: device.hostPath,
          containerPath: device.containerPath,
          permissions: device.permissions,
          remake: device.remake || ''
        })));
      }

      // 如果有配置数据，标记为已加载配置
      if (data.cpuCount || data.memory) {
        // 获取限制配置以设置滑块范围
        const limitRes: any = await getContainerLimit(addItem.id);
        if (limitRes.code === 200) {
          setContainerConfig(limitRes.data);
        }
        setConfigLoaded(true);
      }
    }
  };

  // 动态生成CPU核数的marks
  const cpuMarks = useMemo(() => {
    const max = containerConfig.maxCpuCores;
    const marks: Record<number, string> = {};
    marks[1] = '1核';
    if (max > 1) marks[max] = `${max}核`;
    // 中间值不显示文字
    for (let i = 2; i < max; i++) {
      marks[i] = '';
    }
    return marks;
  }, [containerConfig.maxCpuCores]);

  // 动态生成内存的marks (按2的幂次方: 1, 2, 4, 8, 16GB)
  const memoryMarks = useMemo(() => {
    const max = containerConfig.maxMemoryMiB;
    const marks: Record<number, string> = {};
    for (let gb = 2; gb <= 128; gb *= 2) {
      const mb = gb * 1024;
      if (mb <= max) {
        marks[mb] = `${gb}GB`;
      }
    }
    return marks;
  }, [containerConfig.maxMemoryMiB]);

  useEffect(() => {
    if (envType.length > 0) setEnvTypeOptions(envType);
  }, [envType]);


  useEffect(() => {
    if (visible) {
      // 不再自动加载，等用户点击按钮
      getConfig()
    }
    else {
      // 关闭时重置表单和数据
      form.resetFields();
      setPortMappingData([]);
      setDirectoryMountData([]);
      setDeviceMountData([]);
      setNetworkTypeList([]);
      setSelectedNetworkType([]);
      setCurrentNetworkCard('');
      setCurrentIp('');
      setConfigLoaded(false);
      setConfigLoading(false);
    }
  }, [visible]);

  return (
    <Modal
      title="容器配置"
      visible={visible}
      onOk={handleOk}
      onCancel={handleCancel}
      confirmLoading={loading}
      autoFocus={false}
      focusLock={true}
      style={{ width: '80%' }}
    >
      <Form form={form} autoComplete="off" labelCol={{ flex: 'none' }}>
        {/* 容器资源配置区域 - 需要点击按钮获取 */}
        {!configLoaded ? (
          <div style={{
            textAlign: 'center',
            padding: '20px 0',
            marginBottom: 16,
            background: '#f7f8fa',
            borderRadius: 4
          }}>
            <Button
              type="primary"
              loading={configLoading}
              onClick={getLimit}
            >
              获取容器配置
            </Button>
            <div style={{ marginTop: 8, color: '#86909c', fontSize: 13 }}>
              点击按钮获取当前环境的容器资源限制
            </div>
          </div>
        ) : (
          <>
            <Grid.Row gutter={8}>
              <Grid.Col span={12}>
                <FormItem
                  label="CPU核数："
                  field="cpuCount"
                  initialValue={1}
                >
                  <Slider
                    min={1}
                    max={containerConfig.maxCpuCores}
                    step={1}
                    showTicks={true}
                    marks={cpuMarks}
                    style={{
                      width: '90%',
                      whiteSpace: 'nowrap'
                    }}
                  />
                </FormItem>
              </Grid.Col>
              <Grid.Col span={12}>
                <FormItem
                  label="是否使用GPU："
                  field="useGpu"
                  initialValue={false}
                  triggerPropName="checked"
                >
                  <Switch checkedText="ON" uncheckedText="OFF" />
                </FormItem>
              </Grid.Col>
            </Grid.Row>
            <FormItem
              label="最大内存："
              field="memory"
              initialValue={2048}
            >
              <Slider
                min={1024}
                max={containerConfig.maxMemoryMiB}
                step={64}
                marks={memoryMarks}
                showInput={{
                  hideControl: false,
                  suffix: 'MB',
                  style: {
                    width: 100
                  }
                }}
                style={{ width: '100%' }}
              />
            </FormItem>
          </>
        )}

        {/* 以下配置默认展示 */}
        <Grid.Row gutter={8}>
          <Grid.Col span={8}>
            <FormItem
              label="网络模式："
              field="networkMode"
              rules={[{ required: true, message: '请选择网络模式' }]}
              style={{ flexWrap: 'nowrap' }}
            >
              <Select
                placeholder="请选择网络模式"
                style={{ width: '80%', minWidth: 120 }}
                onChange={(value) => fetchNetworkMode(value, addItem.id)}
              >
                {netType.map((option, index) => (
                  <Option key={option.value} value={option.value}>
                    {option.label}
                  </Option>
                ))}
              </Select>
            </FormItem>
          </Grid.Col>
          <Grid.Col span={8}>
            <FormItem
              label="网卡："
              field="networkType"
              rules={[{ required: true, message: '请选择网卡' }]}
              style={{ flexWrap: 'nowrap' }}
            >
              <Select
                placeholder="请选择网卡"
                style={{ width: '90%', minWidth: 120 }}
                value={currentNetworkCard}
                onChange={value => {
                  setCurrentNetworkCard(value);
                  form.setFieldValue('networkType', value);
                  const selectedCard = networkTypeList.find(item => item.name === value);
                  setSelectedNetworkType(selectedCard ? [selectedCard] : []);
                }}
              >
                {networkTypeList.map((option, index) => (
                  <Option key={option.type} value={option.name}>
                    {option.name}
                  </Option>
                ))}
              </Select>
            </FormItem>
          </Grid.Col>
          <Grid.Col span={8}>
            <FormItem
              label="IP："
              field="ip"
              style={{ flexWrap: 'nowrap' }}
            >
              <Input
                style={{ width: '90%', minWidth: 120 }}
                allowClear
                placeholder="请输入IP"
                value={currentIp}
                onChange={(value) => {
                  setCurrentIp(value);
                  form.setFieldValue('ip', value);
                }}
                onBlur={(e) => {
                  const value = e.target.value;
                  if (value) {
                    // IP地址正则表达式
                    const ipRegex = /^((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/;
                    if (!ipRegex.test(value)) {
                      Message.warning('请输入有效的IP地址');
                    }
                  }
                }}
              />
              <div style={{
                fontSize: 12,
                color: '#c0c4cc',
                marginTop: 10
              }}>所属子网: {selectedNetworkType.length > 0 ? selectedNetworkType[0]?.subnet : '-'}</div>
            </FormItem>
          </Grid.Col>
        </Grid.Row>
        <FormItem label="端口映射：">
          <EditableTable
            columns={portColumns}
            data={portMappingData}
            onDataChange={(newData) => setPortMappingData(newData)}
            showAddButton={true}
            addButtonText="添加行"
            showDeleteButton={true}
            deleteButtonText="删除"
            tableProps={{
              pagination: { pageSize: 5 },
              scroll: { y: 400 }
            }}
          />
        </FormItem>
        <FormItem label="目录挂载：">
          <EditableTable
            columns={directoryColumns}
            data={directoryMountData}
            onDataChange={(newData) => setDirectoryMountData(newData)}
            showAddButton={true}
            addButtonText="添加行"
            showDeleteButton={true}
            deleteButtonText="删除"
            tableProps={{
              pagination: { pageSize: 5 },
              scroll: { y: 400 }
            }}
          />
        </FormItem>
        <FormItem label="设备挂载：">
          <EditableTable
            columns={deviceColumns}
            data={deviceMountData}
            onDataChange={(newData) => setDeviceMountData(newData)}
            showAddButton={true}
            addButtonText="添加行"
            showDeleteButton={true}
            deleteButtonText="删除"
            tableProps={{
              pagination: { pageSize: 5 },
              scroll: { y: 400 }
            }}
          />
        </FormItem>
      </Form>

    </Modal>
  );
};

export default ContainerModal;