"use client";
import Link from "next/link";
import Image from "next/image";
import { useEffect, useState, ChangeEvent } from "react";
import { toast } from "react-toastify";
import ColorPicker from "@/app/components/form/ColorPicker";
import { FormInput, FormButton } from "@/app/components/form/forms";
import TextArea from "@/app/components/form/TextArea";
import { getApiClient, postApiClient } from "@/utils/apiClient";
import { AWS_CDN_URL} from "@/utils/staticValues";
import Cookies from "js-cookie";

interface ShowcaseImgProps {
  id: number;
  file: File | null;
  preview: string;
  serverUrl?: string;
  uploading?: boolean;
}

export default function CoCreatorProfileDetail() {
  // State for profile data
  const [profileData, setProfileData] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  const [designHouseName, setDesignHouseName] = useState("");
  const [slug, setSlug] = useState("");
  const [profileImage, setProfileImage] = useState(
    "https://dummyimage.com/100x100/0fffff/484fb3&text=Logo",
  );
  const [backgroundIcon, setBackgroundIcon] = useState(
    "https://dummyimage.com/100x100/0fffff/484fb3&text=Bio+image",
  );
  const [symbolImage, setSymbolImage] = useState(
    "https://dummyimage.com/100x100/0fffff/484fb3&text=Thumbnail+image",
  );
  const [carouselImage, setCarouselImage] = useState([]);
  const [baseInCity, setBaseInCity] = useState("");
  const [caption, setCaption] = useState("");
  const [shortBio, setShortBio] = useState("");
  const [interests, setInterests] = useState("");
  const [buttonLink, setButtonLink] = useState("");
  const [buttonText, setButtonText] = useState("");

  const [hexcodeforBg, setHexcodeforBg] = useState("#ffffff");
  const [hero_bg_from, setHeroBgFrom] = useState("#ffffff");
  const [hero_bg_to, setHeroBgTo] = useState("#ffffff");
  const [hero_bg_via, setHeroBgVia] = useState("#ffffff");

  const [primary_color, setPrimaryColor] = useState("#ffffff");
  const [secondary_color, setSecondaryColor] = useState("#ffffff");
  const [font_color, setFontColor] = useState("#ffffff");
  const [highlight_color, setHighlightColor] = useState("#ffffff");
  const [button_color, setButtonColor] = useState("#ffffff");
  const [hexcode_for_piece_bg, setHexcodeForPieceBg] = useState("#ffffff");

  // start code for add/remove showcases ------------------------
  const showcaseLimit = 20;
  const [showcaseImg, setShowcaseImg] = useState<ShowcaseImgProps[]>([]);

  const handleAddShowcase = () => {
    if (showcaseImg.length >= 20) return;
    setShowcaseImg([
      ...showcaseImg,
      { id: Date.now(), file: null, preview: "" },
    ]);
  };

  const handleRemoveShowcase = (id: number) => {
    setShowcaseImg(showcaseImg.filter((img) => img.id !== id));
  };

  // Function to remove carousel image from server
  const handleRemoveCarouselImage = async (
    imageId: string | number,
    imagePath: string,
  ) => {
    try {
      const response = await postApiClient(
        "dashboard/cocreator/remove-carousel-image",
        {
          image_id: imageId,
          image_path: imagePath,
        },
      );

      console.log("Carousel image removed successfully:", response);
  toast.success("Image removed successfully!");

      // Refresh the profile data to show updated carousel images
      await fetchDesignHouseProfile();
    } catch (error: any) {
      console.error("Failed to remove carousel image:", error);
  toast.error("Failed to remove image. Please try again.");
    }
  };

  // Function to upload carousel image for co-creator
  const uploadCarouselImage = async (file: File) => {
    try {
      const formData = new FormData();
      formData.append("image", file);

      const response = await fetch(
        `${process.env.NEXT_PUBLIC_APP_URL}/dashboard/cocreator/carousel-image`,
        {
          method: "POST",
          headers: {
            Authorization: `Bearer ${Cookies.get("token")}`,
          },
          body: formData,
        },
      );

      const data = await response.json();
      if (!response.ok) throw new Error(data.message || "Upload failed");

      return data;
    } catch (error: any) {
      console.error("Carousel image upload error:", error);
      throw error;
    }
  };

  // Handle showcase image upload
  const handleShowcaseUpload = async (id: number, file: File) => {
    try {
      // Show preview immediately
      const updatedImages = showcaseImg.map((img) =>
        img.id === id
          ? {
              ...img,
              file,
              preview: URL.createObjectURL(file),
              uploading: true,
            }
          : img,
      );
      setShowcaseImg(updatedImages);

      // Upload to server using co-creator carousel API
      const uploadResponse = await uploadCarouselImage(file);

      // Update with server response
      const finalImages = showcaseImg.map((img) =>
        img.id === id
          ? {
              ...img,
              file,
              preview:
                uploadResponse.url ||
                `${AWS_CDN_URL}/${uploadResponse.image_path}` ||
                URL.createObjectURL(file),
              serverUrl:
                uploadResponse.url ||
                `${AWS_CDN_URL}/${uploadResponse.image_path}`,
              uploading: false,
            }
          : img,
      );
      setShowcaseImg(finalImages);

      // Refresh the profile data to show the new image immediately
      await fetchDesignHouseProfile();
    } catch (error: any) {
      console.error("Failed to upload carousel image:", error);
      // Reset upload state on error
      const resetImages = showcaseImg.map((img) =>
        img.id === id
          ? {
              ...img,
              uploading: false,
            }
          : img,
      );
      setShowcaseImg(resetImages);
    }
  };

  const handleShowcaseChange = (
    id: number,
    event: ChangeEvent<HTMLInputElement>,
  ) => {
    const file = event.target.files?.[0];
    if (file) {
      handleShowcaseUpload(id, file);
    }
  };

  // end code for add/remove showcases ------------------------
  const [savingDesignHouse, setSavingDesignHouse] = useState(false);
  const [savingThemeColors, setSavingThemeColors] = useState(false);
  const [savingBranding, setSavingBranding] = useState(false);

  // Function to save design house information
  const handleSaveDesignHouse = async (e: React.FormEvent) => {
    e.preventDefault();

    try {
      setSavingDesignHouse(true);

      const formData = {
        name: designHouseName,
        based_in_city: baseInCity,
        caption: caption,
        bio: shortBio,
        interests: interests,
        button_link: buttonLink,
        button_text: buttonText,
      };

      console.log("Saving co-creator data:", formData);

      const response = await postApiClient(
        "dashboard/cocreator/update-profile",
        formData,
      );

      console.log("Co-creator updated successfully:", response);

      // Show success message or handle success state
  toast.success("Co-creator information updated successfully!");

      // Refresh the profile data to show updated information
      await fetchDesignHouseProfile();
    } catch (error: any) {
      console.error("Failed to update co-creator:", error);
  toast.error("Failed to update co-creator information. Please try again.");
    } finally {
      setSavingDesignHouse(false);
    }
  };

  // Function to save theme colors
  const handleSaveThemeColors = async (e: React.FormEvent) => {
    e.preventDefault();

    try {
      setSavingThemeColors(true);

      const themeData = {
        hexcode_for_bg: hexcodeforBg,
        hero_bg_from: hero_bg_from,
        hero_bg_to: hero_bg_to,
        hero_bg_via: hero_bg_via,
        primary_color: primary_color,
        secondary_color: secondary_color,
        font_color: font_color,
        high_light_color: highlight_color,
        hexcode_for_button: button_color,
        hexcode_for_piece_bg: hexcode_for_piece_bg,
      };

      console.log("Saving theme colors:", themeData);

      const response = await postApiClient(
        "dashboard/cocreator/update-profile",
        themeData,
      );

      console.log("Theme colors updated successfully:", response);
  toast.success("Theme colors updated successfully!");

      // Refresh the profile data
      await fetchDesignHouseProfile();
    } catch (error: any) {
      console.error("Failed to update theme colors:", error);
  toast.error("Failed to update theme colors. Please try again.");
    } finally {
      setSavingThemeColors(false);
    }
  };

  // Function to handle image uploads for branding
  const handleBrandingImageUpload = async (
    imageType: "profile_image" | "background_icon" | "symbol",
    file: File,
  ) => {
    try {
      setSavingBranding(true);

      const formData = new FormData();
      formData.append("image", file);
      formData.append("image_type", imageType);

      const response = await fetch(
        `${process.env.NEXT_PUBLIC_APP_URL}/dashboard/cocreator/branding-image`,
        {
          method: "POST",
          headers: {
            Authorization: `Bearer ${Cookies.get("token")}`,
          },
          body: formData,
        },
      );

      const data = await response.json();
      if (!response.ok) throw new Error(data.message || "Upload failed");

      console.log(`${imageType} updated successfully:`, data);
  toast.success(`${imageType.replace("_", " ")} updated successfully!`);

      // Update the local state with new image URL
      if (imageType === "profile_image") {
        setProfileImage(data.url || `${AWS_CDN_URL}/${data.image_path}`);
      } else if (imageType === "background_icon") {
        setBackgroundIcon(data.url || `${AWS_CDN_URL}/${data.image_path}`);
      } else if (imageType === "symbol") {
        setSymbolImage(data.url || `${AWS_CDN_URL}/${data.image_path}`);
      }

      // Refresh the profile data
      await fetchDesignHouseProfile();
    } catch (error: any) {
      console.error(`Failed to upload ${imageType}:`, error);
      toast.error(
        `Failed to upload ${imageType.replace("_", " ")}. Please try again.`,
      );
    } finally {
      setSavingBranding(false);
    }
  };

  // Function to handle image removal
  const handleBrandingImageRemove = async (
    imageType: "profile_image" | "background_icon" | "symbol",
  ) => {
    try {
      setSavingBranding(true);

      const response = await postApiClient(
        "dashboard/cocreator/remove-branding-image",
        {
          image_type: imageType,
        },
      );

      console.log(`${imageType} removed successfully:`, response);
  toast.success(`${imageType.replace("_", " ")} removed successfully!`);

      // Reset the local state to default image
      const defaultImage =
        "https://dummyimage.com/100x100/0fffff/484fb3&text=" +
        (imageType === "profile_image"
          ? "Profile+Image"
          : imageType === "background_icon"
            ? "Background+Icon"
            : "Symbol");

      if (imageType === "profile_image") {
        setProfileImage(defaultImage);
      } else if (imageType === "background_icon") {
        setBackgroundIcon(defaultImage);
      } else if (imageType === "symbol") {
        setSymbolImage(defaultImage);
      }

      // Refresh the profile data
      await fetchDesignHouseProfile();
    } catch (error: any) {
      console.error(`Failed to remove ${imageType}:`, error);
      toast.error(
        `Failed to remove ${imageType.replace("_", " ")}. Please try again.`,
      );
    } finally {
      setSavingBranding(false);
    }
  };

  // Function to fetch design house profile
  const fetchDesignHouseProfile = async () => {
    try {
      setLoading(true);
      setError(null);
      const data = await getApiClient("dashboard/cocreator/profile");
      setProfileData(data);

      console.log("profile_data:", data);
      // Populate form fields with fetched data if available
      if (data) {
        setDesignHouseName(data.creator.name);

        setSlug(data.creator.slug || "");

        setBaseInCity(data.creator.based_in_city || "");
        setCaption(data.creator.caption || "");

        setShortBio(data.creator.bio || "");
        setButtonLink(data.creator.button_link || "");
        setButtonText(data.creator.button_text || "");
        setInterests(data.creator.interests || "");

        const L = data.creator.profile_image;
        if (L != null) {
          console.log("profile_image:", L);
          const LURL = L != null ? `${AWS_CDN_URL}/${L}` : "";
          setProfileImage(LURL);
        }

        const B = data.creator.background_icon;
        if (B != null) {
          const BURL = `${AWS_CDN_URL}/${B}`;
          setBackgroundIcon(BURL);
        }

        //setThumbnailImage
        const T = data.creator.symbol;

        if (T != null) {
          console.log("symbol:", T);
          const TURL = T != null ? `${AWS_CDN_URL}/${T}` : "";
          setSymbolImage(TURL);
        }

        setHexcodeforBg(data.creator.hexcode_for_bg || "");

        setHeroBgFrom(data.creator.hero_bg_from || "");
        setHeroBgTo(data.creator.hero_bg_to || "");
        setHeroBgVia(data.creator.hero_bg_via || "");
        setCarouselImage(data.creator.co_creator_images || []);

        // Set theme colors
        setPrimaryColor(data.creator.primary_color || "");
        setSecondaryColor(data.creator.secondary_color || "");
        setFontColor(data.creator.font_color || "");
        setHighlightColor(data.creator.high_light_color || "");
        setButtonColor(data.creator.hexcode_for_button || "");
        setHexcodeForPieceBg(data.creator.hexcode_for_piece_bg || "");

        // Clear upload forms since profile is refreshed and images are now on server
        setShowcaseImg([]);
      }
    } catch (error: any) {
      console.error("Failed to fetch design house profile:", error);
      setError(error.message || "Failed to load profile data");
    } finally {
      setLoading(false);
    }
  };

  // Effect to fetch profile data on component mount
  useEffect(() => {
    fetchDesignHouseProfile();
  }, []);

  return (
    <div className="flex w-full flex-col">
      {/* Loading state */}
      {loading && (
        <div className="flex items-center justify-center py-10">
          <div className="text-lg">Loading Profile data...</div>
        </div>
      )}

      {/* Error state */}
      {/* {error && (
        <div className="mb-5 rounded bg-red-100 border border-red-400 text-red-700 px-4 py-3">
          <strong>Error:</strong> {error}
          <button
            onClick={fetchDesignHouseProfile}
            className="ml-4 underline hover:no-underline"
          >
            Retry
          </button>
        </div>
      )} */}

      <div className="flex flex-col">
        <h1 className="med">Co Creator</h1>
      </div>
      <div className="mt-5 flex w-full flex-col justify-between gap-5 align-top md:flex-row">
        <div className="flex w-full flex-col">
          <div className="flex flex-col gap-4">
            {designHouseName && (
              <div>
                <Link
                  href={`/co-creators/${slug}`}
                  target="_blank"
                  className="btn-outline items-center justify-center align-middle"
                >
                  <span className="relative top-[2px] mr-1">
                    <i
                      className="icon-[humbleicons--link]"
                      style={{ width: 18, height: 18 }}
                    ></i>
                  </span>
                  View your Co Creator
                </Link>
              </div>
            )}

            <form
              onSubmit={handleSaveDesignHouse}
              className="flex w-full flex-col"
            >
              <div className="mt-5 flex flex-col gap-5 bg-white p-5 md:gap-10 md:p-10">
                <FormInput
                  type="text"
                  id="design_house_name"
                  label="Co-Creator Name"
                  require={true}
                  value={designHouseName}
                  onChange={(e: any) => setDesignHouseName(e.target.value)}
                />

                <div className="grid grid-cols-1 gap-5 md:grid-cols-2 md:gap-10">
                  <FormInput
                    type="text"
                    id="dh_base_in_city"
                    label="Base in City"
                    require={true}
                    value={baseInCity}
                    onChange={(e: any) => setBaseInCity(e.target.value)}
                  />
                  <FormInput
                    type="text"
                    id="dh_caption"
                    label="Caption"
                    require={true}
                    value={caption}
                    onChange={(e: any) => setCaption(e.target.value)}
                  />
                  <FormInput
                    type="text"
                    id="Interests"
                    label="Interests"
                    require={true}
                    value={interests}
                    onChange={(e: any) => setInterests(e.target.value)}
                  />
                  <FormInput
                    type="text"
                    id="button_link"
                    label="Button Link"
                    require={true}
                    value={buttonLink}
                    onChange={(e: any) => setButtonLink(e.target.value)}
                  />
                  <FormInput
                    type="text"
                    id="button_text"
                    label="Button Text"
                    require={true}
                    value={buttonText}
                    onChange={(e: any) => setButtonText(e.target.value)}
                  />
                </div>

                <div>
                  <h4 className="med">Bio</h4>
                  <TextArea
                    label=""
                    name="dh_short_intro"
                    maxLength={500}
                    placeholder="Tell us something about your design house short intro..."
                    showLimitMessage={true}
                    value={shortBio}
                    onChange={(e) => setShortBio(e.target.value)}
                    required={true}
                  />
                </div>

                <div className="flex w-full md:w-[30%]">
                  <FormButton
                    id="btn_save_design_house"
                    label={savingDesignHouse ? "Saving..." : "Save Co Creator"}
                    type="submit"
                    color="gray"
                    hairline=""
                    disabled={savingDesignHouse}
                  />
                </div>
              </div>
            </form>
            <div className="mt-5 flex flex-col gap-5 bg-white p-5 md:gap-10 md:p-10">
              <div className="flex flex-row items-center justify-between gap-2 align-middle">
                <div className="font-bogart text-xl capitalize">
                  Co-Creator Branding
                </div>
              </div>
              <div className="grid grid-cols-2 gap-5 md:grid-cols-3 md:gap-10">
                <div className="flex flex-col gap-1">
                  <p className="label">Profile Image</p>
                  <div>
                    <Image
                      src={profileImage}
                      width={128}
                      height={128}
                      alt="profile image"
                      className="w-[128px]"
                    />
                  </div>
                  <div className="flex flex-row gap-4">
                    <button
                      type="button"
                      onClick={() => handleBrandingImageRemove("profile_image")}
                      disabled={savingBranding}
                      className="btn-link disabled:opacity-50"
                    >
                      {savingBranding ? "Processing..." : "Remove"}
                    </button>
                    <label className="btn-link cursor-pointer">
                      <input
                        type="file"
                        accept="image/*"
                        className="hidden"
                        disabled={savingBranding}
                        onChange={(e) => {
                          const file = e.target.files?.[0];
                          if (file)
                            handleBrandingImageUpload("profile_image", file);
                        }}
                      />
                      {savingBranding ? "Processing..." : "Change"}
                    </label>
                  </div>
                </div>
                <div className="flex flex-col gap-1">
                  <p className="label">Background Icon</p>
                  <div>
                    <Image
                      src={backgroundIcon}
                      width={128}
                      height={128}
                      alt="background icon"
                      className="w-[128px]"
                    />
                  </div>
                  <div className="flex flex-row gap-4">
                    <button
                      type="button"
                      onClick={() =>
                        handleBrandingImageRemove("background_icon")
                      }
                      disabled={savingBranding}
                      className="btn-link disabled:opacity-50"
                    >
                      {savingBranding ? "Processing..." : "Remove"}
                    </button>
                    <label className="btn-link cursor-pointer">
                      <input
                        type="file"
                        accept="image/*"
                        className="hidden"
                        disabled={savingBranding}
                        onChange={(e) => {
                          const file = e.target.files?.[0];
                          if (file)
                            handleBrandingImageUpload("background_icon", file);
                        }}
                      />
                      {savingBranding ? "Processing..." : "Change"}
                    </label>
                  </div>
                </div>
                <div className="flex flex-col gap-1">
                  <p className="label">Symbol</p>
                  <div>
                    <Image
                      src={symbolImage}
                      width={128}
                      height={128}
                      alt="symbol image"
                      className="w-[128px]"
                    />
                  </div>
                  <div className="flex flex-row gap-4">
                    <button
                      type="button"
                      onClick={() => handleBrandingImageRemove("symbol")}
                      disabled={savingBranding}
                      className="btn-link disabled:opacity-50"
                    >
                      {savingBranding ? "Processing..." : "Remove"}
                    </button>
                    <label className="btn-link cursor-pointer">
                      <input
                        type="file"
                        accept="image/*"
                        className="hidden"
                        disabled={savingBranding}
                        onChange={(e) => {
                          const file = e.target.files?.[0];
                          if (file) handleBrandingImageUpload("symbol", file);
                        }}
                      />
                      {savingBranding ? "Processing..." : "Change"}
                    </label>
                  </div>
                </div>
              </div>
            </div>
            <form onSubmit={handleSaveThemeColors} name="theme_settings">
              <div className="mt-5 flex flex-col gap-5 bg-white p-5 md:gap-10 md:p-10">
                <div className="flex flex-row items-center justify-between gap-2 align-middle">
                  <div className="font-bogart text-xl capitalize">
                    Theme Colors
                  </div>
                </div>
                <div className="flex flex-col gap-2 border-b-1 border-gray-950/25 pb-4">
                  <div className="flex text-sm font-medium capitalize">
                    Hero/Top section gradient background
                  </div>
                  <div className="flex text-xs">
                    If you want solid background Use the same value for all
                    settings.
                  </div>
                  <div className="grid grid-cols-2 gap-5 md:grid-cols-3 md:gap-10">
                    <ColorPicker
                      id="hero_bg_2"
                      label="Hero Background From"
                      value={hero_bg_from || ""}
                      onChange={(color: any) => setHeroBgFrom(color)}
                    />
                    <ColorPicker
                      id="hero_bg_4"
                      label="Hero Background To"
                      value={hero_bg_to || ""}
                      onChange={(color: any) => setHeroBgTo(color)}
                    />
                    <ColorPicker
                      id="hero_bg_via"
                      label="Hero Background Via"
                      value={hero_bg_via || ""}
                      onChange={(color: any) => setHeroBgVia(color)}
                    />
                  </div>
                  <div
                    className="flex flex-col items-center justify-center p-8 align-middle"
                    style={{
                      background: `linear-gradient(to right, ${hero_bg_from}, ${hero_bg_via}, ${hero_bg_to})`,
                      color: `${hexcodeforBg}`,
                    }}
                  >
                    <div className="flex flex-col text-center">
                      <h3>{designHouseName || "Placeholder Co-Creator Name"}</h3>
                      <p className="text-xs">
                       {caption || "Placeholder Caption"}
                      </p>
                    </div>
                  </div>
                </div>
                <div className="flex flex-col gap-2 border-b-1 border-gray-950/25 pb-4">
                  <div className="flex text-sm font-medium capitalize">
                    Overall Page styles
                  </div>
                  <div className="grid grid-cols-2 gap-5 md:grid-cols-3 md:gap-10">
                    <div className="flex flex-row gap-1">
                      <ColorPicker
                        id="hero_bg_1"
                        label="Primary color"
                        value={hexcodeforBg || ""}
                        onChange={(color: any) => setHexcodeforBg(color)}
                      />
                      <div
                        title={`Also applies to \n1) Hero text color. \n2) Button text color. \n3) Featured piece bg gradient 1.`}
                      >
                        <i className="icon-[mage--message-info-round-fill] bg-gray-500"></i>
                      </div>
                    </div>
                    <div className="flex flex-row gap-1">
                      <ColorPicker
                        id="font_color"
                        label="body Font Color"
                        value={font_color}
                        onChange={(color: any) => setFontColor(color)}
                      />
                      <div
                        title={`Also apply to botton hover background color.`}
                      >
                        <i className="icon-[mage--message-info-round-fill] bg-gray-500"></i>
                      </div>
                    </div>
                  </div>
                  <div
                    className="flex flex-col items-center justify-center p-8 align-middle"
                    style={{
                      backgroundColor: `${hexcodeforBg}`,
                      color: `${font_color}`,
                    }}
                  >
                    <div>
                     {shortBio || "Placeholder short bio"}
                    </div>
                  </div>
                </div>
                <div className="hidden flex-col gap-2 border-b-1 border-gray-950/25 pb-4">
                  <div className="grid grid-cols-2 gap-5 md:grid-cols-3 md:gap-10">
                    <ColorPicker
                      id="hexcode_for_piece_bg"
                      label="Hallmark border color"
                      value={hexcode_for_piece_bg}
                      onChange={(color: any) => setHexcodeForPieceBg(color)}
                    />
                  </div>
                </div>
                <div className="flex flex-col gap-2 border-b-1 border-gray-950/25 pb-4">
                  <div className="flex text-sm font-medium capitalize">
                    Other color styles
                  </div>
                  <div className="grid grid-cols-2 gap-5 md:grid-cols-3 md:gap-10">
                    <div className="flex flex-row gap-1">
                      <ColorPicker
                        id="primary_color"
                        label="Footer Color"
                        value={primary_color}
                        onChange={(color: any) => setPrimaryColor(color)}
                      />
                      <div title={`Also apply to hallmark border color.`}>
                        <i className="icon-[mage--message-info-round-fill] bg-gray-500"></i>
                      </div>
                    </div>
                    <div className="flex flex-row gap-1">
                      <ColorPicker
                        id="secondary_color"
                        label="Featured piece button bg"
                        value={secondary_color}
                        onChange={(color: any) => setSecondaryColor(color)}
                      />
                    </div>
                    <ColorPicker
                      id="highlight_color"
                      label="Featured piece bg gradient"
                      value={highlight_color}
                      onChange={(color: any) => setHighlightColor(color)}
                    />
                  </div>
                </div>
                <div className="flex flex-col gap-2 border-b-1 border-gray-950/25 pb-4">
                  <div className="grid grid-cols-2 gap-5 md:grid-cols-3 md:gap-10">
                    <ColorPicker
                      id="button_color"
                      label="Button Color"
                      value={button_color}
                      onChange={(color: any) => setButtonColor(color)}
                    />
                  </div>
                </div>
                <div className="flex w-full md:w-[30%]">
                  {designHouseName && (
                    <FormButton
                      id="btn_theme_save_color"
                      label={
                        savingThemeColors ? "Saving..." : "Save Theme Colors"
                      }
                      type="submit"
                      color="gray"
                      hairline=""
                      disabled={savingThemeColors}
                    />
                  )}
                </div>
              </div>
            </form>
            <div className="mt-5 flex flex-col gap-5 bg-white p-5 md:p-10">
              <div>
                <h4 className="med">My Showcase</h4>
                <p className="label">
                  Select and upload images one by one. Images will be saved
                  immediately upon upload:
                </p>
                <ul className="text-xs">
                  <li>• Raw materials (fabrics, threads, buttons)</li>
                  <li>• Tools & hands at work (the human touch)</li>
                  <li>
                    • Process shots (loom setup, dye vats, embroidery in
                    progress)
                  </li>
                  <li>
                    • sketches / process, Finished garments, detail close-ups,
                    people wearing pieces
                  </li>
                </ul>
              </div>

              {/* Display existing carousel images */}
              {carouselImage && carouselImage.length > 0 && (
                <div>
                  <h5 className="mb-3 font-medium">Current Showcase Images</h5>
                  <div className="mb-5 grid grid-cols-2 gap-3 md:grid-cols-4">
                    {carouselImage.map((carouselImg: any, index: number) => (
                      <div
                        key={carouselImg.id || index}
                        className="group relative"
                      >
                        <Image
                          src={`${AWS_CDN_URL}/${carouselImg.image}`}
                          width={150}
                          height={150}
                          alt={`Showcase ${index + 1}`}
                          className="h-32 w-full rounded border object-cover"
                        />
                        <button
                          type="button"
                          onClick={() =>
                            handleRemoveCarouselImage(
                              carouselImg.id,
                              carouselImg.image,
                            )
                          }
                          className="absolute top-1 right-1 flex h-6 w-6 items-center justify-center rounded-full bg-red-500 text-xs text-white opacity-0 transition-opacity group-hover:opacity-100"
                          title="Remove image"
                        >
                          ×
                        </button>
                      </div>
                    ))}
                  </div>
                </div>
              )}

              {/* Upload new images section */}
              <div>
                <h5 className="mb-3 font-medium">Add New Images</h5>
                <div className="grid grid-cols-1 gap-5 md:grid-cols-2">
                  {showcaseImg.map((image, index) => (
                    <div
                      key={image.id}
                      className="flex w-full flex-row items-center justify-center gap-2 bg-gray-100 p-5 text-xs"
                    >
                      <div className="flex-1">
                        <input
                          type="file"
                          accept="image/*"
                          onChange={(e) => handleShowcaseChange(image.id, e)}
                          className="w-full rounded-2xl border-1 bg-gray-300 p-2 text-center"
                          disabled={image.uploading}
                        />
                        {image.uploading && (
                          <div className="mt-2 text-xs text-blue-600">
                            Uploading...
                          </div>
                        )}
                      </div>
                      {image.preview && (
                        <div className="relative">
                          <Image
                            src={image.preview}
                            width={100}
                            height={100}
                            alt={`Preview ${index + 1}`}
                            className="h-20 w-20 rounded border object-cover"
                          />
                          {image.uploading && (
                            <div className="bg-opacity-50 absolute inset-0 flex items-center justify-center rounded bg-black">
                              <div className="text-xs text-white">
                                Uploading...
                              </div>
                            </div>
                          )}
                        </div>
                      )}
                      <button
                        type="button"
                        onClick={() => handleRemoveShowcase(image.id)}
                        className="text-amber-600 underline underline-offset-4"
                        disabled={image.uploading}
                      >
                        Remove
                      </button>
                    </div>
                  ))}
                </div>
              </div>

              <div>
                <button
                  type="button"
                  onClick={handleAddShowcase}
                  disabled={showcaseImg.length >= showcaseLimit}
                  className={`flex px-2 py-2 text-xs ${showcaseImg.length >= showcaseLimit ? "bg-gray-300 text-gray-600" : "btn-outline"}`}
                >
                  {showcaseImg.length >= showcaseLimit
                    ? "You have reach the limit"
                    : "Add New Image"}
                </button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}
