import { useState } from 'react';
import { useQueryClient } from '@tanstack/react-query';
import { reposApi } from '../../lib/api/repos';
import { toast } from 'sonner';

interface FileTreeHeaderProps {
  owner: string;
  repo: string;
}

export function FileTreeHeader({ owner, repo }: FileTreeHeaderProps) {
  const [isRefreshing, setIsRefreshing] = useState(false);
  const queryClient = useQueryClient();

  const handleRefresh = async () => {
    setIsRefreshing(true);

    try {
      // Invalidate backend cache
      const result = await reposApi.invalidateCache(owner, repo);

      // Invalidate React Query cache
      await queryClient.invalidateQueries({
        queryKey: ['files', owner, repo],
        refetchType: 'all', // Force refetch even for inactive queries
      });

      toast.success(`Cache cleared! ${result.invalidated_count} entries invalidated.`);
    } catch (error) {
      console.error('Failed to refresh cache:', error);
      toast.error('Failed to refresh cache. Please try again.');
    } finally {
      setIsRefreshing(false);
    }
  };

  return (
    <div className="p-4 border-b border-gray-200 flex items-center justify-between">
      <div className="text-sm font-semibold text-gray-900">Files</div>
      <button
        onClick={handleRefresh}
        disabled={isRefreshing}
        className="text-xs px-3 py-1.5 rounded-md border border-gray-300 hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed flex items-center gap-1.5 transition-colors"
        title="Refresh file list (clears cache)"
      >
        <svg
          className={`w-3.5 h-3.5 ${isRefreshing ? 'animate-spin' : ''}`}
          fill="none"
          viewBox="0 0 24 24"
          stroke="currentColor"
        >
          <path
            strokeLinecap="round"
            strokeLinejoin="round"
            strokeWidth={2}
            d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"
          />
        </svg>
        <span>{isRefreshing ? 'Refreshing...' : 'Refresh'}</span>
      </button>
    </div>
  );
}
