"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";
import { createClient } from "../../../lib/supabase/client";

type Props = {
  productId: string;
  productName: string;
  featuredImageUrl: string | null;
};

export default function DeleteProductButton({
  productId,
  productName,
  featuredImageUrl,
}: Props) {
  const router = useRouter();

  const [deleting, setDeleting] =
    useState(false);

  const [errorMessage, setErrorMessage] =
    useState("");

  function getStoragePath(
    publicUrl: string
  ) {
    const marker =
      "/storage/v1/object/public/product-media/";

    const index =
      publicUrl.indexOf(marker);

    if (index === -1) {
      return null;
    }

    return decodeURIComponent(
      publicUrl.substring(
        index + marker.length
      )
    );
  }

  async function handleDelete() {
    const confirmed = window.confirm(
      `Delete "${productName}"?\n\n` +
      `This will permanently remove the product, its image and its video.\n\n` +
      `This action cannot be undone.`
    );

    if (!confirmed) {
      return;
    }

    setDeleting(true);
    setErrorMessage("");

    const supabase = createClient();

    try {

      // ======================================
      // GET PRODUCT MEDIA
      // ======================================

      const {
        data: media,
        error: mediaError,
      } = await supabase
        .from("product_media")
        .select(
          "id, media_url, media_type"
        )
        .eq(
          "product_id",
          productId
        );

      if (mediaError) {
        throw mediaError;
      }


      // ======================================
      // COLLECT STORAGE PATHS
      // ======================================

      const storagePaths =
        new Set<string>();

      media?.forEach((item) => {
        const path =
          getStoragePath(
            item.media_url
          );

        if (path) {
          storagePaths.add(path);
        }
      });


      // Also check featured image
      // in case an older product does not
      // have a product_media image record.

      if (featuredImageUrl) {
        const imagePath =
          getStoragePath(
            featuredImageUrl
          );

        if (imagePath) {
          storagePaths.add(
            imagePath
          );
        }
      }


      // ======================================
      // DELETE STORAGE FILES
      // ======================================

      if (
        storagePaths.size > 0
      ) {
        const {
          error: storageError,
        } = await supabase.storage
          .from("product-media")
          .remove(
            Array.from(
              storagePaths
            )
          );

        if (storageError) {
          throw storageError;
        }
      }


      // ======================================
      // DELETE PRODUCT
      // ======================================

      const {
        error: productError,
      } = await supabase
        .from("products")
        .delete()
        .eq(
          "id",
          productId
        );

      if (productError) {
        throw productError;
      }


      // ======================================
      // REFRESH
      // ======================================

      router.refresh();

    } catch (error) {
      console.error(error);

      setErrorMessage(
        error instanceof Error
          ? error.message
          : "Unable to delete product."
      );

    } finally {
      setDeleting(false);
    }
  }


  return (
    <div className="inline-flex flex-col">

      <button
        type="button"
        onClick={handleDelete}
        disabled={deleting}
        className="rounded-full border border-red-200 px-4 py-2 text-sm font-bold text-red-600 transition hover:bg-red-600 hover:text-white disabled:opacity-50"
      >
        {deleting
          ? "Deleting..."
          : "Delete"}
      </button>

      {errorMessage && (
        <p className="mt-2 max-w-[180px] text-xs text-red-600">
          {errorMessage}
        </p>
      )}

    </div>
  );
}