import { describe, it, expect, beforeEach, vi } from 'vitest'
import { mount } from '@vue/test-utils'
import { createPinia, setActivePinia } from 'pinia'
import { useUi } from '@/stores/useUi'
import { usePlanillasStore } from '@/stores/usePlanillas'
import PlanillasIndex from '../PlanillasIndex.vue'
import TablaPlanillas from '@/components/planillas/tablaPlanillas.vue'
import CardPlanilla from '@/components/planillas/cardPlanilla.vue'

// Mock child components
vi.mock('@/components/planillas/tablaPlanillas.vue', () => ({
  default: {
    name: 'TablaPlanillas',
    props: ['planillas'], // Match actual props
    emits: ['edit'],
    template: '<div data-testid="tabla-planillas"></div>',
  },
}))

vi.mock('@/components/planillas/cardPlanilla.vue', () => ({
  default: {
    name: 'CardPlanilla',
    props: ['planilla'], // Match actual props
    emits: ['edit'],
    template: '<div data-testid="card-planilla"></div>',
  },
}))

// Mock stores
const mockSetDefaultViewPlanillas = vi.fn();
const mockFetchPlanillas = vi.fn();

vi.mock('@/stores/useUi', () => ({
  useUi: vi.fn(() => ({
    defaultViewPlanillas: 'table', // Default mock value
    setDefaultViewPlanillas: mockSetDefaultViewPlanillas,
  })),
}))

vi.mock('@/stores/usePlanillas', () => ({
  usePlanillasStore: vi.fn(() => ({
    planillas: [],
    fetchPlanillas: mockFetchPlanillas,
  })),
}))

describe('PlanillasIndex.vue', () => {
  let uiStoreMock
  let planillasStoreMock

  beforeEach(() => {
    setActivePinia(createPinia())
    mockFetchPlanillas.mockClear().mockResolvedValue([])
    mockSetDefaultViewPlanillas.mockClear()

    uiStoreMock = useUi()
    planillasStoreMock = usePlanillasStore()
  })

  const mountComponent = () => {
    return mount(PlanillasIndex, {
      global: {},
    })
  }

  it('fetches planillas on mount', async () => {
    mountComponent()
    await mockFetchPlanillas(); // Ensure the promise from fetch resolves
    expect(mockFetchPlanillas).toHaveBeenCalledTimes(1)
  })

  describe('View Rendering based on useUi store', () => {
    it('renders TablaPlanillas when defaultViewPlanillas is "table"', async () => {
      uiStoreMock.defaultViewPlanillas = 'table'
      planillasStoreMock.planillas = [{ id: 1, periodo: '2023-01', total: 5000 }]

      const wrapper = mountComponent()
      await mockFetchPlanillas();
      await wrapper.vm.$nextTick() // Wait for reactivity
      await wrapper.vm.$nextTick() // Additional tick if loading state causes multiple updates

      expect(wrapper.findComponent({ name: 'TablaPlanillas' }).exists()).toBe(true)
      expect(wrapper.findComponent({ name: 'TablaPlanillas' }).props('planillas')).toEqual(planillasStoreMock.planillas)
      expect(wrapper.findComponent({ name: 'CardPlanilla' }).exists()).toBe(false)
    })

    it('renders CardPlanilla when defaultViewPlanillas is "card"', async () => {
      uiStoreMock.defaultViewPlanillas = 'card'
      planillasStoreMock.planillas = [{ id: 1, P1: 'P1' }, { id: 2, P2: 'P2' }]

      const wrapper = mountComponent()
      await mockFetchPlanillas();
      await wrapper.vm.$nextTick()
      await wrapper.vm.$nextTick()

      const cardWrappers = wrapper.findAllComponents({ name: 'CardPlanilla' })
      expect(cardWrappers.length).toBe(planillasStoreMock.planillas.length)
      expect(cardWrappers[0].props('planilla')).toEqual(planillasStoreMock.planillas[0])
      expect(wrapper.findComponent({ name: 'TablaPlanillas' }).exists()).toBe(false)
    })

    it('renders no data message for table view when no planillas exist', async () => {
        uiStoreMock.defaultViewPlanillas = 'table';
        planillasStoreMock.planillas = [];

        const wrapper = mountComponent();
        await mockFetchPlanillas();
        await wrapper.vm.$nextTick();
        await wrapper.vm.$nextTick();

        expect(wrapper.findComponent({ name: 'TablaPlanillas' }).exists()).toBe(true);
        expect(wrapper.text()).toContain('No hay planillas para mostrar');
    });

    it('renders no data message for card view when no planillas exist', async () => {
        uiStoreMock.defaultViewPlanillas = 'card';
        planillasStoreMock.planillas = [];

        const wrapper = mountComponent();
        await mockFetchPlanillas();
        await wrapper.vm.$nextTick();
        await wrapper.vm.$nextTick();

        expect(wrapper.findAllComponents({ name: 'CardPlanilla' }).length).toBe(0);
        expect(wrapper.text()).toContain('No hay planillas para mostrar');
    });
  })

  describe('Local View Toggle Buttons', () => {
    it('renders toggle buttons and reflects initial view from store (table)', async () => {
      uiStoreMock.defaultViewPlanillas = 'table';
      const wrapper = mountComponent();
      await mockFetchPlanillas();
      await wrapper.vm.$nextTick();
      await wrapper.vm.$nextTick();

      const tableViewButton = wrapper.find('button[aria-label="Table View"]');
      const cardViewButton = wrapper.find('button[aria-label="Card View"]');

      expect(tableViewButton.exists()).toBe(true);
      expect(cardViewButton.exists()).toBe(true);
      expect(tableViewButton.classes()).toContain('bg-[var(--accent-color-planillas)]');
      expect(cardViewButton.classes()).toContain('bg-gray-200');
    });

    it('renders toggle buttons and reflects initial view from store (card)', async () => {
      uiStoreMock.defaultViewPlanillas = 'card';
      const wrapper = mountComponent();
      await mockFetchPlanillas();
      await wrapper.vm.$nextTick();
      await wrapper.vm.$nextTick();

      const tableViewButton = wrapper.find('button[aria-label="Table View"]');
      const cardViewButton = wrapper.find('button[aria-label="Card View"]');

      expect(cardViewButton.classes()).toContain('bg-[var(--accent-color-planillas)]');
      expect(tableViewButton.classes()).toContain('bg-gray-200');
    });

    it('switches to card view on button click and updates button styles, does not call global store action', async () => {
      uiStoreMock.defaultViewPlanillas = 'table';
      planillasStoreMock.planillas = [{ id: 1, periodo: 'Test' }];
      const wrapper = mountComponent();
      await mockFetchPlanillas();
      await wrapper.vm.$nextTick();
      await wrapper.vm.$nextTick();

      const cardViewButton = wrapper.find('button[aria-label="Card View"]');
      const tableViewButton = wrapper.find('button[aria-label="Table View"]');

      await cardViewButton.trigger('click');
      await wrapper.vm.$nextTick();

      expect(wrapper.findComponent({ name: 'CardPlanilla' }).exists()).toBe(true);
      expect(wrapper.findComponent({ name: 'TablaPlanillas' }).exists()).toBe(false);
      expect(cardViewButton.classes()).toContain('bg-[var(--accent-color-planillas)]');
      expect(tableViewButton.classes()).toContain('bg-gray-200');
      expect(mockSetDefaultViewPlanillas).not.toHaveBeenCalled();
    });

    it('switches back to table view on button click and updates button styles, does not call global store action', async () => {
      uiStoreMock.defaultViewPlanillas = 'card'; // Start with card view
      planillasStoreMock.planillas = [{ id: 1, periodo: 'Test' }];
      const wrapper = mountComponent();
      await mockFetchPlanillas();
      await wrapper.vm.$nextTick();
      await wrapper.vm.$nextTick();

      const cardViewButton = wrapper.find('button[aria-label="Card View"]');
      const tableViewButton = wrapper.find('button[aria-label="Table View"]');
      expect(cardViewButton.classes()).toContain('bg-[var(--accent-color-planillas)]');

      await tableViewButton.trigger('click');
      await wrapper.vm.$nextTick();

      expect(wrapper.findComponent({ name: 'TablaPlanillas' }).exists()).toBe(true);
      expect(wrapper.findComponent({ name: 'CardPlanilla' }).exists()).toBe(false);
      expect(tableViewButton.classes()).toContain('bg-[var(--accent-color-planillas)]');
      expect(cardViewButton.classes()).toContain('bg-gray-200');
      expect(mockSetDefaultViewPlanillas).not.toHaveBeenCalled();
    });
  });
})
