import { useState, useEffect, useRef } from 'react';
import SubCard from 'ui-component/cards/SubCard';
import {
  Stack,
  FormControl,
  InputLabel,
  OutlinedInput,
  Button,
  Alert,
  TextField,
  Switch,
  FormControlLabel,
  Divider,
  Typography,
  Chip,
  Tooltip,
  IconButton,
  InputAdornment,
} from '@mui/material';
import Grid from '@mui/material/Unstable_Grid2';
import { showError, showSuccess } from 'utils/common';
import { API } from 'utils/api';

const ServerConfigSetting = () => {
  const [configs, setConfigs] = useState([]);
  const [loading, setLoading] = useState(false);
  const fileInputRef = useRef(null);

  const getConfigs = async () => {
    setLoading(true);
    const res = await API.get('/api/server/config/');
    const { success, message, data } = res.data;
    if (success) {
      setConfigs(data);
    } else {
      showError(message);
    }
    setLoading(false);
  };

  useEffect(() => {
    getConfigs().then();
  }, []);

  const categories = [
    { key: 'database', title: '数据库' },
    { key: 'redis', title: 'Redis' },
    { key: 'performance', title: '性能与调试' },
    { key: 'network', title: '网络与代理' },
    { key: 'ratelimit', title: '速率限制' },
    { key: 'metrics', title: '指标与监控' },
    { key: 'other', title: '其他设置' },
  ];

  const getConfigsByCategory = (category) => {
    return configs.filter((item) => item.category === category);
  };

  const isSecretKey = (key) => {
    const secretKeys = [
      'SESSION_SECRET', 'REDIS_PASSWORD', 'REDIS_CONN_STRING',
      'SQL_DSN', 'LOG_SQL_DSN', 'HTTPS_PROXY',
    ];
    return secretKeys.includes(key);
  };

  const isBooleanKey = (key) => {
    const booleanKeys = [
      'DEBUG', 'DEBUG_SQL', 'MEMORY_CACHE_ENABLED', 'BATCH_UPDATE_ENABLED',
      'ENABLE_METRIC', 'ONLY_ONE_LOG_FILE', 'ENFORCE_INCLUDE_USAGE',
    ];
    return booleanKeys.includes(key);
  };

  const isNumericKey = (key) => {
    const numericKeys = [
      'BATCH_UPDATE_INTERVAL', 'RELAY_TIMEOUT', 'USER_CONTENT_REQUEST_TIMEOUT',
      'GLOBAL_API_RATE_LIMIT', 'GLOBAL_WEB_RATE_LIMIT', 'METRIC_QUEUE_SIZE',
      'METRIC_SUCCESS_RATE_THRESHOLD', 'PORT', 'SQLITE_BUSY_TIMEOUT',
      'SQL_MAX_IDLE_CONNS', 'SQL_MAX_OPEN_CONNS', 'SQL_MAX_LIFETIME',
      'SYNC_FREQUENCY', 'CHANNEL_TEST_FREQUENCY',
    ];
    return numericKeys.includes(key);
  };

  const handleValueChange = (key, value) => {
    setConfigs((prev) =>
      prev.map((item) => (item.key === key ? { ...item, value } : item))
    );
  };

  const updateConfig = async (key, value) => {
    setLoading(true);
    const res = await API.put('/api/server/config/', { key, value });
    const { success, message } = res.data;
    if (success) {
      showSuccess('设置已更新');
    } else {
      showError(message);
      getConfigs().then();
    }
    setLoading(false);
  };

  const handleSaveRuntime = async (key) => {
    const item = configs.find((c) => c.key === key);
    if (!item) return;
    let value = item.value;
    if (isBooleanKey(key)) {
      value = value === 'true' ? 'true' : 'false';
    }
    await updateConfig(key, value);
  };

  const handleToggle = async (key) => {
    const item = configs.find((c) => c.key === key);
    if (!item) return;
    const newValue = item.value === 'true' ? 'false' : 'true';
    setConfigs((prev) =>
      prev.map((c) => (c.key === key ? { ...c, value: newValue } : c))
    );
    await updateConfig(key, newValue);
  };

  const handleDownloadEnv = async () => {
    try {
      const res = await API.get('/api/server/config/download', {
        responseType: 'blob',
      });
      const url = window.URL.createObjectURL(new Blob([res.data]));
      const link = document.createElement('a');
      link.href = url;
      link.setAttribute('download', 'server-config.env');
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      window.URL.revokeObjectURL(url);
      showSuccess('配置已下载');
    } catch (error) {
      showError('下载失败');
    }
  };

  const handleImportClick = () => {
    fileInputRef.current?.click();
  };

  const handleImportEnv = async (e) => {
    const file = e.target.files[0];
    if (!file) return;

    const formData = new FormData();
    formData.append('file', file);

    setLoading(true);
    try {
      const res = await API.post('/api/server/config/import', formData, {
        headers: { 'Content-Type': 'multipart/form-data' },
      });
      const { success, message } = res.data;
      if (success) {
        showSuccess(message);
      } else {
        showError(message);
      }
    } catch (error) {
      showError('导入失败，请检查文件格式');
    }
    setLoading(false);
    e.target.value = '';
  };

  const renderConfigInput = (item) => {
    const { key, value, restart_required } = item;

    if (isBooleanKey(key)) {
      return (
        <Grid xs={12} key={key}>
          <FormControlLabel
            control={
              <Switch
                checked={value === 'true'}
                onChange={() => handleToggle(key)}
              />
            }
            label={
              <span>
                {key}
                {restart_required && (
                  <Chip
                    label="需要重启"
                    color="warning"
                    size="small"
                    sx={{ ml: 1 }}
                  />
                )}
              </span>
            }
          />
        </Grid>
      );
    }

    if (key === 'db_type') {
      return (
        <Grid xs={12} sm={6} key={key}>
          <TextField
            fullWidth
            label={
              <span>
                {key}
                {restart_required && (
                  <Chip
                    label="需要重启"
                    color="warning"
                    size="small"
                    sx={{ ml: 1 }}
                  />
                )}
              </span>
            }
            value={value}
            InputProps={{ readOnly: true }}
          />
        </Grid>
      );
    }

    return (
      <Grid xs={12} sm={6} key={key}>
        <TextField
          fullWidth
          label={
            <span>
              {key}
              {restart_required && (
                <Chip
                  label="需要重启"
                  color="warning"
                  size="small"
                  sx={{ ml: 1 }}
                />
              )}
            </span>
          }
          placeholder={item.default_value}
          value={value}
          type={isSecretKey(key) ? 'password' : isNumericKey(key) ? 'number' : 'text'}
          onChange={(e) => {
            const target = e.target;
            handleValueChange(key, target.value);
          }}
          InputProps={
            !restart_required
              ? {
                  endAdornment: (
                    <InputAdornment position="end">
                      <Button
                        variant="contained"
                        color="success"
                        size="small"
                        onClick={() => handleSaveRuntime(key)}
                      >
                        保存
                      </Button>
                    </InputAdornment>
                  ),
                }
              : undefined
          }
        />
      </Grid>
    );
  };

  return (
    <SubCard>
      <Stack spacing={3}>
        <Alert severity="info" sx={{ mb: 2 }}>
          <Typography variant="subtitle1" fontWeight="bold">
            关于服务器配置
          </Typography>
          <Typography variant="body2">
            此处显示的是通过环境变量或命令行参数配置的服务器设置。部分设置修改后需要重启服务才能生效。
            您可以使用「下载 .env」按钮导出完整配置，修改后重启即可。
          </Typography>
        </Alert>

        <Stack direction="row" spacing={2}>
          <Button variant="contained" color="primary" onClick={handleDownloadEnv}>
            下载 .env
          </Button>
          <Button variant="contained" color="secondary" onClick={handleImportClick}>
            导入 .env
          </Button>
          <input
            ref={fileInputRef}
            type="file"
            accept=".env,.txt"
            style={{ display: 'none' }}
            onChange={handleImportEnv}
          />
          <Button variant="outlined" onClick={getConfigs}>
            刷新
          </Button>
        </Stack>

        {categories.map((cat) => {
          const catConfigs = getConfigsByCategory(cat.key);
          if (catConfigs.length === 0) return null;

          return (
            <div key={cat.key}>
              <Divider sx={{ my: 2 }} />
              <Typography variant="h5" gutterBottom>
                {cat.title}（共 {catConfigs.length} 项）
              </Typography>
              <Grid container spacing={2}>
                {catConfigs.map((item) => renderConfigInput(item))}
              </Grid>
            </div>
          );
        })}
      </Stack>
    </SubCard>
  );
};

export default ServerConfigSetting;