import { renderHook, act } from '@testing-library/react-native'
import { useCategoryTemplates } from './use-category-templates'
import { root } from '@repo/core'
import { TemplateController } from '@repo/sdk'
import { handleError } from './use-error'
import { OWNER_ID } from '@/lib/auth'

jest.mock('@repo/core', () => ({
  root: {
    get: jest.fn(),
  },
}))

jest.mock('./use-error', () => ({
  handleError: jest.fn(async (cb) => {
    try {
      const data = await cb()
      return { data, error: null }
    } catch (e) {
      return { data: null, error: e }
    }
  }),
}))

jest.mock('@/lib/auth', () => ({
  OWNER_ID: 'test-owner-id',
}))

describe('useCategoryTemplates', () => {
  beforeEach(() => {
    jest.clearAllMocks()
  })

  afterEach(() => {
    jest.restoreAllMocks()
  })

  describe('initial state', () => {
    it('should return initial state with no data', () => {
      const { result } = renderHook(() => useCategoryTemplates('category-1'))

      expect(result.current.data).toBeUndefined()
      expect(result.current.templates).toEqual([])
      expect(result.current.loading).toBe(false)
      expect(result.current.loadingMore).toBe(false)
      expect(result.current.error).toBeNull()
      expect(result.current.hasMore).toBe(true)
    })
  })

  describe('loading state', () => {
    it('should set loading to true during fetch', async () => {
      let resolveFetch: (value: any) => void
      const fetchPromise = new Promise((resolve) => {
        resolveFetch = resolve
      })

      const mockController = {
        list: jest.fn().mockReturnValue(fetchPromise),
      }
      ;(root.get as jest.Mock).mockReturnValue(mockController)

      const { result } = renderHook(() => useCategoryTemplates('category-1'))

      act(() => {
        result.current.execute()
      })

      expect(result.current.loading).toBe(true)

      await act(async () => {
        resolveFetch!({ templates: [], total: 0, page: 1, limit: 20, totalPages: 1 })
        await fetchPromise
      })

      expect(result.current.loading).toBe(false)
    })

    it('should set loading to false after error', async () => {
      const mockError = { status: 500, message: 'Error' }

      const mockController = {
        list: jest.fn().mockRejectedValue(mockError),
      }
      ;(root.get as jest.Mock).mockReturnValue(mockController)

      const { result } = renderHook(() => useCategoryTemplates('category-1'))

      await act(async () => {
        await result.current.execute()
      })

      expect(result.current.loading).toBe(false)
    })
  })

  describe('execute function', () => {
    it('should load templates with categoryId successfully', async () => {
      const mockData = {
        templates: [
          { id: '1', title: 'Template 1', titleEn: 'Template 1 EN', previewUrl: 'url1', coverImageUrl: 'cover1', aspectRatio: '16:9' },
          { id: '2', title: 'Template 2', titleEn: 'Template 2 EN', previewUrl: 'url2', coverImageUrl: 'cover2', aspectRatio: '16:9' },
        ],
        total: 2,
        page: 1,
        limit: 20,
        totalPages: 1,
      }

      const mockController = {
        list: jest.fn().mockResolvedValue(mockData),
      }
      ;(root.get as jest.Mock).mockReturnValue(mockController)

      const { result } = renderHook(() => useCategoryTemplates('category-1'))

      await act(async () => {
        await result.current.execute()
      })

      expect(mockController.list).toHaveBeenCalledWith(
        expect.objectContaining({
          categoryId: 'category-1',
          ownerId: OWNER_ID,
          page: 1,
        })
      )
      expect(result.current.data).toEqual(mockData)
      expect(result.current.templates).toEqual(mockData.templates)
      expect(result.current.error).toBeNull()
      expect(result.current.hasMore).toBe(false)
    })

    it('should handle API errors', async () => {
      const mockError = {
        status: 500,
        statusText: 'Internal Server Error',
        message: 'Failed to load templates',
      }

      const mockController = {
        list: jest.fn().mockRejectedValue(mockError),
      }
      ;(root.get as jest.Mock).mockReturnValue(mockController)

      const { result } = renderHook(() => useCategoryTemplates('category-1'))

      await act(async () => {
        await result.current.execute()
      })

      expect(result.current.error).toEqual(mockError)
      expect(result.current.data).toBeUndefined()
    })

    it('should merge custom params with defaults', async () => {
      const mockData = {
        templates: [],
        total: 0,
        page: 2,
        limit: 10,
        totalPages: 1,
      }

      const mockController = {
        list: jest.fn().mockResolvedValue(mockData),
      }
      ;(root.get as jest.Mock).mockReturnValue(mockController)

      const { result } = renderHook(() => useCategoryTemplates('category-1'))

      await act(async () => {
        await result.current.execute({ page: 2, limit: 10 })
      })

      expect(mockController.list).toHaveBeenCalledWith(
        expect.objectContaining({
          categoryId: 'category-1',
          page: 2,
          limit: 10,
          ownerId: OWNER_ID,
        })
      )
    })

    it('should use initial params', async () => {
      const mockData = {
        templates: [],
        total: 0,
        page: 1,
        limit: 50,
        totalPages: 1,
      }

      const mockController = {
        list: jest.fn().mockResolvedValue(mockData),
      }
      ;(root.get as jest.Mock).mockReturnValue(mockController)

      const { result } = renderHook(() => useCategoryTemplates('category-1', { limit: 50 }))

      await act(async () => {
        await result.current.execute()
      })

      expect(mockController.list).toHaveBeenCalledWith(
        expect.objectContaining({
          categoryId: 'category-1',
          limit: 50,
          page: 1,
          ownerId: OWNER_ID,
        })
      )
    })
  })

  describe('pagination - loadMore', () => {
    it('should load more templates and append to existing data', async () => {
      const page1Data = {
        templates: [
          { id: '1', title: 'Template 1', titleEn: 'Template 1 EN', previewUrl: 'url1', coverImageUrl: 'cover1', aspectRatio: '16:9' },
          { id: '2', title: 'Template 2', titleEn: 'Template 2 EN', previewUrl: 'url2', coverImageUrl: 'cover2', aspectRatio: '16:9' },
        ],
        total: 4,
        page: 1,
        limit: 2,
        totalPages: 2,
      }

      const page2Data = {
        templates: [
          { id: '3', title: 'Template 3', titleEn: 'Template 3 EN', previewUrl: 'url3', coverImageUrl: 'cover3', aspectRatio: '16:9' },
          { id: '4', title: 'Template 4', titleEn: 'Template 4 EN', previewUrl: 'url4', coverImageUrl: 'cover4', aspectRatio: '16:9' },
        ],
        total: 4,
        page: 2,
        limit: 2,
        totalPages: 2,
      }

      const mockController = {
        list: jest.fn()
          .mockResolvedValueOnce(page1Data)
          .mockResolvedValueOnce(page2Data),
      }
      ;(root.get as jest.Mock).mockReturnValue(mockController)

      const { result } = renderHook(() => useCategoryTemplates('category-1', { limit: 2 }))

      await act(async () => {
        await result.current.execute()
      })

      expect(result.current.templates).toHaveLength(2)
      expect(result.current.hasMore).toBe(true)

      await act(async () => {
        await result.current.loadMore()
      })

      expect(result.current.templates).toHaveLength(4)
      expect(result.current.templates).toEqual([
        ...page1Data.templates,
        ...page2Data.templates,
      ])
      expect(result.current.hasMore).toBe(false)
    })

    it('should not load more if already loading', async () => {
      let resolveFetch: (value: any) => void
      const fetchPromise = new Promise((resolve) => {
        resolveFetch = resolve
      })

      const mockController = {
        list: jest.fn().mockReturnValue(fetchPromise),
      }
      ;(root.get as jest.Mock).mockReturnValue(mockController)

      const { result } = renderHook(() => useCategoryTemplates('category-1'))

      act(() => {
        result.current.execute()
      })

      act(() => {
        result.current.loadMore()
      })

      await act(async () => {
        resolveFetch!({ templates: [], total: 0, page: 1, limit: 20, totalPages: 1 })
        await fetchPromise
      })

      expect(mockController.list).toHaveBeenCalledTimes(1)
    })

    it('should not load more if no more data', async () => {
      const mockData = {
        templates: [{ id: '1', title: 'Template 1', titleEn: 'Template 1 EN', previewUrl: 'url1', coverImageUrl: 'cover1', aspectRatio: '16:9' }],
        total: 1,
        page: 1,
        limit: 20,
        totalPages: 1,
      }

      const mockController = {
        list: jest.fn().mockResolvedValue(mockData),
      }
      ;(root.get as jest.Mock).mockReturnValue(mockController)

      const { result } = renderHook(() => useCategoryTemplates('category-1'))

      await act(async () => {
        await result.current.execute()
      })

      expect(result.current.hasMore).toBe(false)

      await act(async () => {
        await result.current.loadMore()
      })

      expect(mockController.list).toHaveBeenCalledTimes(1)
    })

    it('should set loadingMore state correctly', async () => {
      const page1Data = {
        templates: [{ id: '1', title: 'Template 1', titleEn: 'Template 1 EN', previewUrl: 'url1', coverImageUrl: 'cover1', aspectRatio: '16:9' }],
        total: 2,
        page: 1,
        limit: 1,
        totalPages: 2,
      }

      let resolveLoadMore: (value: any) => void
      const loadMorePromise = new Promise((resolve) => {
        resolveLoadMore = resolve
      })

      const mockController = {
        list: jest.fn()
          .mockResolvedValueOnce(page1Data)
          .mockReturnValueOnce(loadMorePromise),
      }
      ;(root.get as jest.Mock).mockReturnValue(mockController)

      const { result } = renderHook(() => useCategoryTemplates('category-1', { limit: 1 }))

      await act(async () => {
        await result.current.execute()
      })

      act(() => {
        result.current.loadMore()
      })

      expect(result.current.loadingMore).toBe(true)

      await act(async () => {
        resolveLoadMore!({ templates: [{ id: '2', title: 'Template 2', titleEn: 'Template 2 EN', previewUrl: 'url2', coverImageUrl: 'cover2', aspectRatio: '16:9' }], total: 2, page: 2, limit: 1, totalPages: 2 })
        await loadMorePromise
      })

      expect(result.current.loadingMore).toBe(false)
    })

    it('should pass categoryId when loading more', async () => {
      const page1Data = {
        templates: [{ id: '1', title: 'Template 1', titleEn: 'Template 1 EN', previewUrl: 'url1', coverImageUrl: 'cover1', aspectRatio: '16:9' }],
        total: 2,
        page: 1,
        limit: 1,
        totalPages: 2,
      }

      const page2Data = {
        templates: [{ id: '2', title: 'Template 2', titleEn: 'Template 2 EN', previewUrl: 'url2', coverImageUrl: 'cover2', aspectRatio: '16:9' }],
        total: 2,
        page: 2,
        limit: 1,
        totalPages: 2,
      }

      const mockController = {
        list: jest.fn()
          .mockResolvedValueOnce(page1Data)
          .mockResolvedValueOnce(page2Data),
      }
      ;(root.get as jest.Mock).mockReturnValue(mockController)

      const { result } = renderHook(() => useCategoryTemplates('category-1', { limit: 1 }))

      await act(async () => {
        await result.current.execute()
      })

      await act(async () => {
        await result.current.loadMore()
      })

      expect(mockController.list).toHaveBeenNthCalledWith(2,
        expect.objectContaining({
          categoryId: 'category-1',
          page: 2,
          ownerId: OWNER_ID,
        })
      )
    })
  })

  describe('refetch function', () => {
    it('should reset and reload data from page 1', async () => {
      const initialData = {
        templates: [{ id: '1', title: 'Template 1', titleEn: 'Template 1 EN', previewUrl: 'url1', coverImageUrl: 'cover1', aspectRatio: '16:9' }],
        total: 1,
        page: 1,
        limit: 20,
        totalPages: 1,
      }

      const refreshedData = {
        templates: [
          { id: '1', title: 'Template 1', titleEn: 'Template 1 EN', previewUrl: 'url1', coverImageUrl: 'cover1', aspectRatio: '16:9' },
          { id: '2', title: 'Template 2', titleEn: 'Template 2 EN', previewUrl: 'url2', coverImageUrl: 'cover2', aspectRatio: '16:9' },
        ],
        total: 2,
        page: 1,
        limit: 20,
        totalPages: 1,
      }

      const mockController = {
        list: jest.fn()
          .mockResolvedValueOnce(initialData)
          .mockResolvedValueOnce(refreshedData),
      }
      ;(root.get as jest.Mock).mockReturnValue(mockController)

      const { result } = renderHook(() => useCategoryTemplates('category-1'))

      await act(async () => {
        await result.current.execute()
      })

      expect(result.current.templates).toHaveLength(1)

      await act(async () => {
        await result.current.refetch()
      })

      expect(result.current.templates).toHaveLength(2)
      expect(mockController.list).toHaveBeenCalledTimes(2)
    })

    it('should reset hasMore flag', async () => {
      const mockData = {
        templates: [{ id: '1', title: 'Template 1', titleEn: 'Template 1 EN', previewUrl: 'url1', coverImageUrl: 'cover1', aspectRatio: '16:9' }],
        total: 1,
        page: 1,
        limit: 20,
        totalPages: 1,
      }

      const mockController = {
        list: jest.fn().mockResolvedValue(mockData),
      }
      ;(root.get as jest.Mock).mockReturnValue(mockController)

      const { result } = renderHook(() => useCategoryTemplates('category-1'))

      await act(async () => {
        await result.current.execute()
      })

      expect(result.current.hasMore).toBe(false)

      await act(async () => {
        await result.current.refetch()
      })

      expect(result.current.hasMore).toBe(false)
    })

    it('should pass categoryId when refetching', async () => {
      const mockData = {
        templates: [{ id: '1', title: 'Template 1', titleEn: 'Template 1 EN', previewUrl: 'url1', coverImageUrl: 'cover1', aspectRatio: '16:9' }],
        total: 1,
        page: 1,
        limit: 20,
        totalPages: 1,
      }

      const mockController = {
        list: jest.fn().mockResolvedValue(mockData),
      }
      ;(root.get as jest.Mock).mockReturnValue(mockController)

      const { result } = renderHook(() => useCategoryTemplates('category-1'))

      await act(async () => {
        await result.current.refetch()
      })

      expect(mockController.list).toHaveBeenCalledWith(
        expect.objectContaining({
          categoryId: 'category-1',
          page: 1,
          ownerId: OWNER_ID,
        })
      )
    })
  })

  describe('hasMore flag', () => {
    it('should set hasMore to true when more pages exist', async () => {
      const mockData = {
        templates: [{ id: '1', title: 'Template 1', titleEn: 'Template 1 EN', previewUrl: 'url1', coverImageUrl: 'cover1', aspectRatio: '16:9' }],
        total: 40,
        page: 1,
        limit: 20,
        totalPages: 2,
      }

      const mockController = {
        list: jest.fn().mockResolvedValue(mockData),
      }
      ;(root.get as jest.Mock).mockReturnValue(mockController)

      const { result } = renderHook(() => useCategoryTemplates('category-1'))

      await act(async () => {
        await result.current.execute()
      })

      expect(result.current.hasMore).toBe(true)
    })

    it('should set hasMore to false on last page', async () => {
      const mockData = {
        templates: [{ id: '1', title: 'Template 1', titleEn: 'Template 1 EN', previewUrl: 'url1', coverImageUrl: 'cover1', aspectRatio: '16:9' }],
        total: 20,
        page: 1,
        limit: 20,
        totalPages: 1,
      }

      const mockController = {
        list: jest.fn().mockResolvedValue(mockData),
      }
      ;(root.get as jest.Mock).mockReturnValue(mockController)

      const { result } = renderHook(() => useCategoryTemplates('category-1'))

      await act(async () => {
        await result.current.execute()
      })

      expect(result.current.hasMore).toBe(false)
    })
  })

  describe('error handling', () => {
    it('should clear error on successful execute', async () => {
      const mockError = { status: 500, message: 'Error' }
      const mockData = {
        templates: [{ id: '1', title: 'Template 1', titleEn: 'Template 1 EN', previewUrl: 'url1', coverImageUrl: 'cover1', aspectRatio: '16:9' }],
        total: 1,
        page: 1,
        limit: 20,
        totalPages: 1,
      }

      const mockController = {
        list: jest.fn()
          .mockRejectedValueOnce(mockError)
          .mockResolvedValueOnce(mockData),
      }
      ;(root.get as jest.Mock).mockReturnValue(mockController)

      const { result } = renderHook(() => useCategoryTemplates('category-1'))

      await act(async () => {
        await result.current.execute()
      })

      expect(result.current.error).toEqual(mockError)

      await act(async () => {
        await result.current.execute()
      })

      expect(result.current.error).toBeNull()
    })

    it('should handle loadMore errors without affecting existing data', async () => {
      const page1Data = {
        templates: [{ id: '1', title: 'Template 1', titleEn: 'Template 1 EN', previewUrl: 'url1', coverImageUrl: 'cover1', aspectRatio: '16:9' }],
        total: 2,
        page: 1,
        limit: 1,
        totalPages: 2,
      }

      const mockError = { status: 500, message: 'Error loading more' }

      const mockController = {
        list: jest.fn()
          .mockResolvedValueOnce(page1Data)
          .mockRejectedValueOnce(mockError),
      }
      ;(root.get as jest.Mock).mockReturnValue(mockController)

      const { result } = renderHook(() => useCategoryTemplates('category-1', { limit: 1 }))

      await act(async () => {
        await result.current.execute()
      })

      expect(result.current.templates).toHaveLength(1)

      await act(async () => {
        await result.current.loadMore()
      })

      expect(result.current.templates).toHaveLength(1)
      expect(result.current.loadingMore).toBe(false)
    })
  })

  describe('categoryId change', () => {
    it('should reload data when categoryId changes', async () => {
      const category1Data = {
        templates: [{ id: '1', title: 'Category 1 Template', titleEn: 'Category 1 Template EN', previewUrl: 'url1', coverImageUrl: 'cover1', aspectRatio: '16:9' }],
        total: 1,
        page: 1,
        limit: 20,
        totalPages: 1,
      }

      const category2Data = {
        templates: [{ id: '2', title: 'Category 2 Template', titleEn: 'Category 2 Template EN', previewUrl: 'url2', coverImageUrl: 'cover2', aspectRatio: '16:9' }],
        total: 1,
        page: 1,
        limit: 20,
        totalPages: 1,
      }

      const mockController = {
        list: jest.fn()
          .mockResolvedValueOnce(category1Data)
          .mockResolvedValueOnce(category2Data),
      }
      ;(root.get as jest.Mock).mockReturnValue(mockController)

      const { result, rerender } = renderHook(
        ({ categoryId }) => useCategoryTemplates(categoryId),
        { initialProps: { categoryId: 'category-1' } }
      )

      await act(async () => {
        await result.current.execute()
      })

      expect(result.current.templates).toEqual(category1Data.templates)
      expect(mockController.list).toHaveBeenCalledWith(
        expect.objectContaining({
          categoryId: 'category-1',
        })
      )

      rerender({ categoryId: 'category-2' })

      await act(async () => {
        await result.current.execute()
      })

      expect(result.current.templates).toEqual(category2Data.templates)
      expect(mockController.list).toHaveBeenCalledWith(
        expect.objectContaining({
          categoryId: 'category-2',
        })
      )
    })

    it('should reset pagination state when categoryId changes and refetch is called', async () => {
      const page1Category1 = {
        templates: [{ id: '1', title: 'Template 1', titleEn: 'Template 1 EN', previewUrl: 'url1', coverImageUrl: 'cover1', aspectRatio: '16:9' }],
        total: 2,
        page: 1,
        limit: 1,
        totalPages: 2,
      }

      const page2Category1 = {
        templates: [{ id: '2', title: 'Template 2', titleEn: 'Template 2 EN', previewUrl: 'url2', coverImageUrl: 'cover2', aspectRatio: '16:9' }],
        total: 2,
        page: 2,
        limit: 1,
        totalPages: 2,
      }

      const page1Category2 = {
        templates: [{ id: '3', title: 'Template 3', titleEn: 'Template 3 EN', previewUrl: 'url3', coverImageUrl: 'cover3', aspectRatio: '16:9' }],
        total: 1,
        page: 1,
        limit: 1,
        totalPages: 1,
      }

      const mockController = {
        list: jest.fn()
          .mockResolvedValueOnce(page1Category1)
          .mockResolvedValueOnce(page2Category1)
          .mockResolvedValueOnce(page1Category2),
      }
      ;(root.get as jest.Mock).mockReturnValue(mockController)

      const { result, rerender } = renderHook(
        ({ categoryId }) => useCategoryTemplates(categoryId, { limit: 1 }),
        { initialProps: { categoryId: 'category-1' } }
      )

      await act(async () => {
        await result.current.execute()
      })

      await act(async () => {
        await result.current.loadMore()
      })

      expect(result.current.templates).toHaveLength(2)

      rerender({ categoryId: 'category-2' })

      await act(async () => {
        await result.current.refetch()
      })

      expect(result.current.templates).toEqual(page1Category2.templates)
      expect(mockController.list).toHaveBeenLastCalledWith(
        expect.objectContaining({
          categoryId: 'category-2',
          page: 1,
        })
      )
    })
  })
})