import { useState, useEffect, useCallback } from 'react';

interface UsePWAReturn {
  isInstallable: boolean;
  isInstalled: boolean;
  isOffline: boolean;
  hasUpdate: boolean;
  install: () => Promise<void>;
  update: () => void;
}

interface BeforeInstallPromptEvent extends Event {
  readonly platforms: string[];
  prompt(): Promise<void>;
  userChoice: Promise<{ outcome: 'accepted' | 'dismissed'; platform: string }>;
}

let deferredPrompt: BeforeInstallPromptEvent | null = null;
let swRegistration: ServiceWorkerRegistration | null = null;
let updateCallback: (() => void) | null = null;

/**
 * 注册 Service Worker 并监听其更新
 */
export function registerServiceWorker(): void {
  if (!('serviceWorker' in navigator)) return;

  window.addEventListener('load', () => {
    navigator.serviceWorker.register('/sw.js').then((reg) => {
      swRegistration = reg;
      console.log('SW registered:', reg.scope);

      // 监听 SW 更新
      reg.addEventListener('updatefound', () => {
        const newWorker = reg.installing;
        if (!newWorker) return;

        newWorker.addEventListener('statechange', () => {
          if (newWorker.state === 'installed' && navigator.serviceWorker.controller) {
            // 有新 SW 等待激活
            updateCallback?.();
          }
        });
      });
    }).catch((err) => {
      console.log('SW registration failed:', err);
    });

    // 定期检查更新 (每 60 分钟)
    setInterval(() => {
      if (swRegistration) {
        swRegistration.update().catch(() => {});
      }
    }, 60 * 60 * 1000);
  });
}

/**
 * usePWA Hook - 管理 PWA 安装和更新
 */
export function usePWA(): UsePWAReturn {
  const [isInstallable, setIsInstallable] = useState(false);
  const [isInstalled, setIsInstalled] = useState(false);
  const [isOffline, setIsOffline] = useState(!navigator.onLine);
  const [hasUpdate, setHasUpdate] = useState(false);

  // 检测是否已安装为 PWA
  useEffect(() => {
    const checkInstalled = () => {
      const standalone = window.matchMedia('(display-mode: standalone)').matches;
      const safariStandalone = (navigator as Navigator & { standalone?: boolean }).standalone === true;
      setIsInstalled(standalone || safariStandalone);
    };

    checkInstalled();

    const mediaQuery = window.matchMedia('(display-mode: standalone)');
    mediaQuery.addEventListener('change', checkInstalled);

    return () => {
      mediaQuery.removeEventListener('change', checkInstalled);
    };
  }, []);

  // 监听 beforeinstallprompt 事件
  useEffect(() => {
    const handler = (e: Event) => {
      e.preventDefault();
      deferredPrompt = e as BeforeInstallPromptEvent;
      setIsInstallable(true);
    };

    window.addEventListener('beforeinstallprompt', handler);

    return () => {
      window.removeEventListener('beforeinstallprompt', handler);
    };
  }, []);

  // 监听 online/offline 事件
  useEffect(() => {
    const handleOnline = () => setIsOffline(false);
    const handleOffline = () => setIsOffline(true);

    window.addEventListener('online', handleOnline);
    window.addEventListener('offline', handleOffline);

    return () => {
      window.removeEventListener('online', handleOnline);
      window.removeEventListener('offline', handleOffline);
    };
  }, []);

  // 注册 SW 更新回调
  useEffect(() => {
    updateCallback = () => setHasUpdate(true);
    return () => {
      updateCallback = null;
    };
  }, []);

  // 安装 PWA
  const install = useCallback(async () => {
    if (!deferredPrompt) {
      console.log('PWA: beforeinstallprompt 不可用');
      return;
    }

    try {
      await deferredPrompt.prompt();
      const { outcome } = await deferredPrompt.userChoice;
      console.log(`PWA: 用户 ${outcome === 'accepted' ? '接受' : '拒绝'} 安装`);
      deferredPrompt = null;
      setIsInstallable(false);

      if (outcome === 'accepted') {
        setIsInstalled(true);
      }
    } catch (err) {
      console.error('PWA install error:', err);
    }
  }, []);

  // 更新 SW
  const update = useCallback(() => {
    if (!swRegistration || !swRegistration.waiting) {
      // 尝试触发更新检查
      if (swRegistration) {
        swRegistration.update().catch(() => {});
      }
      return;
    }

    // 通知等待中的 SW 跳过等待
    swRegistration.waiting.postMessage({ type: 'SKIP_WAITING' });

    swRegistration.waiting.addEventListener('statechange', (e) => {
      const worker = e.target as ServiceWorker;
      if (worker.state === 'activated') {
        setHasUpdate(false);
        window.location.reload();
      }
    });
  }, []);

  return {
    isInstallable,
    isInstalled,
    isOffline,
    hasUpdate,
    install,
    update,
  };
}
