'use client';

import { useState, useEffect } from 'react';
import { AlertCircle, RefreshCw } from 'lucide-react';
import { Button } from './ui/button';

interface VersionInfo {
  version: string;
  buildTime: string;
}

export function VersionChecker() {
  const [currentVersion, setCurrentVersion] = useState<string | null>(null);
  const [serverVersion, setServerVersion] = useState<string | null>(null);
  const [showUpdate, setShowUpdate] = useState(false);

  useEffect(() => {
    // Get initial version from version.json
    const loadCurrentVersion = async () => {
      try {
        const response = await fetch('/ui/version.json', {
          cache: 'no-store' // Always fetch fresh version
        });
        if (response.ok) {
          const data: VersionInfo = await response.json();
          setCurrentVersion(data.version);
        }
      } catch (error) {
        console.warn('Failed to load UI version:', error);
      }
    };

    loadCurrentVersion();
  }, []);

  useEffect(() => {
    // Check server version periodically (every 5 minutes)
    const checkVersion = async () => {
      try {
        // Check if __SERVER_CONFIG__ is available
        if (typeof window !== 'undefined' && (window as any).__SERVER_CONFIG__) {
          const config = (window as any).__SERVER_CONFIG__;
          const version = config.uiVersion;

          if (version && version !== 'unknown') {
            setServerVersion(version);

            // If we have both versions and they don't match, show update notification
            if (currentVersion && version !== currentVersion) {
              setShowUpdate(true);
            }
          }
        }
      } catch (error) {
        console.warn('Failed to check server version:', error);
      }
    };

    // Initial check after 2 seconds
    const initialTimeout = setTimeout(checkVersion, 2000);

    // Periodic check every 5 minutes
    const interval = setInterval(checkVersion, 5 * 60 * 1000);

    return () => {
      clearTimeout(initialTimeout);
      clearInterval(interval);
    };
  }, [currentVersion]);

  const handleRefresh = () => {
    // Force reload to get new version
    window.location.reload();
  };

  if (!showUpdate) {
    return null;
  }

  return (
    <div className="fixed top-4 left-1/2 transform -translate-x-1/2 z-50 animate-in slide-in-from-top duration-300">
      <div className="bg-amber-500 dark:bg-amber-600 text-white px-4 py-3 rounded-lg shadow-lg flex items-center gap-3 max-w-md">
        <AlertCircle className="h-5 w-5 flex-shrink-0" />
        <div className="flex-1">
          <p className="font-semibold">New UI Version Available</p>
          <p className="text-sm opacity-90">
            A new version of the UI has been deployed. Refresh to get the latest updates.
          </p>
        </div>
        <Button
          size="sm"
          variant="secondary"
          onClick={handleRefresh}
          className="flex-shrink-0"
        >
          <RefreshCw className="h-4 w-4 mr-1" />
          Refresh
        </Button>
      </div>
    </div>
  );
}
