<script setup lang="ts">
import type { TableColumnsType } from 'ant-design-vue';

import { onMounted, reactive, ref } from 'vue';

import {
  Button,
  Card,
  Divider,
  Form,
  Input,
  Modal,
  notification,
  Space,
  Switch,
  Table,
  Tag,
} from 'ant-design-vue';

import {
  createTelegramNotificationConfig,
  deleteTelegramNotificationConfig,
  getTelegramNotificationConfigs,
  TelegramApi,
  testTelegramNotificationConfig,
  updateTelegramNotificationConfig,
} from '#/api/core/telegram';

defineOptions({ name: 'FinanceSettings' });

// 系统设置
const settings = ref({
  defaultCurrency: 'CNY',
  notifications: {
    budget: true,
    bills: true,
    investment: false,
  },
  autoBackup: true,
  compactMode: false,
  autoLock: false,
  analytics: true,
});

// 操作加载状态
const operationLoading = ref({
  backup: false,
  import: false,
  cache: false,
  reset: false,
});

interface TelegramConfigForm {
  name: string;
  botToken: string;
  chatId: string;
  isEnabled: boolean;
  notificationTypes: string[];
}

const telegramConfigs = ref<TelegramApi.NotificationConfig[]>([]);
const telegramLoading = ref(false);
const telegramModalVisible = ref(false);
const telegramModalLoading = ref(false);
const telegramTestLoading = ref(false);
const testingRowId = ref<null | number>(null);
const togglingConfigId = ref<null | number>(null);
const editingTelegramConfig = ref<null | TelegramApi.NotificationConfig>(null);

const telegramForm = reactive<TelegramConfigForm>({
  name: '',
  botToken: '',
  chatId: '',
  isEnabled: true,
  notificationTypes: ['transaction'],
});

const telegramColumns: TableColumnsType<TelegramApi.NotificationConfig> = [
  {
    title: '配置名称',
    dataIndex: 'name',
    key: 'name',
    width: 200,
  },
  {
    title: 'Bot Token',
    key: 'botToken',
    width: 260,
  },
  {
    title: 'Chat ID',
    dataIndex: 'chatId',
    key: 'chatId',
    width: 200,
  },
  {
    title: '通知类型',
    key: 'notificationTypes',
    width: 200,
  },
  {
    title: '启用状态',
    key: 'isEnabled',
    width: 140,
  },
  {
    title: '更新时间',
    dataIndex: 'updatedAt',
    key: 'updatedAt',
    width: 200,
  },
  {
    title: '操作',
    key: 'actions',
    fixed: 'right',
    width: 220,
  },
];

function resetTelegramForm() {
  telegramForm.name = '';
  telegramForm.botToken = '';
  telegramForm.chatId = '';
  telegramForm.isEnabled = true;
  telegramForm.notificationTypes = ['transaction'];
}

function validateTelegramForm() {
  if (!telegramForm.name.trim()) {
    notification.error({
      message: '请填写配置名称',
      description: '例如：财务通知群或个人提醒',
    });
    return false;
  }

  if (!telegramForm.botToken.trim()) {
    notification.error({
      message: '请填写 Bot Token',
      description: '可从 @BotFather 获取完整的 Bot Token',
    });
    return false;
  }

  if (!telegramForm.chatId.trim()) {
    notification.error({
      message: '请填写 Chat ID',
      description: '个人或群组的 Chat ID 不能为空',
    });
    return false;
  }

  return true;
}

async function fetchTelegramConfigs() {
  telegramLoading.value = true;
  try {
    telegramConfigs.value = await getTelegramNotificationConfigs();
  } catch (error) {
    console.error('加载 Telegram 配置失败:', error);
    notification.error({
      message: '加载 Telegram 配置失败',
      description: '请稍后重试或检查后端服务状态',
    });
  } finally {
    telegramLoading.value = false;
  }
}

function openCreateTelegramConfig() {
  editingTelegramConfig.value = null;
  resetTelegramForm();
  telegramModalVisible.value = true;
}

function openEditTelegramConfig(config: TelegramApi.NotificationConfig) {
  editingTelegramConfig.value = config;
  telegramForm.name = config.name;
  telegramForm.botToken = config.botToken;
  telegramForm.chatId = config.chatId;
  telegramForm.isEnabled = config.isEnabled;
  telegramForm.notificationTypes = [...config.notificationTypes];
  telegramModalVisible.value = true;
}

function handleTelegramCancel() {
  telegramModalVisible.value = false;
  editingTelegramConfig.value = null;
  resetTelegramForm();
}

async function handleModalTestTelegramConfig() {
  const botToken = telegramForm.botToken.trim();
  const chatId = telegramForm.chatId.trim();

  if (!botToken || !chatId) {
    notification.warning({
      message: '请先填写完整的 Bot Token 和 Chat ID',
    });
    return;
  }

  telegramForm.botToken = botToken;
  telegramForm.chatId = chatId;

  telegramTestLoading.value = true;
  try {
    await testTelegramNotificationConfig({ botToken, chatId });
    notification.success({
      message: '测试消息已发送',
      description: '请在 Telegram 中检查是否收到测试通知',
    });
  } catch (error) {
    console.error('Telegram 测试失败:', error);
    notification.error({
      message: '测试失败',
      description: '请检查 Bot Token、Chat ID 或网络连接',
    });
  } finally {
    telegramTestLoading.value = false;
  }
}

async function handleTelegramSubmit() {
  if (!validateTelegramForm()) {
    return;
  }

  const name = telegramForm.name.trim();
  const botToken = telegramForm.botToken.trim();
  const chatId = telegramForm.chatId.trim();

  telegramForm.name = name;
  telegramForm.botToken = botToken;
  telegramForm.chatId = chatId;

  telegramModalLoading.value = true;

  try {
    if (editingTelegramConfig.value) {
      const payload: TelegramApi.UpdateNotificationConfigParams = {};

      if (name !== editingTelegramConfig.value.name) {
        payload.name = name;
      }

      if (botToken !== editingTelegramConfig.value.botToken) {
        payload.botToken = botToken;
      }

      if (chatId !== editingTelegramConfig.value.chatId) {
        payload.chatId = chatId;
      }

      if (
        telegramForm.notificationTypes.join(',') !==
        editingTelegramConfig.value.notificationTypes.join(',')
      ) {
        payload.notificationTypes = [...telegramForm.notificationTypes];
      }

      if (telegramForm.isEnabled !== editingTelegramConfig.value.isEnabled) {
        payload.isEnabled = telegramForm.isEnabled;
      }

      if (Object.keys(payload).length === 0) {
        notification.info({
          message: '配置未发生变化',
          description: '如需更新请修改字段后再保存',
        });
        return;
      }

      await updateTelegramNotificationConfig(
        editingTelegramConfig.value.id,
        payload,
      );

      notification.success({
        message: '配置已更新',
        description: `「${name}」已保存最新配置`,
      });
    } else {
      await createTelegramNotificationConfig({
        name,
        botToken,
        chatId,
        notificationTypes: [...telegramForm.notificationTypes],
        isEnabled: telegramForm.isEnabled,
      });

      notification.success({
        message: '配置已创建',
        description: `「${name}」已加入通知列表`,
      });
    }

    await fetchTelegramConfigs();
    handleTelegramCancel();
  } catch (error) {
    console.error('保存 Telegram 配置失败:', error);
    notification.error({
      message: '保存失败',
      description: '请检查信息是否正确或稍后再试',
    });
  } finally {
    telegramModalLoading.value = false;
  }
}

async function handleToggleTelegramConfig(
  config: TelegramApi.NotificationConfig,
  value: boolean,
) {
  togglingConfigId.value = config.id;
  try {
    await updateTelegramNotificationConfig(config.id, { isEnabled: value });
    await fetchTelegramConfigs();
    notification.success({
      message: value ? '配置已启用' : '配置已禁用',
      description: `「${config.name}」通知状态已更新`,
    });
  } catch (error) {
    console.error('更新 Telegram 状态失败:', error);
    notification.error({
      message: '状态更新失败',
      description: '请稍后重试',
    });
  } finally {
    togglingConfigId.value = null;
  }
}

async function handleTestExistingConfig(
  config: TelegramApi.NotificationConfig,
) {
  testingRowId.value = config.id;
  try {
    await testTelegramNotificationConfig({
      botToken: config.botToken,
      chatId: config.chatId,
    });
    notification.success({
      message: '测试消息已发送',
      description: `请在 Telegram 检查「${config.name}」`,
    });
  } catch (error) {
    console.error('测试 Telegram 配置失败:', error);
    notification.error({
      message: '测试失败',
      description: '请检查 Bot Token 和 Chat ID',
    });
  } finally {
    testingRowId.value = null;
  }
}

function handleDeleteTelegramConfig(config: TelegramApi.NotificationConfig) {
  Modal.confirm({
    title: `确认删除配置「${config.name}」？`,
    content: '删除后将无法继续向该目标发送 Telegram 通知。',
    okText: '删除',
    cancelText: '取消',
    okButtonProps: { danger: true },
    async onOk() {
      try {
        await deleteTelegramNotificationConfig(config.id);
        notification.success({
          message: '配置已删除',
          description: `「${config.name}」已移除`,
        });
        await fetchTelegramConfigs();
      } catch (error) {
        console.error('删除 Telegram 配置失败:', error);
        notification.error({
          message: '删除失败',
          description: '请稍后重试',
        });
        throw error;
      }
    },
  });
}

function formatDateTime(value: string) {
  try {
    return new Date(value).toLocaleString('zh-CN', {
      timeZone: 'Asia/Shanghai',
      hour12: false,
    });
  } catch {
    return value;
  }
}

function maskToken(token: string) {
  if (token.length <= 10) {
    return token;
  }
  return `${token.slice(0, 6)}...${token.slice(-4)}`;
}

const saveNotificationSettings = () => {
  localStorage.setItem(
    'app-notifications',
    JSON.stringify(settings.value.notifications),
  );
  notification.info({
    message: '通知设置已保存',
    description: '通知偏好设置已更新',
  });
};

const toggleAutoBackup = (enabled: boolean) => {
  localStorage.setItem('app-auto-backup', enabled.toString());
  notification.info({
    message: enabled ? '自动备份已启用' : '自动备份已禁用',
    description: enabled ? '系统将定期自动备份数据' : '已关闭自动备份功能',
  });
};

const toggleCompactMode = (enabled: boolean) => {
  document.documentElement.classList.toggle('compact', enabled);
  localStorage.setItem('app-compact-mode', enabled.toString());
  notification.info({
    message: enabled ? '紧凑模式已启用' : '紧凑模式已禁用',
  });
};

const toggleAutoLock = (enabled: boolean) => {
  localStorage.setItem('app-auto-lock', enabled.toString());
  notification.info({
    message: enabled ? '自动锁屏已启用' : '自动锁屏已禁用',
  });
};

const toggleAnalytics = (enabled: boolean) => {
  localStorage.setItem('app-analytics', enabled.toString());
  notification.info({
    message: enabled ? '数据统计已启用' : '数据统计已禁用',
  });
};

const backupData = async () => {
  operationLoading.value.backup = true;
  try {
    // 模拟备份过程
    await new Promise((resolve) => setTimeout(resolve, 2000));

    // 创建备份数据
    const backupData = {
      settings: settings.value,
      timestamp: new Date().toISOString(),
      version: '1.0.0',
    };

    // 下载备份文件
    const blob = new Blob([JSON.stringify(backupData, null, 2)], {
      type: 'application/json',
    });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = `finwise-pro-backup-${new Date().toISOString().split('T')[0]}.json`;
    a.click();
    URL.revokeObjectURL(url);

    notification.success({
      message: '数据备份成功',
      description: '备份文件已下载到本地',
    });
  } catch {
    notification.error({
      message: '备份失败',
      description: '数据备份过程中出现错误',
    });
  } finally {
    operationLoading.value.backup = false;
  }
};

const importData = () => {
  const input = document.createElement('input');
  input.type = 'file';
  input.accept = '.json';
  input.addEventListener('change', async (e) => {
    const file = (e.target as HTMLInputElement).files?.[0];
    if (file) {
      operationLoading.value.import = true;
      try {
        const text = await file.text();
        const importedData = JSON.parse(text);

        // 验证数据格式
        if (importedData.settings && importedData.version) {
          settings.value = { ...settings.value, ...importedData.settings };

          notification.success({
            message: '数据导入成功',
            description: '设置已从备份文件恢复',
          });
        } else {
          throw new Error('无效的备份文件格式');
        }
      } catch {
        notification.error({
          message: '导入失败',
          description: '备份文件格式无效或已损坏',
        });
      } finally {
        operationLoading.value.import = false;
      }
    }
  });
  input.click();
};

const clearCache = async () => {
  operationLoading.value.cache = true;
  try {
    // 模拟清除缓存过程
    await new Promise((resolve) => setTimeout(resolve, 1500));

    // 清除各种缓存
    if ('caches' in window) {
      const cacheNames = await caches.keys();
      await Promise.all(cacheNames.map((name) => caches.delete(name)));
    }

    // 清除localStorage中的缓存数据
    const keysToKeep = new Set(['app-currency', 'app-language', 'app-theme']);
    Object.keys(localStorage).forEach((key) => {
      if (!keysToKeep.has(key)) {
        localStorage.removeItem(key);
      }
    });

    notification.success({
      message: '缓存清除成功',
      description: '系统缓存已清理完成',
    });
  } catch {
    notification.error({
      message: '清除失败',
      description: '缓存清除过程中出现错误',
    });
  } finally {
    operationLoading.value.cache = false;
  }
};

const resetSystem = () => {
  Modal.confirm({
    title: '⚠️ 确认重置系统',
    content: '此操作将删除所有数据和设置，且不可恢复。确定要继续吗？',
    okText: '确定重置',
    okType: 'danger',
    cancelText: '取消',
    async onOk() {
      operationLoading.value.reset = true;
      try {
        // 模拟重置过程
        await new Promise((resolve) => setTimeout(resolve, 2000));

        // 清除所有本地数据
        localStorage.clear();
        sessionStorage.clear();

        notification.success({
          message: '系统重置成功',
          description: '系统将重新加载以应用重置',
        });

        // 延迟重新加载
        setTimeout(() => {
          window.location.reload();
        }, 2000);
      } catch {
        notification.error({
          message: '重置失败',
          description: '系统重置过程中出现错误',
        });
      } finally {
        operationLoading.value.reset = false;
      }
    },
  });
};

const saveAllSettings = () => {
  localStorage.setItem('app-all-settings', JSON.stringify(settings.value));
  notification.success({
    message: '设置保存成功',
    description: '所有配置已保存',
  });
};

const resetAllSettings = () => {
  settings.value = {
    defaultCurrency: 'CNY',
    notifications: {
      budget: true,
      bills: true,
      investment: false,
    },
    autoBackup: true,
    compactMode: false,
    autoLock: false,
    analytics: true,
  };

  notification.success({
    message: '设置已重置',
    description: '所有设置已恢复为默认值',
  });
};

const exportAllSettings = () => {
  const settingsData = {
    settings: settings.value,
    timestamp: new Date().toISOString(),
    version: '1.0.0',
  };

  const blob = new Blob([JSON.stringify(settingsData, null, 2)], {
    type: 'application/json',
  });
  const url = URL.createObjectURL(blob);
  const a = document.createElement('a');
  a.href = url;
  a.download = `finwise-pro-settings-${new Date().toISOString().split('T')[0]}.json`;
  a.click();
  URL.revokeObjectURL(url);

  notification.success({
    message: '设置导出成功',
    description: '配置文件已下载',
  });
};

// 初始化
onMounted(() => {
  // 从localStorage恢复设置
  try {
    const savedSettings = localStorage.getItem('app-all-settings');
    if (savedSettings) {
      const parsed = JSON.parse(savedSettings);
      settings.value = { ...settings.value, ...parsed };
    }

    settings.value.defaultCurrency =
      localStorage.getItem('app-currency') || 'CNY';
  } catch (error) {
    console.error('设置恢复失败:', error);
  }

  fetchTelegramConfigs();
});
</script>

<template>
  <div class="p-6">
    <div class="mb-6">
      <h1 class="mb-2 text-3xl font-bold text-gray-900">⚙️ 系统设置</h1>
      <p class="text-gray-600">财务系统的个性化配置和偏好设置</p>
    </div>

    <div class="grid grid-cols-1 gap-6 lg:grid-cols-2">
      <Card title="🔧 基本设置">
        <Form :model="settings" layout="vertical">
          <Divider>通知设置</Divider>

          <div class="space-y-3">
            <div class="flex items-center justify-between">
              <div>
                <span class="font-medium">💰 预算提醒</span>
                <p class="text-sm text-gray-500">预算接近或超支时提醒</p>
              </div>
              <Switch
                v-model:checked="settings.notifications.budget"
                @change="saveNotificationSettings"
              />
            </div>
            <div class="flex items-center justify-between">
              <div>
                <span class="font-medium">🔔 账单提醒</span>
                <p class="text-sm text-gray-500">账单到期前提醒缴费</p>
              </div>
              <Switch
                v-model:checked="settings.notifications.bills"
                @change="saveNotificationSettings"
              />
            </div>
            <div class="flex items-center justify-between">
              <div>
                <span class="font-medium">📊 投资更新</span>
                <p class="text-sm text-gray-500">投资收益变化通知</p>
              </div>
              <Switch
                v-model:checked="settings.notifications.investment"
                @change="saveNotificationSettings"
              />
            </div>
            <div class="flex items-center justify-between">
              <div>
                <span class="font-medium">💾 自动备份</span>
                <p class="text-sm text-gray-500">定期自动备份数据</p>
              </div>
              <Switch
                v-model:checked="settings.autoBackup"
                @change="toggleAutoBackup"
              />
            </div>
          </div>

          <Divider>高级设置</Divider>

          <div class="space-y-3">
            <div class="flex items-center justify-between">
              <span>🎨 紧凑模式</span>
              <Switch
                v-model:checked="settings.compactMode"
                @change="toggleCompactMode"
              />
            </div>
            <div class="flex items-center justify-between">
              <span>🔒 自动锁屏</span>
              <Switch
                v-model:checked="settings.autoLock"
                @change="toggleAutoLock"
              />
            </div>
            <div class="flex items-center justify-between">
              <span>📈 数据统计</span>
              <Switch
                v-model:checked="settings.analytics"
                @change="toggleAnalytics"
              />
            </div>
          </div>

          <div class="mt-6 space-x-4">
            <Button type="primary" @click="saveAllSettings">
              💾 保存所有设置
            </Button>
            <Button @click="resetAllSettings">🔄 恢复默认</Button>
            <Button @click="exportAllSettings">📤 导出配置</Button>
          </div>
        </Form>
      </Card>

      <Card title="📊 系统状态">
        <div class="space-y-3">
          <div class="flex justify-between">
            <span>系统版本:</span>
            <span>v1.0.0</span>
          </div>
          <div class="flex justify-between">
            <span>数据库大小:</span>
            <span>空</span>
          </div>
          <div class="flex justify-between">
            <span>在线状态:</span>
            <Tag color="green">正常</Tag>
          </div>
          <div class="flex justify-between">
            <span>数据记录:</span>
            <span>0条</span>
          </div>
        </div>
        <div class="mt-4 space-y-2">
          <Button block @click="backupData" :loading="operationLoading.backup">
            🗄️ 备份数据
          </Button>
          <Button block @click="importData" :loading="operationLoading.import">
            📥 导入数据
          </Button>
          <Button block @click="clearCache" :loading="operationLoading.cache">
            🧹 清除缓存
          </Button>
          <Button
            block
            danger
            @click="resetSystem"
            :loading="operationLoading.reset"
          >
            🗑️ 重置系统
          </Button>
        </div>
      </Card>

      <Card class="lg:col-span-2">
        <template #title>🚀 Telegram 通知配置</template>
        <template #extra>
          <Button type="primary" @click="openCreateTelegramConfig">
            ➕ 新增配置
          </Button>
        </template>
        <Table
          :columns="telegramColumns"
          :data-source="telegramConfigs"
          :loading="telegramLoading"
          :pagination="false"
          :row-key="(record) => record.id"
          :scroll="{ x: 960 }"
          bordered
        >
          <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'botToken'">
              <span class="font-mono text-xs">{{
                maskToken(record.botToken)
              }}</span>
            </template>

            <template v-else-if="column.key === 'notificationTypes'">
              <Space :size="4" wrap>
                <Tag
                  v-for="item in record.notificationTypes"
                  :key="item"
                  color="blue"
                >
                  {{ item }}
                </Tag>
              </Space>
            </template>

            <template v-else-if="column.key === 'isEnabled'">
              <Switch
                :checked="record.isEnabled"
                :loading="togglingConfigId === record.id"
                @change="(value) => handleToggleTelegramConfig(record, value)"
              />
            </template>

            <template v-else-if="column.dataIndex === 'updatedAt'">
              {{ formatDateTime(record.updatedAt) }}
            </template>

            <template v-else-if="column.key === 'actions'">
              <Space size="small">
                <Button
                  size="small"
                  type="link"
                  @click="openEditTelegramConfig(record)"
                >
                  编辑
                </Button>
                <Button
                  size="small"
                  type="link"
                  :loading="testingRowId === record.id"
                  @click="handleTestExistingConfig(record)"
                >
                  测试
                </Button>
                <Button
                  size="small"
                  type="link"
                  danger
                  @click="handleDeleteTelegramConfig(record)"
                >
                  删除
                </Button>
              </Space>
            </template>
          </template>
        </Table>
      </Card>
    </div>

    <Modal
      v-model:open="telegramModalVisible"
      :confirm-loading="telegramModalLoading"
      :title="editingTelegramConfig ? '编辑通知配置' : '新增通知配置'"
      destroy-on-close
      width="520px"
      @cancel="handleTelegramCancel"
    >
      <Form layout="vertical">
        <Form.Item label="配置名称" required>
          <Input
            v-model:value="telegramForm.name"
            placeholder="例如：财务通知群"
            maxlength="100"
          />
        </Form.Item>
        <Form.Item label="Bot Token" required>
          <Input
            v-model:value="telegramForm.botToken"
            placeholder="1234567890:ABCdefGHI..."
            maxlength="255"
          />
          <p class="mt-1 text-xs text-gray-500">
            从 Telegram 的 @BotFather 获取完整的 Bot Token
          </p>
        </Form.Item>
        <Form.Item label="Chat ID" required>
          <Input
            v-model:value="telegramForm.chatId"
            placeholder="-1001234567890"
            maxlength="64"
          />
          <p class="mt-1 text-xs text-gray-500">
            个人可使用 @userinfobot 查询，群组需将 Bot 加入后获取
          </p>
        </Form.Item>
        <Form.Item label="启用状态">
          <Switch v-model:checked="telegramForm.isEnabled" />
        </Form.Item>
        <Form.Item label="通知类型">
          <Space :size="4" wrap>
            <Tag
              v-for="item in telegramForm.notificationTypes"
              :key="item"
              color="blue"
            >
              {{ item }}
            </Tag>
          </Space>
        </Form.Item>
      </Form>
      <template #footer>
        <Space>
          <Button @click="handleTelegramCancel">取消</Button>
          <Button
            :loading="telegramTestLoading"
            @click="handleModalTestTelegramConfig"
          >
            发送测试
          </Button>
          <Button
            type="primary"
            :loading="telegramModalLoading"
            @click="handleTelegramSubmit"
          >
            {{ editingTelegramConfig ? '保存更新' : '创建配置' }}
          </Button>
        </Space>
      </template>
    </Modal>
  </div>
</template>

<style scoped>
.grid {
  display: grid;
}
</style>
