import { useState, useRef, useCallback, useEffect } from 'react';
import { useNavigation } from '../../contexts/NavigationContext';
import AppHeader from '../../components/Layout/AppHeader';
import EnvironmentSwitchModal from '../../components/Modal/EnvironmentSwitchModal';
import { check, type Update, type DownloadEvent } from '@tauri-apps/plugin-updater';
import { relaunch } from '@tauri-apps/plugin-process';
import { saveAppConfig } from '../../api/modules/config';
import { invoke } from '@tauri-apps/api/core';
import { toast } from '../../store/uiStore';
import '../ContentManagement/ContentManagement.css';

const CURRENT_VERSION = __APP_VERSION__;

export default function Settings() {
  const { navigate, appEnvironment } = useNavigation();

  // ── 系统更新状态 ──
  const [checking, setChecking] = useState(false);
  const [checkResult, setCheckResult] = useState<'none' | 'latest' | 'available'>('none');
  const [updateInfo, setUpdateInfo] = useState<Update | null>(null);
  const [downloading, setDownloading] = useState(false);
  const [installing, setInstalling] = useState(false);
  const [progress, setProgress] = useState(0);
  const [downloadedBytes, setDownloadedBytes] = useState(0);
  const [totalBytes, setTotalBytes] = useState(0);
  const [updateError, setUpdateError] = useState<string | null>(null);

  // ── 环境切换 ──
  const [showEnvModal, setShowEnvModal] = useState(false);

  // ── 缓存清理 ──
  const [cacheSize, setCacheSize] = useState(0);
  const [clearingCache, setClearingCache] = useState(false);
  const clickCountRef = useRef(0);
  const clickTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);

  const formatBytes = (bytes: number) => {
    if (bytes === 0) {return '0 B';}
    const k = 1024;
    const sizes = ['B', 'KB', 'MB', 'GB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    return `${(bytes / Math.pow(k, i)).toFixed(1)} ${sizes[i]}`;
  };

  const handleCheck = async () => {
    setChecking(true);
    setCheckResult('none');
    setUpdateError(null);
    setUpdateInfo(null);

    try {
      const update = await check();
      if (update) {
        setUpdateInfo(update);
        setCheckResult('available');
      } else {
        setCheckResult('latest');
      }
    } catch (err) {
      console.error('[Settings] 检查更新失败:', err);
      setUpdateError(err instanceof Error ? err.message : '检查更新失败');
      setCheckResult('none');
    } finally {
      setChecking(false);
    }
  };

  const handleDownloadAndInstall = async () => {
    if (!updateInfo) {return;}

    setDownloading(true);
    setProgress(0);
    setDownloadedBytes(0);
    setTotalBytes(0);
    setUpdateError(null);

    let totalSize = 0;

    try {
      await updateInfo.downloadAndInstall((event: DownloadEvent) => {
        switch (event.event) {
          case 'Started':
            totalSize = event.data.contentLength ?? 0;
            setTotalBytes(totalSize);
            break;
          case 'Progress':
            setDownloadedBytes(prev => {
              const next = prev + event.data.chunkLength;
              if (totalSize > 0) {
                setProgress(Math.min(Math.round((next / totalSize) * 100), 100));
              }
              return next;
            });
            break;
          case 'Finished':
            setProgress(100);
            break;
        }
      });

      setDownloading(false);
      setInstalling(true);
    } catch (err) {
      console.error('[Settings] 下载安装失败:', err);
      setUpdateError(err instanceof Error ? err.message : '下载安装失败');
      setDownloading(false);
    }
  };

  const handleRelaunch = async () => {
    try {
      await relaunch();
    } catch (err) {
      setUpdateError(err instanceof Error ? err.message : '重启失败');
    }
  };

  // ── 版本号连击 ──
  const handleVersionClick = useCallback(() => {
    clickCountRef.current += 1;

    if (clickCountRef.current === 5) {
      setShowEnvModal(true);
      clickCountRef.current = 0;
      if (clickTimerRef.current) { clearTimeout(clickTimerRef.current); }
      return;
    }

    if (clickTimerRef.current) { clearTimeout(clickTimerRef.current); }
    clickTimerRef.current = setTimeout(() => {
      clickCountRef.current = 0;
    }, 2000);
  }, []);

  // 获取媒体缓存大小（视频缓存 + BGM 缓存）
  const fetchCacheSize = useCallback(async () => {
    try {
      const [videoSize, bgmSize] = await Promise.all([
        invoke<number>('get_video_cache_size_cmd'),
        invoke<number>('get_bgm_cache_size_cmd'),
      ]);
      setCacheSize(videoSize + bgmSize);
    } catch {
      setCacheSize(0);
    }
  }, []);

  useEffect(() => {
    fetchCacheSize();
    return () => {
      if (clickTimerRef.current) {
        clearTimeout(clickTimerRef.current);
      }
    };
  }, [fetchCacheSize]);

  // 清理媒体缓存（视频缓存 + BGM 缓存）
  const handleClearCache = async () => {
    if (cacheSize === 0) {
      toast.info('暂无缓存需要清理');
      return;
    }
    setClearingCache(true);
    try {
      const [videoFreed, bgmFreed] = await Promise.all([
        invoke<number>('clear_video_cache_cmd'),
        invoke<number>('clear_bgm_cache_cmd'),
      ]);
      const totalFreed = videoFreed + bgmFreed;
      setCacheSize(0);
      toast.success(`已清理 ${formatBytes(totalFreed)} 缓存`);
    } catch {
      toast.error('清理缓存失败');
    } finally {
      setClearingCache(false);
    }
  };

  const handleSaveEnv = async (env: string) => {
    try {
      await saveAppConfig(env);

      if (import.meta.env.DEV) {
        toast.success('配置已保存，即将刷新');
        setTimeout(() => { window.location.reload(); }, 500);
        return;
      }

      toast.success('配置已保存，应用即将重启');
      setTimeout(() => { invoke('restart_app'); }, 800);
    } catch {
      toast.error('保存配置失败');
    }
  };

  return (
    <div className="settings-page">
      <AppHeader title="设置" showBack onBack={() => navigate('profile')} />

      {/* 关于我们 */}
      <div className="settings-section">
        <div className="card about-card" style={{ padding: 'var(--spacing-lg)', overflow: 'hidden' }}>
          {/* 品牌 */}
          <div className="about-brand">
            <img className="about-logo" src="/assets/logo.png" alt="美家卡智影" />
            <span className="about-name">美家卡 智影</span>
          </div>

          {/* 版本 + 检查更新 */}
          <div className="about-version-row">
            <span
              className="about-version-text"
              onClick={handleVersionClick}
              title={appEnvironment !== 'production' ? `当前环境: ${appEnvironment}` : undefined}
            >
              当前版本 v{CURRENT_VERSION}
            </span>
            <button
              className="btn btn-sm about-check-btn"
              onClick={handleCheck}
              disabled={checking || downloading}
            >
              {checking ? '检查中' : '检查更新'}
            </button>
          </div>
          <div className="about-version-status">
            {checking ? (
              <span className="about-checking-status">
                <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="var(--primary)" strokeWidth="2" style={{ animation: 'spin 1s linear infinite' }}>
                  <path d="M21 12a9 9 0 11-6.219-8.56" />
                </svg>
                检查中...
              </span>
            ) : checkResult === 'latest' ? (
              <span className="about-check-result about-check-latest">当前已是最新版本</span>
            ) : checkResult === 'available' ? (
              <span className="about-check-result about-check-available">发现新版本 {updateInfo?.version}</span>
            ) : null}
          </div>

          {/* 更新详情（发现新版本时展开） */}
          {checkResult === 'available' && updateInfo && (
            <div className="about-update-detail">
              {updateInfo.body && (
                <div className="about-update-body">
                  <div className="about-update-body-title">更新内容</div>
                  <pre>{updateInfo.body}</pre>
                </div>
              )}

              {downloading && (
                <div className="about-update-progress">
                  <div className="about-progress-bar">
                    <div className="about-progress-fill" style={{ width: `${progress}%` }} />
                  </div>
                  <div className="about-progress-meta">
                    <span>{progress}%</span>
                    {totalBytes > 0 && <span>{formatBytes(downloadedBytes)} / {formatBytes(totalBytes)}</span>}
                  </div>
                </div>
              )}

              <div className="about-update-actions">
                {installing ? (
                  <button className="btn btn-primary btn-sm" onClick={handleRelaunch}>立即重启</button>
                ) : (
                  <button className="btn btn-primary btn-sm" onClick={handleDownloadAndInstall} disabled={downloading}>
                    {downloading ? '下载中...' : '立即更新'}
                  </button>
                )}
              </div>
            </div>
          )}

          {updateError && (
            <div className="about-update-error">
              {updateError}
            </div>
          )}
        </div>
      </div>

      {/* 缓存清理 */}
      <div className="settings-section">
        <h2>缓存管理</h2>
        <div className="card" style={{ padding: 0, overflow: 'hidden' }}>
          <div className="settings-row">
            <span className="settings-row-label">本地文件缓存</span>
            <div className="settings-row-value" style={{ display: 'flex', alignItems: 'center', gap: 'var(--spacing-md)', justifyContent: 'flex-end' }}>
              <span style={{ fontSize: 'var(--font-sm)', color: 'var(--text-tertiary)' }}>
                {cacheSize > 0 ? formatBytes(cacheSize) : '暂无缓存'}
              </span>
              <button
                className="btn btn-sm about-check-btn"
                onClick={handleClearCache}
                disabled={clearingCache || cacheSize === 0}
              >
                {clearingCache ? '清理中...' : '立即清理'}
              </button>
            </div>
          </div>
        </div>
      </div>

      {/* 授权信息 */}
      <div className="settings-section">
        <h2>授权信息</h2>
        <div className="card" style={{ padding: 'var(--spacing-xl)' }}>
          <p style={{ lineHeight: 1.8, margin: 0 }}>
            本软件由美家卡团队开发维护。授权用户可在授权范围内使用本软件进行视频创作。
            如需商业授权或有任何疑问，请联系我们的支持团队（support@meijiaka.cn）。
          </p>
        </div>
      </div>

      {/* 版权声明 */}
      <div className="settings-section">
        <h2>版权声明</h2>
        <div className="card" style={{ padding: 'var(--spacing-xl)' }}>
          <p style={{ lineHeight: 1.8, margin: 0 }}>
            Copyright 2025 美家卡 (meijiaka.cn). All rights reserved.
          </p>
          <p style={{ lineHeight: 1.8, marginTop: 'var(--spacing-md)', marginBottom: 0 }}>
            本软件及其相关文档的所有权利均归美家卡所有。
            未经授权，不得复制、修改、分发或以其他方式使用本软件。
          </p>
        </div>
      </div>

      <EnvironmentSwitchModal
        key={appEnvironment}
        open={showEnvModal}
        currentEnv={appEnvironment}
        onSave={handleSaveEnv}
        onCancel={() => setShowEnvModal(false)}
      />
    </div>
  );
}
