<script lang="ts">
  import type { PhotoPost } from "../../../../../generated/prisma/client.js";

  interface Props {
    photo: PhotoPost;
  }

  const { photo }: Props = $props();

  let imgElement: HTMLImageElement;
  let deleteDialogElement: HTMLDialogElement;
  let title = $state(photo.title);
  let description = $state(photo.description);
  let isDeleteDialogOpen = $state(false);

  const handleImageChange = (event: Event) => {
    const target = event.target as HTMLInputElement;
    const file = target.files?.[0];
    if (file) {
      const reader = new FileReader();
      reader.onload = (e) => {
        if (e.target?.result) {
          imgElement.src = e.target.result as string;
        }
      };
      reader.readAsDataURL(file);
    }
  };

  const openDeleteDialog = () => {
    isDeleteDialogOpen = true;
    deleteDialogElement.showModal();
  };

  const closeDeleteDialog = () => {
    isDeleteDialogOpen = false;
    if (deleteDialogElement.open) {
      deleteDialogElement.close();
    }
  };

  const handleDeleteDialogClose = () => {
    isDeleteDialogOpen = false;
  };
</script>

<form
  class="cms-form"
  method="POST"
  enctype="multipart/form-data"
  action="?/update"
>
  <div class="image-container">
    <img
      src={`/image/${photo.fileName}`}
      alt={photo.title}
      class="preview"
      bind:this={imgElement}
    />
  </div>

  <div class="field">
    <label for="title">Title</label>
    <input type="text" id="title" name="title" bind:value={title} />
  </div>
  <div class="field">
    <label for="description">Description</label>
    <textarea
      id="description"
      name="description"
      rows="4"
      bind:value={description}
    ></textarea>
  </div>
  <div class="field">
    <label for="file">File</label>
    <input type="file" id="file" name="file" onchange={handleImageChange} />
  </div>

  <div class="actions">
    <input type="submit" value="Update Photo" class="thomaswilson-button" />
    <button
      type="button"
      class="thomaswilson-button danger"
      onclick={openDeleteDialog}
    >
      Delete photo
    </button>
  </div>
</form>

<dialog
  class="confirm-dialog"
  bind:this={deleteDialogElement}
  onclose={handleDeleteDialogClose}
>
  <p>Delete this photo permanently?</p>

  <div class="dialog-actions">
    <button
      type="button"
      class="thomaswilson-button"
      onclick={closeDeleteDialog}
    >
      No
    </button>

    <form method="POST" action="?/delete">
      <button type="submit" class="thomaswilson-button delete-button"
        >Yes, delete</button
      >
    </form>
  </div>
</dialog>

<style>
  .image-container {
    display: flex;
    justify-content: center;
  }

  .actions {
    display: flex;
    gap: 0.5rem;
  }


  img.preview {
    height: 250px;
  }
</style>
