'use client';

import { useState, useEffect } from 'react';
import { AlertCircle, RefreshCw, Info } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { getVersion, VersionInfo } from '@/lib/api';

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

  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 = await response.json();
          setCurrentVersion(data.version);
        }
      } catch (error) {
        console.warn('Failed to load UI version:', error);
      } finally {
        setLoading(false);
      }
    };

    loadCurrentVersion();
  }, []);

  useEffect(() => {
    // Check server version periodically (every 5 minutes)
    const checkVersion = async () => {
      try {
        const versionInfo = await getVersion();
        setServerVersion(versionInfo);

        // If we have both versions and they don't match, show update notification
        if (currentVersion && versionInfo.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 (loading || !serverVersion) {
    return null;
  }

  // Version badge display (always visible in footer/header)
  const VersionBadge = () => (
    <div className="flex items-center gap-2 text-xs text-muted-foreground">
      <Info className="h-3 w-3" />
      <span>v{serverVersion.version}</span>
      {!serverVersion.clean && <span className="text-amber-500">*</span>}
    </div>
  );

  // Update notification overlay
  if (showUpdate) {
    return (
      <>
        <VersionBadge />
        <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 UI has been deployed. Current: {currentVersion}, Server: {serverVersion.version}. 
                Refresh to get 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>
      </>
    );
  }

  return <VersionBadge />;
}