import { useState, useEffect, useRef } from 'react';
import {
  Button,
  Box,
  Dialog,
  DialogBackdrop,
  DialogPositioner,
  DialogContent,
  DialogCloseTrigger,
  DialogHeader,
  DialogBody,
  DialogFooter,
  Field,
  Input,
  Portal,
  Stack,
} from '@chakra-ui/react';
import { motion, AnimatePresence } from 'framer-motion';
import { IoClose } from 'react-icons/io5';
import { FiCheck } from 'react-icons/fi';
import ConfigTool, { defaultConfig } from '@/libs/config/ConfigTool';

const MotionBox = motion(Box);

/**
 * 连接地址配置组件
 * @param isOpen 打开状态
 * @param onClose 关闭状态
 * @param onSave 保存状态
 * @returns {JSX.Element}
 * @constructor
 */
const ConnectionConfigModal = ({ isOpen, onClose, onSave }) => {
  const [config, setConfig] = useState(defaultConfig);
  const [saved, setSaved] = useState(false);
  const backendRef = useRef(null);

  useEffect(() => {
    setConfig(ConfigTool.load());
  }, []);

  const handleChange = (e) => {
    const { name, value } = e.target;
    setConfig((prev) => ({ ...prev, [name]: value }));
  };

  const handleSave = () => {
    ConfigTool.save(config);
    onSave(config);
    setSaved(true);
    setTimeout(() => {
      setSaved(false);
      onClose();
    }, 1200);
  };

  const handleClear = () => {
    ConfigTool.clear();
    setConfig(defaultConfig);
    onClose();
  };

  return (
    <Dialog.Root open={isOpen} onClose={onClose} initialFocusEl={() => backendRef.current}>
      <Portal>
        <DialogBackdrop backdropFilter={'blur(8px) hue-rotate(0deg)'} bg={'rgba(0, 0, 0, 0.3)'} />
        <DialogPositioner>
          <MotionBox
            as={DialogContent}
            initial={{ opacity: 0, scale: 0.8 }}
            animate={{ opacity: 1, scale: 1 }}
            exit={{ opacity: 0, scale: 0.8 }}
            transition={{ duration: 0.3 }}
            bg={'whiteAlpha.100'}
            backdropFilter={'blur(12px)'}
            border={'1px solid'}
            borderColor={'whiteAlpha.300'}
          >
            <DialogHeader color={'white'}>地址配置</DialogHeader>
            <DialogCloseTrigger asChild>
              <Button
                variant={'outline'}
                borderColor={'whiteAlpha.500'}
                color={'white'}
                size={'sm'}
                position={'absolute'}
                top={3}
                right={3}
                onClick={onClose}
                _hover={{ bg: 'rgba(255, 0, 0, 0.3)' }}
              >
                <IoClose size={20} color={'white'} />
              </Button>
            </DialogCloseTrigger>

            <DialogBody>
              <Stack gap="4">
                <Field.Root>
                  <Field.Label color={'white'}>后端连接地址</Field.Label>
                  <Input
                    ref={backendRef}
                    name={'backendUrl'}
                    value={config.backendUrl}
                    onChange={handleChange}
                    placeholder={'http://127.0.0.1:8000'}
                    bg={'whiteAlpha.200'}
                    color={'white'}
                  />
                </Field.Root>
                <Field.Root>
                  <Field.Label color={'white'}>连接密钥</Field.Label>
                  <Input
                    name={'authKey'}
                    type={'password'}
                    value={config.authKey}
                    onChange={handleChange}
                    placeholder={'123456'}
                    bg={'whiteAlpha.200'}
                    color={'white'}
                  />
                </Field.Root>
              </Stack>
            </DialogBody>

            <DialogFooter justifyContent={'space-between'}>
              <Button
                variant={'outline'}
                borderColor={'whiteAlpha.500'}
                color={'white'}
                onClick={handleClear}
                _hover={{ bg: 'rgba(0, 0, 255, 0.3)' }}
              >
                清除配置
              </Button>

              <Stack direction={'row'} spacing={3}>
                <Button
                  variant={'outline'}
                  borderColor={'whiteAlpha.500'}
                  color={'white'}
                  onClick={onClose}
                  _hover={{ bg: 'rgba(0, 0, 255, 0.3)' }}
                >
                  取消
                </Button>

                <Button
                  variant={'outline'}
                  borderColor={'whiteAlpha.500'}
                  color={'white'}
                  onClick={handleSave}
                  isDisabled={saved}
                  width={'80px'}
                  position={'relative'}
                  _hover={{ bg: 'rgba(0, 0, 255, 0.3)' }}
                >
                  <AnimatePresence initial={false} mode={'wait'}>
                    {saved ? (
                      <motion.div
                        key={'saved'}
                        initial={{ opacity: 0, scale: 0.5 }}
                        animate={{ opacity: 1, scale: 1 }}
                        exit={{ opacity: 0, scale: 0.5 }}
                        transition={{ duration: 0.3 }}
                      >
                        <FiCheck size={20} color={'lightgreen'} />
                      </motion.div>
                    ) : (
                      <motion.div
                        key={'save'}
                        initial={{ opacity: 0, scale: 0.5 }}
                        animate={{ opacity: 1, scale: 1 }}
                        exit={{ opacity: 0, scale: 0.5 }}
                        transition={{ duration: 0.3 }}
                      >
                        保存
                      </motion.div>
                    )}
                  </AnimatePresence>
                </Button>
              </Stack>
            </DialogFooter>
          </MotionBox>
        </DialogPositioner>
      </Portal>
    </Dialog.Root>
  );
};

export default ConnectionConfigModal;
