import React, { useEffect, useState } from 'react';
import {
  Box,
  Button,
  createListCollection,
  Field,
  Heading,
  HStack,
  Portal,
  Select,
  Text,
  Textarea,
  VStack,
} from '@chakra-ui/react';
import DocumentTitle from '@/components/system/pages/DocumentTitle';
import PageContainer from '@/components/system/PageContainer';
import DashboardBackground from '@/components/system/pages/DashboardBackground';
import FadeInWrapper from '@/components/system/layout/FadeInWrapper';
import ConfigTool from '@/libs/config/ConfigTool';
import { api } from '@/services/api/api';
import Notification from '@/libs/system/Notification';
import Common from '@/libs/common';
import configEffect from '@/libs/script/configPage/configEffect';

const testMode = ConfigTool.load().testMode;

const ConfigPage = () => {
  const [devices, setDevices] = useState([]);
  const [selectedDevice, setSelectedDevice] = useState('');
  const [inputText, setInputText] = useState('');
  const [parsedConfig, setParsedConfig] = useState('');
  const [editableConfig, setEditableConfig] = useState('');
  const [applying, setApplying] = useState(false);
  const [hasParsed, setHasParsed] = useState(false);

  const deviceCollection = createListCollection({
    items: devices.map((device) => ({
      label: `${device.name} (${device.ip})`,
      value: device.ip,
    })),
  });

  useEffect(() => {
    const config = ConfigTool.load();
    setDevices(config.devices || []);
  }, []);

  const handleParse = async () => {
    if (!selectedDevice || !inputText.trim()) {
      Notification.error({
        title: '操作失败',
        description: '请选择设备并输入配置指令',
      });
      return;
    }

    try {
      const performParse = async () => {
        if (testMode) {
          await Common.sleep(800 + Math.random() * 700);
          return await configEffect.generateRealisticConfig(inputText, devices);
        }
        return await api.parseCommand(inputText);
      };

      const resultWrapper = await Notification.promise({
        promise: performParse(),
        loading: {
          title: '正在解析配置',
          description: '正在分析您的指令..',
        },
        success: {
          title: '解析完成',
          description: '已生成交换机配置',
        },
        error: {
          title: '解析失败',
          description: '请检查指令格式或网络连接',
        },
      });

      const result = await resultWrapper.unwrap();

      if (result?.config) {
        setParsedConfig(result.config);
        setEditableConfig(result.config);
        setHasParsed(true);
      }
    } catch (error) {
      console.error('配置解析异常:', error);
      Notification.error({
        title: '配置解析异常',
        description: error.message,
      });
    }
  };

  const handleApply = async () => {
    if (!editableConfig.trim()) {
      Notification.warn({
        title: '配置为空',
        description: '请先解析或编辑有效配置',
      });
      return;
    }

    setApplying(true);
    try {
      const applyOperation = testMode
        ? Common.sleep(1000).then(() => ({ success: true }))
        : await api.applyConfig(selectedDevice, editableConfig);

      await Notification.promise({
        promise: applyOperation,
        loading: {
          title: '配置应用中',
          description: '正在推送配置到设备...',
        },
        success: {
          title: '应用成功',
          description: '配置已成功生效',
        },
        error: {
          title: '应用失败',
          description: '请检查设备连接或配置内容',
        },
      });
    } finally {
      setApplying(false);
    }
  };

  return (
    <DocumentTitle title={'交换机配置'}>
      <DashboardBackground />
      <PageContainer>
        <FadeInWrapper delay={0.3} yOffset={-5}>
          <VStack spacing={6} align={'stretch'}>
            <Heading fontSize={'xl'} color={'teal.300'}>
              交换机配置中心
            </Heading>

            <Field.Root>
              <Field.Label fontWeight={'bold'} mb={1} fontSize="sm">
                选择交换机设备
              </Field.Label>
              <Select.Root
                collection={deviceCollection}
                value={selectedDevice ? [selectedDevice] : []}
                onValueChange={({ value }) => setSelectedDevice(value[0] ?? '')}
                placeholder={'请选择交换机设备'}
                size={'sm'}
                colorPalette={'teal'}
              >
                <Select.HiddenSelect />
                <Select.Control>
                  <Select.Trigger>
                    <Select.ValueText />
                  </Select.Trigger>
                  <Select.IndicatorGroup>
                    <Select.Indicator />
                    <Select.ClearTrigger />
                  </Select.IndicatorGroup>
                </Select.Control>
                <Portal>
                  <Select.Positioner>
                    <Select.Content>
                      {deviceCollection.items.map((item) => (
                        <Select.Item key={item.value} item={item}>
                          {item.label}
                        </Select.Item>
                      ))}
                    </Select.Content>
                  </Select.Positioner>
                </Portal>
              </Select.Root>
            </Field.Root>

            <Field.Root>
              <Field.Label fontWeight={'bold'} mb={1} fontSize="sm">
                配置指令输入
              </Field.Label>
              <Textarea
                rows={4}
                placeholder={'例子：创建VLAN 10并配置IP 192.168.10.1/24并在端口1启用SSH访问"'}
                value={inputText}
                onChange={(e) => setInputText(e.target.value)}
                bg={'whiteAlpha.200'}
                size={'sm'}
              />
            </Field.Root>

            <Button
              colorScheme={'teal'}
              variant={'solid'}
              size={'sm'}
              onClick={handleParse}
              isDisabled={!selectedDevice || !inputText.trim()}
            >
              解析配置
            </Button>

            {hasParsed && (
              <FadeInWrapper>
                <Box
                  p={4}
                  bg={'whiteAlpha.100'}
                  borderRadius={'xl'}
                  border={'1px solid'}
                  borderColor={'whiteAlpha.300'}
                >
                  <Text fontWeight={'bold'} mb={2} fontSize="sm">
                    生成配置:
                  </Text>
                  <Textarea
                    value={editableConfig}
                    rows={12}
                    onChange={(e) => setEditableConfig(e.target.value)}
                    fontFamily={'monospace'}
                    size={'sm'}
                    bg={'blackAlpha.200'}
                  />
                  <HStack mt={4} spacing={3} justify={'flex-end'}>
                    <Button
                      variant={'outline'}
                      colorScheme={'gray'}
                      size={'sm'}
                      onClick={() => {
                        setEditableConfig(parsedConfig);
                        Notification.success({
                          title: '成功重置配置！',
                          description: '现在您可以重新审查生成的配置',
                        });
                      }}
                    >
                      重置为原始配置
                    </Button>
                    <Button
                      colorScheme={'teal'}
                      size={'sm'}
                      onClick={handleApply}
                      isLoading={applying}
                      isDisabled={!editableConfig.trim()}
                    >
                      应用到交换机
                    </Button>
                  </HStack>
                </Box>
              </FadeInWrapper>
            )}
          </VStack>
        </FadeInWrapper>
      </PageContainer>
    </DocumentTitle>
  );
};

export default ConfigPage;
