<script lang="ts">
  import type { TeamCapacity, Revenue } from '$lib/types/capacity';
  import type { TeamMember } from '$lib/services/teamMemberService';

  export let teamCapacity: TeamCapacity | null = null;
  export let revenue: Revenue | null = null;
  export let teamMembers: TeamMember[] = [];

  type MemberRow = TeamCapacity['member_capacities'][number] & {
    role_label: string;
    hourly_rate_label: string;
    hourly_rate: number;
  };

  type RoleRow = {
    role: string;
    person_days: number;
    hours: number;
    hourly_rate: number;
  };

  const currencyFormatter = new Intl.NumberFormat('en-US', {
    style: 'currency',
    currency: 'USD'
  });

  function toNumber(value: unknown): number {
    const parsed = Number(value);
    return Number.isFinite(parsed) ? parsed : 0;
  }

  function formatCurrency(value: unknown): string {
    return currencyFormatter.format(toNumber(value));
  }

  $: memberMap = new Map(teamMembers.map((member) => [member.id, member]));
  $: memberRows = (teamCapacity?.member_capacities ?? []).map((member): MemberRow => {
    const details = memberMap.get(member.team_member_id);
    const hourlyRate = details ? Number(details.hourly_rate) : member.hourly_rate;
    const roleName = details?.role?.name ?? member.role;

    return {
      ...member,
      role_label: roleName ?? 'Unknown',
      hourly_rate_label: formatCurrency(hourlyRate),
      hourly_rate: hourlyRate
    };
  });

  $: roleRows = memberRows.reduce<Record<string, RoleRow>>((acc, member) => {
    const roleKey = member.role_label || 'Unknown';

    if (!acc[roleKey]) {
      acc[roleKey] = {
        role: roleKey,
        person_days: 0,
        hours: 0,
        hourly_rate: member.hourly_rate ?? 0
      };
    }

    acc[roleKey].person_days += member.person_days;
    acc[roleKey].hours += member.hours;
    return acc;
  }, {});
</script>

<section class="space-y-6" data-testid="capacity-summary">
  <div class="grid gap-4 md:grid-cols-2">
    <div class="rounded-2xl border border-base-300 bg-base-100 p-4 shadow-sm" data-testid="team-capacity-card">
      <p class="text-xs uppercase tracking-wider text-base-content/50">Team capacity</p>
      <p class="text-3xl font-semibold">
        {toNumber(teamCapacity?.total_person_days).toFixed(1)}d
      </p>
      <p class="text-sm text-base-content/60">{toNumber(teamCapacity?.total_hours)} hrs</p>
    </div>
    <div class="rounded-2xl border border-base-300 bg-base-100 p-4 shadow-sm" data-testid="possible-revenue-card">
      <p class="text-xs uppercase tracking-wider text-base-content/50">Possible revenue</p>
      <p class="text-3xl font-semibold">{formatCurrency(revenue?.total_revenue ?? 0)}</p>
      <p class="text-sm text-base-content/60">Based on current monthly capacity</p>
    </div>
  </div>

  <div class="space-y-4">
    <div class="flex items-center justify-between">
      <h3 class="text-lg font-semibold">Member capacities</h3>
      <span class="text-xs text-base-content/60">{memberRows.length} members</span>
    </div>

    {#if memberRows.length === 0}
      <p class="text-sm text-base-content/60">No capacity data yet.</p>
    {:else}
      <div class="grid gap-3 md:grid-cols-2">
        {#each memberRows as member}
          <div class="rounded-2xl border border-base-200 bg-base-100 p-4 shadow-sm">
            <div class="flex items-start justify-between">
              <div>
                <p class="text-base font-semibold">{member.team_member_name}</p>
                <p class="text-xs text-base-content/60">{member.role_label}</p>
              </div>
            </div>
            <div class="mt-3 flex items-center justify-between">
              <p class="text-sm text-base-content/70">Person days</p>
              <p class="text-base font-semibold">{member.person_days.toFixed(2)}d</p>
            </div>
            <div class="mt-2 flex items-center justify-between">
              <p class="text-sm text-base-content/70">Hours</p>
              <p class="text-base font-semibold">{member.hours}h</p>
            </div>
            <div class="mt-2 flex items-center justify-between">
              <p class="text-sm text-base-content/70">Hourly rate</p>
              <p class="text-base font-semibold">{member.hourly_rate_label}</p>
            </div>
          </div>
        {/each}
      </div>
    {/if}
  </div>

  <div class="space-y-3">
    <h3 class="text-lg font-semibold">Capacity by role</h3>
    {#if Object.keys(roleRows).length === 0}
      <p class="text-sm text-base-content/60">No role breakdown available yet.</p>
    {:else}
      <div class="space-y-2">
        {#each Object.values(roleRows) as role}
          <div class="flex items-center justify-between rounded-2xl border border-base-200 bg-base-100 px-4 py-3">
            <div>
              <p class="font-semibold">{role.role}</p>
              <p class="text-xs text-base-content/60">Hourly rate {formatCurrency(role.hourly_rate)}</p>
            </div>
            <div class="text-right">
              <p class="text-sm font-semibold">{role.person_days.toFixed(1)}d</p>
              <p class="text-xs text-base-content/50">{role.hours} hrs</p>
            </div>
          </div>
        {/each}
      </div>
    {/if}
  </div>
</section>
