import { describe, it, expect, vi, beforeEach } from 'vitest';
import { render, screen, fireEvent, waitFor } from '@testing-library/react';
import React from 'react';
import TimeBlocks from '../TimeBlocks';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';

// Import the mocked hooks so we can control their return values
import {
  useTimeBlocks,
  useCreateTimeBlock,
  useUpdateTimeBlock,
  useDeleteTimeBlock,
  useToggleTimeBlock,
  useHolidays,
  usePendingReviews,
  useApproveTimeBlock,
  useDenyTimeBlock,
} from '../../hooks/useTimeBlocks';
import { useResources } from '../../hooks/useResources';

// Mock hooks
vi.mock('../../hooks/useTimeBlocks', () => ({
  useTimeBlocks: vi.fn(),
  useCreateTimeBlock: vi.fn(),
  useUpdateTimeBlock: vi.fn(),
  useDeleteTimeBlock: vi.fn(),
  useToggleTimeBlock: vi.fn(),
  useHolidays: vi.fn(),
  usePendingReviews: vi.fn(),
  useApproveTimeBlock: vi.fn(),
  useDenyTimeBlock: vi.fn(),
}));

vi.mock('../../hooks/useResources', () => ({
  useResources: vi.fn(),
}));

// Mock translation
vi.mock('react-i18next', () => ({
  useTranslation: () => ({
    t: (key: string, defaultVal: string) => defaultVal || key,
  }),
}));

// Mock child components that might be complex
vi.mock('../../components/time-blocks/YearlyBlockCalendar', () => ({
  default: () => <div data-testid="yearly-calendar">Yearly Calendar</div>,
}));

vi.mock('../../components/time-blocks/TimeBlockCreatorModal', () => ({
  default: ({ isOpen, onClose }: any) => (
    isOpen ? <div data-testid="creator-modal"><button onClick={onClose}>Close</button></div> : null
  ),
}));

// Setup wrapper
const createWrapper = () => {
  const queryClient = new QueryClient({
    defaultOptions: { queries: { retry: false } },
  });
  return ({ children }: { children: React.ReactNode }) => (
    <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
  );
};

// Helper to set up all mock return values
const setupMocks = () => {
  const mockMutation = { mutateAsync: vi.fn(), isPending: false };

  vi.mocked(useTimeBlocks).mockReturnValue({
    data: [
      { id: '1', title: 'Test Block', block_type: 'HARD', recurrence_type: 'NONE', is_active: true }
    ],
    isLoading: false
  } as any);

  vi.mocked(useResources).mockReturnValue({
    data: [{ id: 'res-1', name: 'Test Resource' }]
  } as any);

  vi.mocked(usePendingReviews).mockReturnValue({
    data: { count: 0, pending_blocks: [] }
  } as any);

  vi.mocked(useHolidays).mockReturnValue({ data: [] } as any);

  // Set up mutation hooks
  vi.mocked(useCreateTimeBlock).mockReturnValue(mockMutation as any);
  vi.mocked(useUpdateTimeBlock).mockReturnValue(mockMutation as any);
  vi.mocked(useDeleteTimeBlock).mockReturnValue(mockMutation as any);
  vi.mocked(useToggleTimeBlock).mockReturnValue(mockMutation as any);
  vi.mocked(useApproveTimeBlock).mockReturnValue(mockMutation as any);
  vi.mocked(useDenyTimeBlock).mockReturnValue(mockMutation as any);
};

describe('TimeBlocks Page', () => {
  beforeEach(() => {
    vi.clearAllMocks();
    setupMocks();
  });

  it('renders page title', () => {
    render(<TimeBlocks />, { wrapper: createWrapper() });
    expect(screen.getByText('Time Blocks')).toBeInTheDocument();
  });

  it('renders tabs', () => {
    render(<TimeBlocks />, { wrapper: createWrapper() });
    expect(screen.getByText('Business Blocks')).toBeInTheDocument();
    expect(screen.getByText('Resource Blocks')).toBeInTheDocument();
    expect(screen.getByText('Yearly View')).toBeInTheDocument();
  });

  it('displays business blocks by default', () => {
    render(<TimeBlocks />, { wrapper: createWrapper() });
    expect(screen.getByText('Test Block')).toBeInTheDocument();
  });

  it('opens creator modal when add button clicked', async () => {
    render(<TimeBlocks />, { wrapper: createWrapper() });
    fireEvent.click(screen.getByText('Add Block'));
    expect(screen.getByTestId('creator-modal')).toBeInTheDocument();
  });

  it('switches tabs correctly', async () => {
    render(<TimeBlocks />, { wrapper: createWrapper() });

    fireEvent.click(screen.getByText('Resource Blocks'));
    // Since we mocked useTimeBlocks to return the same data regardless of args in the default mock,
    // we might see the same block if we don't differentiate.
    // But the component filters/requests differently.
    // In the real component, it calls useTimeBlocks({ level: 'resource' }).
    // We can just check if the tab became active.

    // Check if Calendar tab works
    fireEvent.click(screen.getByText('Yearly View'));
    expect(screen.getByTestId('yearly-calendar')).toBeInTheDocument();
  });
});
