<script lang="ts">
  import { parse, format } from "date-fns";

  const initialDate = format(new Date(), 'dd/MM/yyyy');
  let flightType = $state("one-way");
  let outbound = $state(initialDate);
  let retflight = $state(initialDate);

  function isValidDate(d: Date) {
    return !Number.isNaN(d.getDate());
  }

  let outboundDate = $derived(parse(outbound, 'dd/MM/yyyy', new Date()));
  let retflightDate = $derived(parse(retflight, 'dd/MM/yyyy', new Date()));
  let outboundValid = $derived(isValidDate(outboundDate));
  let retflightValid = $derived(isValidDate(retflightDate));

  function isBookDisabled() {
    const valid = outboundValid && (flightType === "return" ? retflightValid && retflightDate > outboundDate : true);
    return !valid;
  }

  function onClickBook() {
    switch (flightType) {
      case "one-way":
        alert(`You have booked a one-way flight on ${outbound}.`);
        break;
      case "return":
        alert(`You have booked a return flight on ${outbound} and ${retflight}.`);
        break;
      default:
        alert("Unknown Status");
    }
  }
</script>

<div class="flex flex-col items-center gap-4 w-80 mx-auto">
  <select class="select" bind:value={flightType}>
    <option value="one-way">One-way flight</option>
    <option value="return">Return flight</option>
  </select>
  <label class={["input w-full", !outboundValid && "input-error"]}>
    <span class="label">Outbound Flight</span>
    <input type="text" placeholder="27/03/2025" bind:value={outbound}/>
  </label>
  <label class={["input w-full", flightType === 'return' && !retflightValid && "input-error"]}>
    <span class="label">Return Flight</span>
    <input type="text" placeholder="31/03/2025" bind:value={retflight} disabled={flightType !== 'return'}/>
  </label>
  <button class="btn btn-primary w-full" disabled={isBookDisabled()} onclick={onClickBook}>Book</button>
</div>