import { useState, useEffect } from 'react';
import { Card, Table, Button, App, Upload, Modal } from 'antd';
import { UploadOutlined, DownloadOutlined, ReloadOutlined } from '@ant-design/icons';
import * as XLSX from 'xlsx';
import GlassCard from '../../components/common/GlassCard';

const BackupRestorePage = () => {
  const { message } = App.useApp();
  const [loading, setLoading] = useState(false);

  // 数据备份
  const handleBackup = async () => {
    try {
      setLoading(true);
      
      // 获取所有数据
      const [users, questions, records, answers] = await Promise.all([
        fetch('/api/admin/export/users').then(res => res.json()),
        fetch('/api/admin/export/questions').then(res => res.json()),
        fetch('/api/admin/export/records').then(res => res.json()),
        fetch('/api/admin/export/answers').then(res => res.json())
      ]);

      // 创建工作簿
      const workbook = XLSX.utils.book_new();
      
      // 添加工作表
      if (users.success && users.data) {
        const usersWS = XLSX.utils.json_to_sheet(users.data);
        XLSX.utils.book_append_sheet(workbook, usersWS, '用户数据');
      }
      
      if (questions.success && questions.data) {
        const questionsWS = XLSX.utils.json_to_sheet(questions.data);
        XLSX.utils.book_append_sheet(workbook, questionsWS, '题库数据');
      }
      
      if (records.success && records.data) {
        const recordsWS = XLSX.utils.json_to_sheet(records.data);
        XLSX.utils.book_append_sheet(workbook, recordsWS, '答题记录');
      }
      
      if (answers.success && answers.data) {
        const answersWS = XLSX.utils.json_to_sheet(answers.data);
        XLSX.utils.book_append_sheet(workbook, answersWS, '答题答案');
      }

      // 下载文件
      const fileName = `问卷系统备份_${new Date().toISOString().split('T')[0]}.xlsx`;
      XLSX.writeFile(workbook, fileName);
      
      message.success('数据备份成功');
    } catch (error) {
      console.error('备份失败:', error);
      message.error('数据备份失败');
    } finally {
      setLoading(false);
    }
  };

  // 数据恢复
  const handleRestore = async (file: File) => {
    try {
      const reader = new FileReader();
      reader.onload = async (e) => {
        try {
          const data = new Uint8Array(e.target?.result as ArrayBuffer);
          const workbook = XLSX.read(data, { type: 'array' });
          
          // 解析各个工作表
          const sheetNames = workbook.SheetNames;
          const restoreData: any = {};
          
          sheetNames.forEach(sheetName => {
            const worksheet = workbook.Sheets[sheetName];
            const jsonData = XLSX.utils.sheet_to_json(worksheet);
            
            if (sheetName.includes('用户')) {
              restoreData.users = jsonData;
            } else if (sheetName.includes('题库')) {
              restoreData.questions = jsonData;
            } else if (sheetName.includes('记录')) {
              restoreData.records = jsonData;
            } else if (sheetName.includes('答案')) {
              restoreData.answers = jsonData;
            }
          });

          // 显示恢复确认对话框
          Modal.confirm({
            title: '确认数据恢复',
            content: (
              <div>
                <p>检测到以下数据：</p>
                <ul>
                  {restoreData.users && <li>用户数据：{restoreData.users.length} 条</li>}
                  {restoreData.questions && <li>题库数据：{restoreData.questions.length} 条</li>}
                  {restoreData.records && <li>答题记录：{restoreData.records.length} 条</li>}
                  {restoreData.answers && <li>答题答案：{restoreData.answers.length} 条</li>}
                </ul>
                <p style={{ color: 'red', marginTop: 16 }}>
                  警告：数据恢复将覆盖现有数据，请确保已备份当前数据！
                </p>
              </div>
            ),
            onOk: async () => {
              await performRestore(restoreData);
            },
            width: 500,
          });
        } catch (error) {
          console.error('解析文件失败:', error);
          message.error('文件解析失败，请检查文件格式');
        }
      };
      
      reader.readAsArrayBuffer(file);
    } catch (error) {
      console.error('恢复失败:', error);
      message.error('数据恢复失败');
    }
    
    return false; // 阻止上传
  };

  // 执行数据恢复
  const performRestore = async (data: any) => {
    try {
      setLoading(true);
      
      // 调用恢复API
      const response = await fetch('/api/admin/restore', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${localStorage.getItem('survey_admin') ? JSON.parse(localStorage.getItem('survey_admin')!).token : ''}`
        },
        body: JSON.stringify(data)
      });
      
      const result = await response.json();
      
      if (result.success) {
        message.success('数据恢复成功');
      } else {
        message.error(result.message || '数据恢复失败');
      }
    } catch (error) {
      console.error('恢复失败:', error);
      message.error('数据恢复失败');
    } finally {
      setLoading(false);
    }
  };

  return (
    <div>
      <div className="flex justify-between items-center mb-6">
        <h1 className="text-2xl font-bold text-white">数据备份与恢复</h1>
      </div>

      <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
        {/* 数据备份 */}
        <GlassCard title={<span className="text-white font-bold text-lg">数据备份</span>}>
          <div className="space-y-4">
            <p className="text-white/70">
              备份所有数据到Excel文件，包括用户信息、题库、答题记录等。
            </p>
            <Button
              type="primary"
              icon={<DownloadOutlined />}
              onClick={handleBackup}
              loading={loading}
              size="large"
              className="w-full"
            >
              立即备份
            </Button>
          </div>
        </GlassCard>

        {/* 数据恢复 */}
        <GlassCard title={<span className="text-white font-bold text-lg">数据恢复</span>}>
          <div className="space-y-4">
            <p className="text-white/70">
              从Excel文件恢复数据，将覆盖现有数据，请谨慎操作。
            </p>
            <Upload
              accept=".xlsx,.xls"
              showUploadList={false}
              beforeUpload={handleRestore}
            >
              <Button
                icon={<UploadOutlined />}
                loading={loading}
                size="large"
                className="w-full"
                danger
              >
                选择文件恢复
              </Button>
            </Upload>
          </div>
        </GlassCard>
      </div>

      {/* 注意事项 */}
      <Card title="注意事项" className="mt-6 shadow-sm">
        <div className="space-y-2 text-gray-600">
          <p>• 建议定期进行数据备份，以防数据丢失</p>
          <p>• 恢复数据前请确保已备份当前数据</p>
          <p>• 数据恢复操作不可撤销，请谨慎操作</p>
          <p>• 备份文件包含所有数据，请妥善保管</p>
          <p>• 建议在系统空闲时进行数据恢复操作</p>
        </div>
      </Card>
    </div>
  );
};

export default BackupRestorePage;
