import React, { useEffect, useState } from 'react';
import {
  Box,
  VStack,
  Heading,
  Text,
  SimpleGrid,
  Input,
  Button,
  HStack,
  Image,
  Collapsible,
} 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 Common from '@/libs/common';
import switchIcon from '@/resources/icon/pages/devices/switch.png';
import Notification from '@/libs/system/Notification';
import DeviceConfigModal from '@/components/pages/config/DeviceConfigModal';

/**
 * 交换机管理
 * @returns {JSX.Element}
 * @constructor
 */
const DevicesPage = () => {
  const [devices, setDevices] = useState([]);
  const [editingIndex, setEditingIndex] = useState(null);
  const [editingName, setEditingName] = useState('');
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [currentDevice, setCurrentDevice] = useState(null);

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

  const handleEdit = (idx) => {
    setEditingIndex(idx);
    setEditingName(devices[idx].name);
  };

  const handleSave = (idx) => {
    const updated = [...devices];
    updated[idx].name = editingName;
    Common.sleep(200).then(() => {
      setDevices(updated);
      ConfigTool.save({ ...ConfigTool.load(), devices: updated });
      Notification.success({
        title: '设备重命名成功！',
      });
      setEditingIndex(null);
    });
  };

  const handleOpenConfigModal = (device) => {
    setCurrentDevice(device);
    setIsModalOpen(true);
  };

  const handleSaveDeviceConfig = (updatedDevice) => {
    const updatedDevices = devices.map((device) =>
      device.ip === updatedDevice.ip ? updatedDevice : device
    );
    setDevices(updatedDevices);
    ConfigTool.save({ ...ConfigTool.load(), devices: updatedDevices });
    Notification.success({
      title: '设备配置已保存！',
    });
    setIsModalOpen(false);
  };

  return (
    <DocumentTitle title={'交换机设备'}>
      <DashboardBackground />
      <PageContainer>
        <FadeInWrapper delay={0.3} yOffset={-5}>
          <VStack gap={4} align={'stretch'}>
            <Heading fontSize={'2xl'} color={'teal.300'}>
              {'交换机设备管理'}
            </Heading>

            <SimpleGrid columns={{ base: 1, md: 3 }} gap={3}>
              {devices.map((device, idx) => (
                <Box
                  key={device.ip}
                  p={4}
                  bg={'whiteAlpha.100'}
                  borderRadius={'xl'}
                  border={'1px solid'}
                  borderColor={'whiteAlpha.300'}
                  transition={'all 0.3s ease'}
                  _hover={{ transform: 'translateY(-8px)', bg: 'whiteAlpha.200' }}
                >
                  <Image src={switchIcon} alt={'Switch'} borderRadius={'md'} mb={3} />

                  <Collapsible.Root open={editingIndex === idx}>
                    <Collapsible.Trigger asChild>
                      <Box mb={3} cursor={'pointer'}>
                        {editingIndex === idx ? null : (
                          <HStack justify={'space-between'}>
                            <Text fontSize={'lg'} fontWeight={'bold'}>
                              {device.name}
                            </Text>
                            <Button
                              size={'xs'}
                              colorPalette={'teal'}
                              onClick={() => handleEdit(idx)}
                            >
                              {'重命名'}
                            </Button>
                          </HStack>
                        )}
                      </Box>
                    </Collapsible.Trigger>

                    <Collapsible.Content>
                      <HStack mb={3}>
                        <Input
                          value={editingName}
                          onChange={(e) => setEditingName(e.target.value)}
                          size={'sm'}
                          bg={'whiteAlpha.300'}
                        />
                        <Button size={'sm'} colorPalette={'teal'} onClick={() => handleSave(idx)}>
                          {'保存'}
                        </Button>
                      </HStack>
                    </Collapsible.Content>
                  </Collapsible.Root>

                  <Text fontSize={'sm'}>
                    {'IP: '}
                    {device.ip}
                  </Text>
                  <Text fontSize={'sm'}>
                    {'MAC: '}
                    {device.mac}
                  </Text>
                  <Text fontSize={'sm'}>
                    {'端口: '}
                    {device.ports.join(', ')}
                  </Text>

                  <Button
                    size={'sm'}
                    colorPalette={'teal'}
                    mt={2}
                    onClick={() => handleOpenConfigModal(device)}
                  >
                    配置
                  </Button>
                </Box>
              ))}
            </SimpleGrid>

            {devices.length === 0 && (
              <Text color={'gray.400'}>{'暂无扫描记录，请先进行网络扫描'}</Text>
            )}
          </VStack>
        </FadeInWrapper>
      </PageContainer>

      {isModalOpen && currentDevice && (
        <DeviceConfigModal
          isOpen={isModalOpen}
          onClose={() => setIsModalOpen(false)}
          onSave={handleSaveDeviceConfig}
          device={currentDevice}
        />
      )}
    </DocumentTitle>
  );
};

export default DevicesPage;
