import { test, expect } from '@playwright/test'

test.describe('Workouts List Page', () => {
  test.beforeEach(async ({ page }) => {
    await page.goto('/workouts')
  })

  test('should display workouts page header', async ({ page }) => {
    // May redirect to login if not authenticated
    const heading = page.getByRole('heading', { name: /workouts|tabatafit admin/i })
    await expect(heading).toBeVisible()
  })

  test('should have Add Workout button', async ({ page }) => {
    // If authenticated, should see the Add Workout button
    const addButton = page.getByRole('link', { name: /add workout/i })
    
    // Page might redirect to login — check if we're on workouts page
    const url = page.url()
    if (url.includes('/workouts')) {
      await expect(addButton).toBeVisible()
    }
  })

  test('should display workouts table with correct columns', async ({ page }) => {
    const url = page.url()
    if (!url.includes('/workouts')) return

    // Wait for loading to finish (loader disappears)
    await page.waitForSelector('[class*="animate-spin"]', { state: 'detached', timeout: 10000 }).catch(() => {})

    const table = page.locator('table')
    // Table may or may not be visible depending on data
    const tableVisible = await table.isVisible().catch(() => false)
    
    if (tableVisible) {
      await expect(page.getByRole('columnheader', { name: /title/i })).toBeVisible()
      await expect(page.getByRole('columnheader', { name: /category/i })).toBeVisible()
      await expect(page.getByRole('columnheader', { name: /level/i })).toBeVisible()
      await expect(page.getByRole('columnheader', { name: /duration/i })).toBeVisible()
      await expect(page.getByRole('columnheader', { name: /rounds/i })).toBeVisible()
      await expect(page.getByRole('columnheader', { name: /actions/i })).toBeVisible()
    }
  })

  test('should navigate to new workout page', async ({ page }) => {
    const url = page.url()
    if (!url.includes('/workouts')) return

    const addButton = page.getByRole('link', { name: /add workout/i })
    if (await addButton.isVisible().catch(() => false)) {
      await addButton.click()
      await expect(page).toHaveURL(/.*workouts\/new/)
    }
  })
})

test.describe('New Workout Page', () => {
  test.beforeEach(async ({ page }) => {
    await page.goto('/workouts/new')
  })

  test('should display create workout heading', async ({ page }) => {
    const url = page.url()
    if (!url.includes('/workouts/new')) return

    await expect(page.getByRole('heading', { name: /create new workout/i })).toBeVisible()
  })

  test('should have back to workouts link', async ({ page }) => {
    const url = page.url()
    if (!url.includes('/workouts/new')) return

    const backLink = page.getByRole('link', { name: /back to workouts/i })
    await expect(backLink).toBeVisible()
  })

  test('should display workout form with tabs', async ({ page }) => {
    const url = page.url()
    if (!url.includes('/workouts/new')) return

    // Form should have 4 tabs: Basics, Timing, Content, Media
    await expect(page.getByRole('tab', { name: /basics/i })).toBeVisible()
    await expect(page.getByRole('tab', { name: /timing/i })).toBeVisible()
    await expect(page.getByRole('tab', { name: /content/i })).toBeVisible()
    await expect(page.getByRole('tab', { name: /media/i })).toBeVisible()
  })

  test('should show basics tab fields by default', async ({ page }) => {
    const url = page.url()
    if (!url.includes('/workouts/new')) return

    // Basics tab should be active by default
    await expect(page.getByLabel(/workout title/i)).toBeVisible()
  })

  test('should switch between form tabs', async ({ page }) => {
    const url = page.url()
    if (!url.includes('/workouts/new')) return

    // Click Timing tab
    await page.getByRole('tab', { name: /timing/i }).click()
    await expect(page.getByLabel(/total rounds/i)).toBeVisible()

    // Click Content tab
    await page.getByRole('tab', { name: /content/i }).click()
    await expect(page.getByText(/exercises/i).first()).toBeVisible()

    // Click Media tab
    await page.getByRole('tab', { name: /media/i }).click()
    await expect(page.getByText(/music vibe/i).first()).toBeVisible()
  })

  test('should have Cancel and Create Workout buttons', async ({ page }) => {
    const url = page.url()
    if (!url.includes('/workouts/new')) return

    await expect(page.getByRole('button', { name: /cancel/i })).toBeVisible()
    await expect(page.getByRole('button', { name: /create workout/i })).toBeVisible()
  })

  test('should show validation errors on empty submit', async ({ page }) => {
    const url = page.url()
    if (!url.includes('/workouts/new')) return

    // Clear the title field and submit
    const titleInput = page.getByLabel(/workout title/i)
    await titleInput.fill('')

    // Click submit
    await page.getByRole('button', { name: /create workout/i }).click()

    // Should show validation error for title
    await expect(page.getByText(/title is required/i)).toBeVisible()
  })

  test('should navigate back when Cancel is clicked', async ({ page }) => {
    const url = page.url()
    if (!url.includes('/workouts/new')) return

    await page.getByRole('button', { name: /cancel/i }).click()
    await expect(page).toHaveURL(/.*workouts$/)
  })
})

test.describe('Workout Detail Page', () => {
  test('should show 404 or redirect for non-existent workout', async ({ page }) => {
    await page.goto('/workouts/non-existent-id')
    
    // Should either show not found or redirect
    const url = page.url()
    const hasNotFound = await page.getByText(/not found/i).isVisible().catch(() => false)
    const redirectedToLogin = url.includes('/login')
    const redirectedToWorkouts = url.match(/\/workouts\/?$/)
    
    expect(hasNotFound || redirectedToLogin || redirectedToWorkouts).toBeTruthy()
  })
})

test.describe('Workout Delete Dialog', () => {
  test.beforeEach(async ({ page }) => {
    await page.goto('/workouts')
  })

  test('should open delete confirmation dialog', async ({ page }) => {
    const url = page.url()
    if (!url.includes('/workouts')) return

    // Wait for loading to finish
    await page.waitForSelector('[class*="animate-spin"]', { state: 'detached', timeout: 10000 }).catch(() => {})

    // Find a delete button in the table actions
    const deleteButtons = page.locator('button').filter({ has: page.locator('svg.lucide-trash-2') })
    const count = await deleteButtons.count()

    if (count > 0) {
      await deleteButtons.first().click()

      // Dialog should appear
      await expect(page.getByRole('heading', { name: /delete workout/i })).toBeVisible()
      await expect(page.getByText(/are you sure/i)).toBeVisible()
      await expect(page.getByRole('button', { name: /cancel/i })).toBeVisible()
      await expect(page.getByRole('button', { name: /^delete$/i })).toBeVisible()
    }
  })

  test('should close delete dialog on Cancel', async ({ page }) => {
    const url = page.url()
    if (!url.includes('/workouts')) return

    await page.waitForSelector('[class*="animate-spin"]', { state: 'detached', timeout: 10000 }).catch(() => {})

    const deleteButtons = page.locator('button').filter({ has: page.locator('svg.lucide-trash-2') })
    const count = await deleteButtons.count()

    if (count > 0) {
      await deleteButtons.first().click()
      await expect(page.getByRole('heading', { name: /delete workout/i })).toBeVisible()

      // Click cancel
      await page.getByRole('button', { name: /cancel/i }).click()

      // Dialog should close
      await expect(page.getByRole('heading', { name: /delete workout/i })).not.toBeVisible()
    }
  })
})
