<script lang="ts">
  let canvasElement: HTMLCanvasElement;
  let errorMessage = $state("");
  let photoObjectUrl = $state("");

  function handleFileChange(event: Event) {
    const file = (event.target as HTMLInputElement).files?.[0];

    if (!file) {
      errorMessage = `No file selected, try again`;
      return;
    }

    const ctx = canvasElement.getContext("2d");

    if (!ctx) {
      errorMessage = `Could not get 2d context from canvas`;
      return;
    }

    ctx.clearRect(0, 0, canvasElement.width, canvasElement.height);

    photoObjectUrl = URL.createObjectURL(file);
    const image = new Image();
    image.src = photoObjectUrl;
    image.onload = () => {
      const orientation = image.width > image.height ? "landscape" : "portrait";

      if (orientation === "landscape") {
        ctx.drawImage(image, 0, 0, canvasElement.width, canvasElement.height);
      } else {
        ctx.drawImage(image, 0, 0, canvasElement.height, canvasElement.width);
      }
    };
  }
</script>

{#if errorMessage}
  <div class="error-message">
    {errorMessage}
  </div>
{/if}
<form
  method="POST"
  action="/admin/photos"
  enctype="multipart/form-data"
  class="cms-form"
>
  <canvas bind:this={canvasElement}></canvas>

  <div class="field">
    <label for="title">Title</label>
    <input type="text" name="title" id="title" required />
  </div>

  <div class="field">
    <input
      onchange={handleFileChange}
      type="file"
      name="file"
      accept="image/*"
      required
    />
  </div>

  <div class="field">
    <label for="description">Description</label>
    <textarea name="description" id="description"></textarea>
  </div>

  <button type="submit">Upload</button>
</form>
