<script lang="ts">
  import { createPTO, deletePTO, getPTOs } from '$lib/api/capacity';
  import type { PTO } from '$lib/types/capacity';
  import type { TeamMember } from '$lib/services/teamMemberService';

  export let teamMembers: TeamMember[] = [];
  export let month: string;
  export let selectedMemberId = '';
  let submitting = false;
  let deletingId: string | null = null;
  let error: string | null = null;
  let ptos: PTO[] = [];
  let form = {
    team_member_id: '',
    start_date: '',
    end_date: '',
    reason: ''
  };

  $: if (!selectedMemberId && teamMembers.length) {
    selectedMemberId = teamMembers[0].id;
  }
  $: if (selectedMemberId && month) {
    refreshList(selectedMemberId);
  }

  async function refreshList(memberId: string) {
    try {
      ptos = await getPTOs({ team_member_id: memberId, month });
    } catch (err) {
      console.error('Failed to load PTOs', err);
      ptos = [];
    }
  }

  async function handleSubmit(event: Event) {
    event.preventDefault();
    if (!form.team_member_id || !form.start_date || !form.end_date) {
      return;
    }

    submitting = true;
    error = null;

    try {
      await createPTO(form);
      const targetMember = form.team_member_id;
      form = { team_member_id: form.team_member_id, start_date: '', end_date: '', reason: '' };
      if (month && targetMember) {
        await refreshList(targetMember);
      }
      selectedMemberId = targetMember;
    } catch (err) {
      console.error(err);
      error = 'Unable to submit PTO request.';
    } finally {
      submitting = false;
    }
  }

  async function handleDelete(pto: PTO) {
    deletingId = pto.id;
    error = null;

    try {
      await deletePTO(pto.id);

      if (selectedMemberId && month) {
        await refreshList(selectedMemberId);
      }
    } catch (err) {
      console.error(err);
      error = 'Unable to delete PTO.';
    } finally {
      deletingId = null;
    }
  }

  function getMemberName(pto: PTO): string {
    return teamMembers.find((member) => member.id === pto.team_member_id)?.name ?? pto.team_member_name ?? 'Team member';
  }
</script>

<section class="space-y-4" data-testid="pto-manager">
  <div class="flex items-center justify-between">
    <div>
      <p class="text-xs uppercase tracking-widest text-base-content/50">PTO requests</p>
      <h2 class="text-lg font-semibold">Team availability</h2>
    </div>
    <select
      class="select select-sm"
      bind:value={selectedMemberId}
      aria-label="Select team member for PTO"
    >
      {#each teamMembers as member}
        <option value={member.id}>{member.name}</option>
      {/each}
    </select>
  </div>

  {#if error}
    <div class="alert alert-error text-sm">{error}</div>
  {/if}

  <div class="space-y-2">
    {#if ptos.length === 0}
      <p class="text-sm text-base-content/60">No PTO requests for this team member.</p>
    {:else}
      {#each ptos as pto}
        <div class="rounded-2xl border border-base-200 bg-base-100 px-4 py-3">
          <div class="flex items-center justify-between">
            <div>
              <p class="font-semibold">{getMemberName(pto)}</p>
              <p class="text-xs text-base-content/60">
                {new Date(pto.start_date).toLocaleDateString('en-US')} -
                {new Date(pto.end_date).toLocaleDateString('en-US')}
              </p>
            </div>
            <span class="badge badge-outline badge-sm">{pto.status}</span>
          </div>
          {#if pto.reason}
            <p class="text-xs text-base-content/70 mt-1">{pto.reason}</p>
          {/if}
          <div class="mt-3 flex flex-wrap gap-2">
            <button
              class="btn btn-sm btn-ghost text-error"
              type="button"
              disabled={deletingId === pto.id}
              on:click={() => handleDelete(pto)}
            >
              Delete
            </button>
          </div>
        </div>
      {/each}
    {/if}
  </div>

  <form class="grid gap-3 border border-base-200 rounded-2xl bg-base-100 p-4 shadow-sm" on:submit|preventDefault={handleSubmit}>
    <div class="grid gap-3 md:grid-cols-2">
      <div class="form-control">
        <label class="label text-xs">Team member</label>
        <select class="select select-bordered" bind:value={form.team_member_id} required>
          <option value="" disabled>Select team member</option>
          {#each teamMembers as member}
            <option value={member.id}>{member.name}</option>
          {/each}
        </select>
      </div>
      <div class="form-control">
        <label class="label text-xs">Start date</label>
        <input type="date" class="input input-bordered" bind:value={form.start_date} required />
      </div>
    </div>
    <div class="grid gap-3 md:grid-cols-2">
      <div class="form-control">
        <label class="label text-xs">End date</label>
        <input type="date" class="input input-bordered" bind:value={form.end_date} required />
      </div>
      <div class="form-control">
        <label class="label text-xs">Reason</label>
        <input
          type="text"
          class="input input-bordered"
          placeholder="Optional reason"
          bind:value={form.reason}
        />
      </div>
    </div>
    <div class="text-right">
      <button class="btn btn-primary btn-sm" type="submit" disabled={submitting}>
        {#if submitting}
          <span class="loading loading-spinner loading-sm"></span>
        {/if}
        Submit PTO
      </button>
    </div>
  </form>
</section>
