import { test, expect, type Page } from '@playwright/test';

async function login(page: Page) {
  await page.goto('/login');
  await page.fill('input[type="email"]', 'superuser@headroom.test');
  await page.fill('input[type="password"]', 'password');
  await page.click('button[type="submit"]');
  await page.waitForURL('/dashboard');
}

async function getAccessToken(page: Page): Promise<string> {
  return (await page.evaluate(() => localStorage.getItem('headroom_access_token'))) as string;
}

async function setPeriod(page: Page, period = '2026-03') {
  await page.evaluate((value) => {
    localStorage.setItem('headroom_selected_period', value);
  }, period);
}

// Backend API base URL
const API_BASE = 'http://localhost:3000';

async function createTeamMember(page: Page, token: string, overrides: Record<string, unknown> = {}) {
  const payload = {
    name: `Utilization Tester ${Date.now()}`,
    role_id: 1,
    hourly_rate: 150,
    active: true,
    ...overrides
  };

  const response = await page.request.post(`${API_BASE}/api/team-members`, {
    headers: {
      Authorization: `Bearer ${token}`,
      'Content-Type': 'application/json'
    },
    data: payload
  });

  return response.json();
}

async function createProject(page: Page, token: string, overrides: Record<string, unknown> = {}) {
  const payload = {
    code: `UTIL-${Date.now()}`,
    title: `Utilization Test Project ${Date.now()}`,
    type: 'Time & Material',
    status: 'Active',
    ...overrides
  };

  const response = await page.request.post(`${API_BASE}/api/projects`, {
    headers: {
      Authorization: `Bearer ${token}`,
      'Content-Type': 'application/json'
    },
    data: payload
  });

  return response.json();
}

async function createAllocation(
  page: Page,
  token: string,
  teamMemberId: string,
  projectId: string,
  month: string,
  allocatedHours: number
) {
  const response = await page.request.post(`${API_BASE}/api/allocations`, {
    headers: {
      Authorization: `Bearer ${token}`,
      'Content-Type': 'application/json'
    },
    data: {
      team_member_id: teamMemberId,
      project_id: projectId,
      month,
      allocated_hours: allocatedHours
    }
  });

  return response.json();
}

test.describe('Utilization Calculations', () => {
  test.fixme('7.1.1: Calculate running utilization YTD', async ({ page }) => {
    // Setup: Create team member with allocations for Jan, Feb, Mar
    await login(page);
    const token = await getAccessToken(page);
    await setPeriod(page, '2026-03');

    const member = await createTeamMember(page, token);
    const project = await createProject(page, token);

    // Create allocations: Jan 140h, Feb 150h, Mar 160h
    await createAllocation(page, token, member.data.id, project.data.id, '2026-01-01', 140);
    await createAllocation(page, token, member.data.id, project.data.id, '2026-02-01', 150);
    await createAllocation(page, token, member.data.id, project.data.id, '2026-03-01', 160);

    // Navigate to allocation page
    await page.goto('/allocations');

    // Verify YTD utilization is displayed and correct
    // Expected: (140 + 150 + 160) / (capacity Jan + Feb + Mar) * 100
    const utilizationBadge = page.locator(`[data-testid="utilization-ytd-${member.data.id}"]`);
    await expect(utilizationBadge).toBeVisible();
    await expect(utilizationBadge).toContainText(/9[0-9]\.[0-9]%/);
  });

  test.fixme('7.1.2: Running utilization at start of year', async ({ page }) => {
    await login(page);
    const token = await getAccessToken(page);
    await setPeriod(page, '2026-01');

    const member = await createTeamMember(page, token);
    const project = await createProject(page, token);

    // Only January allocation: 120h
    await createAllocation(page, token, member.data.id, project.data.id, '2026-01-01', 120);

    await page.goto('/allocations');

    // YTD should be same as monthly in January
    const utilizationBadge = page.locator(`[data-testid="utilization-ytd-${member.data.id}"]`);
    await expect(utilizationBadge).toBeVisible();
    // January 2026: ~21 working days = ~176 hours
    // 120 / 176 = ~68%
    await expect(utilizationBadge).toContainText(/6[0-9]\.[0-9]%/);
  });

  test.fixme('7.1.3: Calculate overall utilization monthly', async ({ page }) => {
    await login(page);
    const token = await getAccessToken(page);
    await setPeriod(page, '2026-02');

    const member = await createTeamMember(page, token);
    const project = await createProject(page, token);

    // February allocation: 140h (out of ~160h capacity)
    await createAllocation(page, token, member.data.id, project.data.id, '2026-02-01', 140);

    await page.goto('/allocations');

    // Monthly utilization: 140 / 160 * 100 = 87.5%
    const utilizationBadge = page.locator(`[data-testid="utilization-monthly-${member.data.id}"]`);
    await expect(utilizationBadge).toBeVisible();
    await expect(utilizationBadge).toContainText('87.5%');
  });

  test.fixme('7.1.4: Full utilization 100%', async ({ page }) => {
    await login(page);
    const token = await getAccessToken(page);
    await setPeriod(page, '2026-02');

    const member = await createTeamMember(page, token);
    const project = await createProject(page, token);

    // Full allocation: 160h
    await createAllocation(page, token, member.data.id, project.data.id, '2026-02-01', 160);

    await page.goto('/allocations');

    const utilizationBadge = page.locator(`[data-testid="utilization-monthly-${member.data.id}"]`);
    await expect(utilizationBadge).toBeVisible();
    await expect(utilizationBadge).toContainText('100%');
  });

  test.fixme('7.1.5: Over-utilization >100%', async ({ page }) => {
    await login(page);
    const token = await getAccessToken(page);
    await setPeriod(page, '2026-02');

    const member = await createTeamMember(page, token);
    const project = await createProject(page, token);

    // Over-allocation: 180h
    await createAllocation(page, token, member.data.id, project.data.id, '2026-02-01', 180);

    await page.goto('/allocations');

    // Over-utilization: 180 / 160 * 100 = 112.5%
    const utilizationBadge = page.locator(`[data-testid="utilization-monthly-${member.data.id}"]`);
    await expect(utilizationBadge).toBeVisible();
    await expect(utilizationBadge).toContainText('112.5%');
  });

  test.fixme('7.1.6: Display utilization alongside capacity', async ({ page }) => {
    await login(page);
    const token = await getAccessToken(page);
    await setPeriod(page, '2026-02');

    const member = await createTeamMember(page, token);
    const project = await createProject(page, token);

    await createAllocation(page, token, member.data.id, project.data.id, '2026-02-01', 140);

    await page.goto('/allocations');

    // Both capacity and utilization should be visible
    const capacityCell = page.locator(`[data-testid="capacity-${member.data.id}"]`);
    await expect(capacityCell).toBeVisible();
    await expect(capacityCell).toContainText('160h');

    const utilizationBadge = page.locator(`[data-testid="utilization-monthly-${member.data.id}"]`);
    await expect(utilizationBadge).toBeVisible();
  });

  test.fixme('7.1.7: Color-code utilization levels', async ({ page }) => {
    await login(page);
    const token = await getAccessToken(page);
    await setPeriod(page, '2026-02');

    // Create multiple members with different utilization levels
    const member1 = await createTeamMember(page, token, { name: 'Under-allocated' }); // <70%
    const member2 = await createTeamMember(page, token, { name: 'Optimal' }); // 80-100%
    const member3 = await createTeamMember(page, token, { name: 'Over-allocated' }); // >110%

    const project = await createProject(page, token);

    // Member 1: 50% utilization (80h / 160h)
    await createAllocation(page, token, member1.data.id, project.data.id, '2026-02-01', 80);
    // Member 2: 90% utilization (144h / 160h)
    await createAllocation(page, token, member2.data.id, project.data.id, '2026-02-01', 144);
    // Member 3: 120% utilization (192h / 160h)
    await createAllocation(page, token, member3.data.id, project.data.id, '2026-02-01', 192);

    await page.goto('/allocations');

    // Verify colors
    const badge1 = page.locator(`[data-testid="utilization-monthly-${member1.data.id}"]`);
    await expect(badge1).toHaveClass(/badge-neutral/); // gray for under-utilized

    const badge2 = page.locator(`[data-testid="utilization-monthly-${member2.data.id}"]`);
    await expect(badge2).toHaveClass(/badge-success/); // green for optimal

    const badge3 = page.locator(`[data-testid="utilization-monthly-${member3.data.id}"]`);
    await expect(badge3).toHaveClass(/badge-error/); // red for over-allocated
  });

  test.fixme('7.1.8: Optimal utilization 80-100% green', async ({ page }) => {
    await login(page);
    const token = await getAccessToken(page);
    await setPeriod(page, '2026-02');

    const member = await createTeamMember(page, token);
    const project = await createProject(page, token);

    // 90% utilization
    await createAllocation(page, token, member.data.id, project.data.id, '2026-02-01', 144);

    await page.goto('/allocations');

    const utilizationBadge = page.locator(`[data-testid="utilization-monthly-${member.data.id}"]`);
    await expect(utilizationBadge).toBeVisible();
    await expect(utilizationBadge).toContainText('90%');
    await expect(utilizationBadge).toHaveClass(/badge-success/);
  });
});
