/**
 * Agent Types List Page
 *
 * Displays a list of agent types with search and filter functionality.
 * Allows navigation to agent type detail and creation pages.
 */

'use client';

import { useState, useCallback, useMemo } from 'react';
import { useRouter } from 'next/navigation';
import { toast } from 'sonner';
import { AgentTypeList } from '@/components/agents';
import { useAgentTypes } from '@/lib/api/hooks/useAgentTypes';
import { useDebounce } from '@/lib/hooks/useDebounce';

export default function AgentTypesPage() {
  const router = useRouter();

  // Filter state
  const [searchQuery, setSearchQuery] = useState('');
  const [statusFilter, setStatusFilter] = useState('all');

  // Debounce search for API calls
  const debouncedSearch = useDebounce(searchQuery, 300);

  // Determine is_active filter value
  const isActiveFilter = useMemo(() => {
    if (statusFilter === 'active') return true;
    if (statusFilter === 'inactive') return false;
    return undefined; // 'all' returns undefined to not filter
  }, [statusFilter]);

  // Fetch agent types
  const { data, isLoading, error } = useAgentTypes({
    search: debouncedSearch || undefined,
    is_active: isActiveFilter,
    page: 1,
    limit: 50,
  });

  // Filter results client-side for 'all' status
  const filteredAgentTypes = useMemo(() => {
    if (!data?.data) return [];

    // When status is 'all', we need to fetch both and combine
    // For now, the API returns based on is_active filter
    return data.data;
  }, [data?.data]);

  // Handle navigation to agent type detail
  const handleSelect = useCallback(
    (id: string) => {
      router.push(`/agents/${id}`);
    },
    [router]
  );

  // Handle navigation to create page
  const handleCreate = useCallback(() => {
    router.push('/agents/new');
  }, [router]);

  // Handle search change
  const handleSearchChange = useCallback((query: string) => {
    setSearchQuery(query);
  }, []);

  // Handle status filter change
  const handleStatusFilterChange = useCallback((status: string) => {
    setStatusFilter(status);
  }, []);

  // Show error toast if fetch fails
  if (error) {
    toast.error('Failed to load agent types', {
      description: 'Please try again later',
    });
  }

  return (
    <div className="container mx-auto px-4 py-6">
      <AgentTypeList
        agentTypes={filteredAgentTypes}
        isLoading={isLoading}
        searchQuery={searchQuery}
        onSearchChange={handleSearchChange}
        statusFilter={statusFilter}
        onStatusFilterChange={handleStatusFilterChange}
        onSelect={handleSelect}
        onCreate={handleCreate}
      />
    </div>
  );
}
