import React, { useState, useEffect } from 'react';
import {
  Box,
  VStack,
  Heading,
  Input,
  Button,
  Text,
  Spinner,
  Table,
  Badge,
  HStack,
  Select,
  Field,
  Portal,
  createListCollection,
} 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 { api } from '@/services/api/api';
import ConfigTool from '@/libs/config/ConfigTool';
import Common from '@/libs/common';
import Notification from '@/libs/system/Notification';
import scanEffect from '@/libs/script/scanPage/scanEffect';

/**
 * 网络扫描页面
 * @returns {JSX.Element}
 * @constructor
 */
const ScanPage = () => {
  const [subnet, setSubnet] = useState('');
  const [networkAdapters, setNetworkAdapters] = useState(createListCollection({ items: [] }));
  const [scannedDevices, setScannedDevices] = useState([]);
  const [loading, setLoading] = useState(false);
  const [localIp, setLocalIp] = useState('');
  const [selectedNetwork, setSelectedNetwork] = useState('');
  const [inputMode, setInputMode] = useState(false);

  const config = ConfigTool.load();
  const testMode = config.testMode;

  useEffect(() => {
    api.getNetworkAdapters().then((response) => {
      const { networks } = response.data;
      const networkCollection = createListCollection({
        items: networks.map((network) => ({
          label: `${network.adapter} (${network.network})`,
          value: network.network,
        })),
      });
      setNetworkAdapters(networkCollection);
      setLocalIp(config.backendUrl);
    });
  }, []);

  const handleScan = async () => {
    setLoading(true);
    try {
      let scanDevices;
      if (testMode) {
        await Common.sleep(2000);
        scanDevices = scanEffect.getTestDevices();
        Notification.success({
          title: '扫描子网设备成功！',
        });
      } else {
        const res = await api.scan(subnet);
        console.log(`res:${JSON.stringify(res)}`);
        scanDevices = res.data.devices || [];
        Notification.success({
          title: '扫描子网设备成功！',
        });
      }
      console.log(`device:${JSON.stringify(scanDevices)}`);
      scanDevices = scanDevices.map((d, idx) => ({
        ...d,
        name: `交换机 ${idx + 1}`,
      }));
      setScannedDevices(scanDevices);
      const updatedStats = {
        totalDevices: scanDevices.length,
        onlineDevices: scanDevices.length,
        lastScan: new Date().toISOString(),
      };

      ConfigTool.save({
        ...config,
        stats: updatedStats,
        devices: scanDevices,
      });
    } catch (err) {
      Notification.error({ title: '扫描网络失败' });
    }
    setLoading(false);
  };

  const handleLastScan = async () => {
    setLoading(true);
    try {
      let scanDevices;
      if (testMode) {
        await Common.sleep(500);
        scanDevices = scanEffect.getTestDevices();
        Notification.success({
          title: '获取上一次扫描记录成功！',
        });
      } else {
        const res = await api.listDevices();
        scanDevices = res.data.devices || [];
      }
      setScannedDevices(scanDevices);
    } catch (err) {
      Notification.error({ title: '获取上次扫描记录失败' });
    }
    setLoading(false);
  };

  const handleNetworkChange = ({ value }) => {
    setSelectedNetwork(value[0] ?? '');
    setSubnet(value[0] ?? '');
  };

  return (
    <DocumentTitle title={'网络扫描'}>
      <DashboardBackground />
      <PageContainer>
        <FadeInWrapper delay={0.3} yOffset={-5}>
          <VStack spacing={8} align={'stretch'}>
            <Box
              p={6}
              bg={'whiteAlpha.100'}
              borderRadius={'xl'}
              border={'1px solid'}
              borderColor={'whiteAlpha.300'}
              mx={4}
              transition={'all 0.2s'}
              _hover={{ transform: 'translateY(-4px)' }}
            >
              <Heading fontSize={'2xl'} mb={4} color={'teal.300'}>
                {'网络扫描'}
              </Heading>

              <HStack mb={4}>
                <Text fontWeight={'medium'}>{'后端服务器IP: '}</Text>
                <Badge colorPalette={'blue'}>{localIp}</Badge>
              </HStack>

              <HStack mb={4} spacing={4}>
                <Field.Root>
                  <Field.Label fontWeight={'bold'} mb={1} fontSize="sm">
                    {'选择网段'}
                  </Field.Label>
                  <Select.Root
                    collection={networkAdapters}
                    value={selectedNetwork ? [selectedNetwork] : []}
                    onValueChange={handleNetworkChange}
                    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>
                          {networkAdapters.items.map((item, index) => (
                            <Select.Item key={`${item.value}-${index}`} item={item}>
                              {' '}
                              {item.label}
                            </Select.Item>
                          ))}
                        </Select.Content>
                      </Select.Positioner>
                    </Portal>
                  </Select.Root>
                </Field.Root>

                <Button
                  mb={-7}
                  onClick={() => setInputMode(!inputMode)}
                  colorPalette={'blue'}
                  variant={'outline'}
                >
                  {inputMode ? '关闭自定义' : '自定义网段'}
                </Button>
              </HStack>

              {inputMode ? (
                <FadeInWrapper delay={0} yOffset={-1}>
                  <Input
                    mb={4}
                    placeholder={'输入子网 (如 192.168.1.0/24)'}
                    value={subnet}
                    onChange={(e) => setSubnet(e.target.value)}
                    width={'300px'}
                    bg={'whiteAlpha.200'}
                  />
                </FadeInWrapper>
              ) : null}

              <HStack mb={5} spacing={4}>
                <Button
                  onClick={handleScan}
                  isLoading={loading}
                  colorPalette={'teal'}
                  variant={'solid'}
                >
                  {'开始扫描'}
                </Button>
                <Button
                  onClick={handleLastScan}
                  isLoading={loading}
                  colorPalette={'blue'}
                  variant={'outline'}
                >
                  {'显示上次结果'}
                </Button>
              </HStack>

              {loading && (
                <FadeInWrapper delay={0} yOffset={-1}>
                  <HStack>
                    <Spinner />
                    <Text>{'正在扫描，请稍候..'}</Text>
                  </HStack>
                </FadeInWrapper>
              )}

              {!loading && scannedDevices.length > 0 && (
                <FadeInWrapper delay={0} yOffset={-3}>
                  <Table.Root
                    variant={'outline'}
                    colorPalette={'teal'}
                    size={'md'}
                    striped={'false'}
                    showColumnBorder={'true'}
                    interactive={'true'}
                    stickyHeader={'true'}
                    mt={4}
                    borderRadius={'lg'}
                    overflow={'hidden'}
                    shadow={'lg'}
                  >
                    <Table.Header bg={'transparent'}>
                      <Table.Row>
                        <Table.ColumnHeader bg={'whiteAlpha.100'} backdropFilter={'blur(4px)'}>
                          {'IP 地址'}
                        </Table.ColumnHeader>
                        <Table.ColumnHeader bg={'whiteAlpha.100'} backdropFilter={'blur(4px)'}>
                          {'MAC 地址'}
                        </Table.ColumnHeader>
                        <Table.ColumnHeader bg={'whiteAlpha.100'} backdropFilter={'blur(4px)'}>
                          {'开放端口'}
                        </Table.ColumnHeader>
                      </Table.Row>
                    </Table.Header>
                    <Table.Body>
                      {scannedDevices.map((d) => (
                        <Table.Row
                          key={d.ip}
                          _hover={{
                            bgGradient: 'linear(to-r, teal.50, blue.50)',
                            transition: 'background 0.3s ease',
                          }}
                        >
                          <Table.Cell>{d.ip}</Table.Cell>
                          <Table.Cell>{d.mac}</Table.Cell>
                          <Table.Cell>{d.ports.join(', ')}</Table.Cell>
                        </Table.Row>
                      ))}
                    </Table.Body>
                  </Table.Root>
                </FadeInWrapper>
              )}

              {!loading && scannedDevices.length === 0 && (
                <FadeInWrapper delay={0} yOffset={-1}>
                  <Text color={'gray.400'}>{'暂无扫描结果，请执行扫描..'}</Text>
                </FadeInWrapper>
              )}
            </Box>
          </VStack>
        </FadeInWrapper>
      </PageContainer>
    </DocumentTitle>
  );
};

export default ScanPage;
