"use client";
import Link from "next/link";
import Image from "next/image";
import { useEffect, useState, Suspense, lazy, ChangeEvent } from "react";
import ColorPicker from "@/app/components/form/ColorPicker";
import { FormInput, FormButton } from "@/app/components/form/forms";
import MobileNumber from "@/app/components/form/country/MobileNumber";
import { GeoLocation } from "@/app/components/locations/geonames";
import TextArea from "@/app/components/form/TextArea";
import { getApiClient, postApiClient, postFormDataClient, deleteApiClient } from "@/utils/apiClient";
import { AWS_CDN_URL} from "@/utils/staticValues";
import { toast } from "react-toastify";

const ZipCodeLookup = lazy(
  () => import("@/app/components/locations/ZipCodeLookup"),
);

interface HallmarksProps {
  id: number;
  value: string;
}

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

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

  const [designHouseName, setDesignHouseName] = useState("");
  const [businessEmail, setBusinessEmail] = useState("");
  const [secondaryEmail, setSecondaryEmail] = useState("");
  const [mobileCode, setMobileCode] = useState("+91");
  const [mobileNumber, setMobileNumber] = useState("");
  const [secondaryPhone, setSecondaryPhone] = useState("");
  const [website, setWebsite] = useState("");
  const [description, setDescription] = useState("");
  const [addressLine1, setAddressLine1] = useState("");
  const [addressLine2, setAddressLine2] = useState("");
  const [city, setCity] = useState("");
  const [state, setState] = useState("");
  const [country, setCountry] = useState("");
  const [postalCode, setPostalCode] = useState("");
  const [minimumOrderValue, setMinimumOrderValue] = useState("");
  const [leadTimeDays, setLeadTimeDays] = useState("");
  const [logo, setLogo] = useState(
    "https://dummyimage.com/100x100/0fffff/484fb3&text=Logo",
  );
  const [bioImage, setBioImage] = useState(
    "https://dummyimage.com/100x100/0fffff/484fb3&text=Bio+image",
  );
  const [thumbnailImage, setThumbnailImage] = useState(
    "https://dummyimage.com/100x100/0fffff/484fb3&text=Thumbnail+image",
  );
  const [carouselImage, setCarouselImage] = useState([]);
  const [designHouseAddress, setDesignHouseAddress] = useState(
    "A-75, Cedar Apartment",
  );
  const [baseInCity, setBaseInCity] = useState("");
  const [hallmark, setHallmark] = useState("");
  const [caption, setCaption] = useState("");
  const [piecesBio, setPiecesBio] = useState(
    "Tell us something about your design house...",
  );

  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");
  const [designHouseId, setDesignHouseId] = useState("");

  const [shortBio, setShortBio] = useState("");

  // Social share images state
  const [socialShareImages, setSocialShareImages] = useState({
    x: "https://dummyimage.com/400x200/0fffff/484fb3&text=X+Share+Image",
    facebook:
      "https://dummyimage.com/400x200/0fffff/484fb3&text=Facebook+Share+Image",
    linkedin:
      "https://dummyimage.com/400x200/0fffff/484fb3&text=LinkedIn+Share+Image",
    pinterest:
      "https://dummyimage.com/400x200/0fffff/484fb3&text=Pinterest+Share+Image",
    whatsapp:
      "https://dummyimage.com/400x200/0fffff/484fb3&text=WhatsApp+Share+Image",
  });
  const [savingSocialShares, setSavingSocialShares] = useState(false);

  // start code for add/remove hallmarks ------------------------
  const HMLimit = 10;
  const [HMItems, setHMItems] = useState<HallmarksProps[]>([]);

  const handleHMAdd = () => {
    if (HMItems.length < HMLimit) {
      setHMItems([...HMItems, { id: Date.now(), value: "" }]);
    }
  };

  const handleHMRemove = (id: number) => {
    setHMItems(HMItems.filter((item) => item.id !== id));
  };

  const handleHMChange = (id: number, value: string) => {
    setHMItems(
      HMItems.map((item) => (item.id === id ? { ...item, value } : item)),
    );
  };

  // end code for add/remove hallmarks ------------------------
  // 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 upload image
  const uploadImage = async (file: File) => {
    try {
      const formData = new FormData();
      formData.append("image", file);
      formData.append("image_type", "showcase");
      formData.append("design_house_profile_id", designHouseId);

      const data = await postFormDataClient(
        "dashboard/designhouse/showcase-image",
        formData
      );

      return data;
    } catch (error: any) {
      console.error("Image upload error:", error);
      toast.error(error.message || "Failed to upload image. Please try again.", {
        toastId: "image_upload_error",
      });
      throw error;
    }
  };

  // Function to delete existing showcase image
  const deleteShowcaseImage = async (imageId: number) => {
    try {
      await postApiClient(
        `dashboard/designhouse/showcase-image/${imageId}`,
        { _method: "DELETE" }
      );

      toast.success("Image deleted successfully!", {
        toastId: "image_delete_success",
      });

      // Re-fetch design house profile to update carousel images
      await fetchDesignHouseProfile();
    } catch (error: any) {
      console.error("Image delete error:", error);
      toast.error("Failed to delete image. Please try again.", {
        toastId: "image_delete_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
      const uploadResponse = await uploadImage(file);

      // Re-fetch design house profile to update carousel images
      await fetchDesignHouseProfile();

      // Remove the uploaded image from the form after successful upload
      setShowcaseImg((prev) => prev.filter((img) => img.id !== id));
    } catch (error: any) {
      console.error("Failed to upload 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 ------------------------
  // start code for add/remove team ---------------------------
  const teamLimit = 20;
  type TeamMember = {
    id: number;
    name: string;
    role: string;
    hourly_rate: string;
    years_of_experience: string;
    availability_status: string;
    bio: string;
    image?: File;
    imagePreview?: string;
    artisan_profile_photo?: string;
  };
  const [team, setTeam] = useState<TeamMember[]>([]);
  const [newMembers, setNewMembers] = useState<TeamMember[]>([]);
  const [savingTeam, setSavingTeam] = useState(false);
  const [savingDesignHouse, setSavingDesignHouse] = useState(false);
  const [savingThemeColors, setSavingThemeColors] = useState(false);
  const [savingShowcase, setSavingShowcase] = useState(false);
  const [savingBranding, setSavingBranding] = useState(false);

  const roleOptions = [
    { value: "Admin", label: "Admin" },
    { value: "Designer", label: "Designer" },
    { value: "Tailor", label: "Tailor" },
    { value: "Embroiderer", label: "Embroiderer" },
    { value: "Pattern Master", label: "Pattern Master" },
    { value: "Dyer", label: "Dyer" },
    { value: "Block Printer", label: "Block Printer" },
    { value: "Painter", label: "Painter" },
    { value: "Hemmer", label: "Hemmer" },
    { value: "Quality Control", label: "Quality Control" },
  ];

  const statusOptions = [
    { value: "Available", label: "Available" },
    { value: "Busy", label: "Busy" },
    { value: "On Leave", label: "On Leave" },
  ];
  const handleAddMember = () => {
    if (team.length + newMembers.length >= teamLimit) return;
    const newMember: TeamMember = {
      id: Date.now(),
      name: "",
      role: "",
      hourly_rate: "",
      years_of_experience: "",
      availability_status: "Available",
      bio: "",
    };
    setNewMembers((prev) => [...prev, newMember]);
  };

  const handleRemoveMember = async (id: number) => {
    // Show confirmation dialog
    const confirmed = window.confirm(
      "Are you sure you want to remove this team member? This action cannot be undone."
    );
    
    // If user cancels, do nothing
    if (!confirmed) {
      return;
    }

    try {
      // Call API to remove team member with proper DELETE request
      const response = await deleteApiClient(
        `dashboard/designhouse/remove-team-member/${id}`
      );
      
      console.log("Remove team member API response:", response);

      toast.success("Team member removed successfully");

      // Refresh data from server to ensure consistency
      await fetchDesignHouseProfile();

      console.log(`Team member ${id} removed successfully`);
    } catch (error: any) {
      console.error("Failed to remove team member:", error);
      toast.error(error.message || "Failed to remove team member. Please try again.");
      
      // Log the full error for debugging
      console.error("Full error details:", error);
    }
  };

  const handleRemoveNewMember = (id: number) => {
    setNewMembers((prev) => prev.filter((member) => member.id !== id));
  };

  const handleMemberChange = (
    id: number,
    field: keyof TeamMember,
    value: any,
  ) => {
    setTeam((prev) =>
      prev.map((member) =>
        member.id === id ? { ...member, [field]: value } : member,
      ),
    );
  };

  const handleNewMemberChange = (
    id: number,
    field: keyof TeamMember,
    value: any,
  ) => {
    setNewMembers((prev) =>
      prev.map((member) =>
        member.id === id ? { ...member, [field]: value } : member,
      ),
    );
  };

  const handleMemberImageChange = (id: number, file: File) => {
    const imagePreview = URL.createObjectURL(file);
    setTeam((prev) =>
      prev.map((member) =>
        member.id === id ? { ...member, image: file, imagePreview } : member,
      ),
    );
  };

  const handleNewMemberImageChange = (id: number, file: File) => {
    const imagePreview = URL.createObjectURL(file);
    setNewMembers((prev) =>
      prev.map((member) =>
        member.id === id ? { ...member, image: file, imagePreview } : member,
      ),
    );
  };

  // Function to save new team members
  const handleSaveNewMembers = async () => {
    try {
      setSavingTeam(true);

      // Validate that design house profile exists
      if (!designHouseId) {
        toast.error("Design house profile not found. Please refresh the page.", {
          toastId: "no_design_house_id",
        });
        return;
      }

      // Validate all new members have required fields
      const invalidMembers = newMembers.filter(
        (member) => !member.name || !member.role
      );
      if (invalidMembers.length > 0) {
        toast.error("Please fill in name and role for all team members.", {
          toastId: "team_validation_error",
        });
        return;
      }

      const promises = newMembers.map(async (member) => {
        // Prepare form data for each member
        const formData = new FormData();
        formData.append("design_house_profile_id", designHouseId);
        formData.append("name", member.name);
        formData.append("role", member.role);
        formData.append("hourly_rate", member.hourly_rate || "0");
        formData.append("years_of_experience", member.years_of_experience || "0");
        formData.append("availability_status", member.availability_status);
        formData.append("bio", member.bio || "");

        if (member.image) {
          formData.append("artisan_profile_photo", member.image);
        }

        // Call API to add new team member using server-side proxy
        const data = await postFormDataClient(
          "dashboard/designhouse/new-team-member",
          formData
        );

        return data;
      });

      // Wait for all members to be added
      const results = await Promise.all(promises);

      console.log("All new team members added successfully:", results);
      toast.success("Team members added successfully!", {
        toastId: "team_members_added_success",
      });

      // Clear new members and refresh the team list
      setNewMembers([]);
      await fetchDesignHouseProfile(); // Refresh to get updated team data
    } catch (error: any) {
      console.error("Failed to save new team members:", error);
      toast.error(error.message || "Failed to add team members. Please try again.", {
        toastId: "team_members_add_error",
      });
    } finally {
      setSavingTeam(false);
    }
  };
  // end code for add/remove team -----------------------------

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

    try {
      setSavingDesignHouse(true);

      const formData = {
        name: designHouseName,
        primary_email: businessEmail,
        secondary_email: secondaryEmail,
        mobile_code: mobileCode,
        primary_phone: mobileNumber,
        secondary_phone: secondaryPhone,
        website: website,
        description: description,
        address_line_1: addressLine1,
        address_line_2: addressLine2,
        city: city,
        state: state,
        country: country,
        postal_code: postalCode,
        minimum_order_value: minimumOrderValue,
        lead_time_days: leadTimeDays,
        based_in_city: baseInCity,
        caption: caption,
        hallmarks: hallmark,
        bio: shortBio,
        pieces_bio: piecesBio,
      };

      console.log("Saving design house data:", formData);

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

      console.log("Design house updated successfully:", response);

      // Show success toast
      toast.success("Design house information updated successfully!", {
        toastId: "design_house_updated_success",
      });

      // Refresh the profile data to show updated information
      await fetchDesignHouseProfile();
    } catch (error: any) {
      console.error("Failed to update design house:", error);
      // Show error toast
      toast.error(
        "Failed to update design house information. Please try again.",
        {
          toastId: "design_house_update_error",
        },
      );
    } 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,
      };

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

      const response = await postApiClient(
        "dashboard/designhouse/update-theme-colors",
        themeData,
      );

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

      // 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.", {
        toastId: "theme_colors_update_error",
      });
    } finally {
      setSavingThemeColors(false);
    }
  };

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

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

      const data = await postFormDataClient(
        "dashboard/designhouse/update-branding-image",
        formData
      );

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

      // Update the local state with new image URL
      if (imageType === "logo") {
        setLogo(data.url || `${AWS_CDN_URL}/${data.image_path}`);
      } else if (imageType === "bio_image") {
        setBioImage(data.url || `${AWS_CDN_URL}/${data.image_path}`);
      } else if (imageType === "thumbnail_image") {
        setThumbnailImage(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.`,
        {
          toastId: `${imageType}_upload_error`,
        },
      );
    } finally {
      setSavingBranding(false);
    }
  };

  // Function to handle image removal
  const handleBrandingImageRemove = async (
    imageType: "logo" | "bio_image" | "thumbnail_image",
  ) => {
    try {
      setSavingBranding(true);

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

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

      // Reset the local state to default image
      const defaultImage =
        "https://dummyimage.com/100x100/0fffff/484fb3&text=" +
        (imageType === "logo"
          ? "Logo"
          : imageType === "bio_image"
            ? "Bio+image"
            : "Thumbnail+image");

      if (imageType === "logo") {
        setLogo(defaultImage);
      } else if (imageType === "bio_image") {
        setBioImage(defaultImage);
      } else if (imageType === "thumbnail_image") {
        setThumbnailImage(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.`,
        {
          toastId: `${imageType}_remove_error`,
        },
      );
    } finally {
      setSavingBranding(false);
    }
  };

  // Function to handle social share image uploads
  const handleSocialShareImageUpload = async (
    platform: "x" | "facebook" | "linkedin" | "pinterest" | "whatsapp",
    file: File,
  ) => {
    try {
      setSavingSocialShares(true);

      const formData = new FormData();
      formData.append("image", file);
      formData.append("platform", platform);
      formData.append("design_house_profile_id", designHouseId);

      const data = await postFormDataClient(
        "dashboard/designhouse/update-social-share-image",
        formData
      );

      console.log(`${platform} social share image updated successfully:`, data);
      toast.success(
        `${platform.charAt(0).toUpperCase() + platform.slice(1)} share image updated successfully!`,
        {
          toastId: `${platform}_share_image_updated_success`,
        },
      );

      // Update the local state with new image URL
      setSocialShareImages((prev) => ({
        ...prev,
        [platform]: data.url || `${AWS_CDN_URL}/${data.image_path}`,
      }));

      // Refresh the profile data
      await fetchDesignHouseProfile();
    } catch (error: any) {
      console.error(`Failed to upload ${platform} social share image:`, error);
      toast.error(
        `Failed to upload ${platform.charAt(0).toUpperCase() + platform.slice(1)} share image. Please try again.`,
        {
          toastId: `${platform}_share_image_upload_error`,
        },
      );
    } finally {
      setSavingSocialShares(false);
    }
  };

  // Function to remove social share image
  const handleSocialShareImageRemove = async (
    platform: "x" | "facebook" | "linkedin" | "pinterest" | "whatsapp",
  ) => {
    try {
      setSavingSocialShares(true);

      const response = await postApiClient(
        "dashboard/designhouse/remove-social-share-image",
        {
          platform: platform,
        },
      );

      console.log(
        `${platform} social share image removed successfully:`,
        response,
      );
      toast.success(
        `${platform.charAt(0).toUpperCase() + platform.slice(1)} share image removed successfully!`,
        {
          toastId: `${platform}_share_image_removed_success`,
        },
      );

      // Reset the local state to default image
      const defaultImage = `https://dummyimage.com/400x200/0fffff/484fb3&text=${platform.charAt(0).toUpperCase() + platform.slice(1)}+Share+Image`;

      setSocialShareImages((prev) => ({
        ...prev,
        [platform]: defaultImage,
      }));

      // Refresh the profile data
      await fetchDesignHouseProfile();
    } catch (error: any) {
      console.error(`Failed to remove ${platform} social share image:`, error);
      toast.error(
        `Failed to remove ${platform.charAt(0).toUpperCase() + platform.slice(1)} share image. Please try again.`,
        {
          toastId: `${platform}_share_image_remove_error`,
        },
      );
    } finally {
      setSavingSocialShares(false);
    }
  };

  // Function to save showcase images
  const handleSaveShowcase = async (e: React.FormEvent) => {
    e.preventDefault();

    try {
      setSavingShowcase(true);

      // Prepare showcase images data - only include images with serverUrl
      const showcaseData = showcaseImg
        .filter((img) => img.serverUrl)
        .map((img) => ({
          image_url: img.serverUrl,
          preview_url: img.preview,
        }));

      console.log("Saving showcase images:", showcaseData);

      const response = await postApiClient(
        "dashboard/designhouse/update-showcase",
        {
          showcase_images: showcaseData,
        },
      );

      console.log("Showcase images updated successfully:", response);
      toast.success("Showcase images updated successfully!", {
        toastId: "showcase_images_updated_success",
      });

      // Clear the showcaseImg array as they are now saved
      setShowcaseImg([]);

      // Refresh the profile data to show updated carousel images
      await fetchDesignHouseProfile();
    } catch (error: any) {
      console.error("Failed to update showcase images:", error);
      toast.error("Failed to update showcase images. Please try again.", {
        toastId: "showcase_images_update_error",
      });
    } finally {
      setSavingShowcase(false);
    }
  };

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

      console.log("Fetched profile data:", data);
      // Populate form fields with fetched data if available
      if (data) {
        setDesignHouseName(data.dh.name);
        setSlug(data.dh.slug);
        setDesignHouseId(data.dh_profile.id);
        setBusinessEmail(data.dh.primary_email || "");
        setSecondaryEmail(data.dh.secondary_email || "");
        setMobileCode(data.dh.mobileCode || "+91");
        setMobileNumber(data.dh.primary_phone || "");
        setSecondaryPhone(data.dh.secondary_phone || "");
        setWebsite(data.dh.website || "");
        setDescription(data.dh.description || "");
        setAddressLine1(data.dh.address_line1 || "");
        setAddressLine2(data.dh.address_line1 || "");
        setCity(data.dh.city || "");
        setState(data.dh.state || "");
        setCountry(data.dh.country || "");
        setPostalCode(data.dh.postal_code || "");
        setMinimumOrderValue(data.dh.minimum_order_value || "");
        setLeadTimeDays(data.dh.lead_time_days || "");
        setBaseInCity(data.dh_profile.based_in_city || "");
        setCaption(data.dh_profile.caption || "");

        setShortBio(data.dh_profile.bio || "");
        setHallmark(data.dh_profile.hallmarks);
        setPiecesBio(data.dh_profile.pieces_bio || "");
        const L = data.dh_profile.logo;

        if (L) {
          const LURL = L ? `${AWS_CDN_URL}/${L}` : "";
          setLogo(LURL);
        }

        const B = data.dh_profile.bio_image;
        if (B) {
          const BURL = B ? `${AWS_CDN_URL}/${B}` : "";
          setBioImage(BURL);
        }

        //setThumbnailImage
        const T = data.dh_profile.thumbnail_image;

        if (T) {
          const TURL = T ? `${AWS_CDN_URL}/${T}` : "";
          setThumbnailImage(TURL);
        }

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

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

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

        // Populate team members if available
        if (data.artisan && Array.isArray(data.artisan)) {
          setTeam(
            data.artisan.map((member: any, index: number) => ({
              id: member.id || Date.now() + index,
              name: member.name || "",
              role: member.role || "",
              hourly_rate: member.hourly_rate || "",
              years_of_experience: member.years_of_experience || "",
              availability_status: member.availability_status || "Available",
              bio: member.bio || "",
              artisan_profile_photo: member.artisan_profile_photo || "",
              imagePreview: member.artisan_profile_photo
                ? `${AWS_CDN_URL}/${member.artisan_profile_photo}`
                : "",
            })),
          );
        }

        // Populate social share images if available
        if (data.dh_profile) {
          setSocialShareImages({
            x: data.dh_profile.x
              ? `${AWS_CDN_URL}/${data.dh_profile.x}`
              : "https://dummyimage.com/400x200/0fffff/484fb3&text=X+Share+Image",
            facebook: data.dh_profile.facebook
              ? `${AWS_CDN_URL}/${data.dh_profile.facebook}`
              : "https://dummyimage.com/400x200/0fffff/484fb3&text=Facebook+Share+Image",
            linkedin: data.dh_profile.linkedin
              ? `${AWS_CDN_URL}/${data.dh_profile.linkedin}`
              : "https://dummyimage.com/400x200/0fffff/484fb3&text=LinkedIn+Share+Image",
            pinterest: data.dh_profile.pinterest
              ? `${AWS_CDN_URL}/${data.dh_profile.pinterest}`
              : "https://dummyimage.com/400x200/0fffff/484fb3&text=Pinterest+Share+Image",
            whatsapp: data.dh_profile.whatsapp
              ? `${AWS_CDN_URL}/${data.dh_profile.whatsapp}`
              : "https://dummyimage.com/400x200/0fffff/484fb3&text=WhatsApp+Share+Image",
          });
        }
      }
    } 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">Design House</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={`/design-houses/${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 Design House
                </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="Design House 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="email"
                    id="dh_business_email"
                    label="Primary Email"
                    require={true}
                    value={businessEmail}
                    onChange={(e: any) => setBusinessEmail(e.target.value)}
                  />
                  <FormInput
                    type="email"
                    id="dh_secondary_email"
                    label="Secondary Email"
                    require={false}
                    value={secondaryEmail}
                    onChange={(e: any) => setSecondaryEmail(e.target.value)}
                  />
                  <div className="mt-8 md:mt-0">
                    <MobileNumber
                      mobileCode={mobileCode}
                      setMobileCode={setMobileCode}
                      mobileNumber={mobileNumber}
                      setMobileNumber={setMobileNumber}
                    />
                  </div>
                  <FormInput
                    type="text"
                    id="dh_secondary_phone"
                    label="Secondary Phone"
                    require={false}
                    value={secondaryPhone}
                    onChange={(e: any) => setSecondaryPhone(e.target.value)}
                  />
                  <FormInput
                    type="text"
                    id="dh_website"
                    label="Website"
                    require={false}
                    value={website}
                    onChange={(e: any) => setWebsite(e.target.value)}
                    placeholder="https://yourwebsite.com"
                  />
                  <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="number"
                    id="dh_minimum_order_value"
                    label="Minimum Order Value"
                    require={false}
                    value={minimumOrderValue}
                    onChange={(e: any) => setMinimumOrderValue(e.target.value)}
                    placeholder="Enter minimum order value"
                  />
                  <FormInput
                    type="number"
                    id="dh_lead_time_days"
                    label="Lead Time (Days)"
                    require={false}
                    value={leadTimeDays}
                    onChange={(e: any) => setLeadTimeDays(e.target.value)}
                    placeholder="Enter lead time in days"
                  />
                </div>

                <div>
                  <h4 className="med">Description</h4>
                  <TextArea
                    label=""
                    name="dh_description"
                    maxLength={1000}
                    placeholder="Tell us something about your design house..."
                    showLimitMessage={true}
                    value={description}
                    onChange={(e) => setDescription(e.target.value)}
                    required={false}
                  />
                </div>

                <div>
                  <h4 className="med">Address Information</h4>
                  <div className="grid grid-cols-1 gap-5 md:grid-cols-2 md:gap-10">
                    <FormInput
                      type="text"
                      id="dh_address_line_1"
                      label="Address Line 1"
                      require={false}
                      value={addressLine1}
                      onChange={(e: any) => setAddressLine1(e.target.value)}
                      placeholder="Street address, building number"
                    />
                    <FormInput
                      type="text"
                      id="dh_address_line_2"
                      label="Address Line 2"
                      require={false}
                      value={addressLine2}
                      onChange={(e: any) => setAddressLine2(e.target.value)}
                      placeholder="Apartment, suite, unit, etc."
                    />
                    <FormInput
                      type="text"
                      id="dh_city"
                      label="City"
                      require={false}
                      value={city}
                      onChange={(e: any) => setCity(e.target.value)}
                    />
                    <FormInput
                      type="text"
                      id="dh_state"
                      label="State/Province"
                      require={false}
                      value={state}
                      onChange={(e: any) => setState(e.target.value)}
                    />
                    <FormInput
                      type="text"
                      id="dh_country"
                      label="Country"
                      require={false}
                      value={country}
                      onChange={(e: any) => setCountry(e.target.value)}
                    />
                    <FormInput
                      type="text"
                      id="dh_postal_code"
                      label="Postal Code"
                      require={false}
                      value={postalCode}
                      onChange={(e: any) => setPostalCode(e.target.value)}
                    />
                  </div>
                </div>

                <div>
                  <h4 className="med">Hallmark</h4>
                  <TextArea
                    label=""
                    name="dh_hallmark"
                    maxLength={500}
                    placeholder="Tell us something about your design house hallmark..."
                    showLimitMessage={true}
                    value={hallmark}
                    onChange={(e) => setHallmark(e.target.value)}
                    required={true}
                  />
                </div>
                <div>
                  <h4 className="med">Short 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>
                  <h4 className="med">Pieces Bio</h4>
                  <TextArea
                    label=""
                    name="dh_pieces_bio"
                    maxLength={255}
                    placeholder="Tell us something about your design house pieces bio..."
                    showLimitMessage={true}
                    value={piecesBio}
                    onChange={(e) => setPiecesBio(e.target.value)}
                    required={true}
                  />
                </div>
                <div className="flex w-full md:w-[30%]">
                  <FormButton
                    id="btn_save_design_house"
                    label={
                      savingDesignHouse ? "Saving..." : "Save Design House"
                    }
                    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">
                  Design House 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">Logo</p>
                  <div>
                    <Image
                      src={logo}
                      width={128}
                      height={128}
                      alt="logo"
                      className="w-[128px]"
                    />
                  </div>
                  <div className="flex flex-row gap-4">
                    <button
                      type="button"
                      onClick={() => handleBrandingImageRemove("logo")}
                      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("logo", file);
                        }}
                      />
                      {savingBranding ? "Processing..." : "Change"}
                    </label>
                  </div>
                </div>
                <div className="flex flex-col gap-1">
                  <p className="label">Bio image</p>
                  <div>
                    <Image
                      src={bioImage}
                      width={128}
                      height={128}
                      alt="bio image"
                      className="w-[128px]"
                    />
                  </div>
                  <div className="flex flex-row gap-4">
                    <button
                      type="button"
                      onClick={() => handleBrandingImageRemove("bio_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("bio_image", file);
                        }}
                      />
                      {savingBranding ? "Processing..." : "Change"}
                    </label>
                  </div>
                </div>
                <div className="flex flex-col gap-1">
                  <p className="label">Thumbnail image</p>
                  <div>
                    <Image
                      src={thumbnailImage}
                      width={128}
                      height={128}
                      alt="thumbnail image"
                      className="w-[128px]"
                    />
                  </div>
                  <div className="flex flex-row gap-4">
                    <button
                      type="button"
                      onClick={() =>
                        handleBrandingImageRemove("thumbnail_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("thumbnail_image", 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="Background left"
                      value={hero_bg_from || ""}
                      onChange={(color: any) => setHeroBgFrom(color)}
                    />
                    <ColorPicker
                      id="hero_bg_via"
                      label="Background Middle"
                      value={hero_bg_via || ""}
                      onChange={(color: any) => setHeroBgVia(color)}
                    />
                    <ColorPicker
                      id="hero_bg_4"
                      label="Background right"
                      value={hero_bg_to || ""}
                      onChange={(color: any) => setHeroBgTo(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})`,
                      //background: `linear-gradient(to right, #32b2c3, #70d7aa, #00e043)`,
                      color: `${hexcodeforBg}`,
                    }}
                  >
                    <div className="flex flex-col text-center">
                      <h3>{designHouseName || "Placeholder Design House Name"}</h3>
                      <p className="text-xs">{baseInCity || "Placeholder Location"}</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 style
                  </div>
                  <div className="mt-4 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) Meet the team text color. \n3) Button text color. \n4) Intro highlight text color. \n5) Showcase background color. \n6) Featured piece background color.`}>
                        <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}`,
                      //backgroundColor: "#d6ffef",
                      //color: "#001a2e",
                    }}
                  >
                    <div>
                     {shortBio || "Placeholder short bio"}
                    </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">
                    Other color styles
                  </div>
                  <div className="grid grid-cols-2 gap-4 md:grid-cols-3">
                    <div className="flex flex-row gap-1">
                      <ColorPicker
                        id="primary_color"
                        label="Footer Color"
                        value={primary_color}
                        onChange={(color: any) => setPrimaryColor(color)}
                      />
                    </div>
                    <div className="flex flex-row gap-1">
                      <ColorPicker
                        id="secondary_color"
                        label="Bio bg Color 1"
                        value={secondary_color}
                        onChange={(color: any) => setSecondaryColor(color)}
                      />
                    </div>
                    <div className="flex flex-row gap-1">
                      <ColorPicker
                        id="highlight_color"
                        label="Bio bg Color 2"
                        value={highlight_color}
                        onChange={(color: any) => setHighlightColor(color)}
                      />
                      <div title="Also apply to meet the team bg color">
                        <i className="icon-[mage--message-info-round-fill] bg-gray-500"></i>
                      </div>
                    </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">
                    Button/Link style
                  </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="button_color"
                        label="Button background Color"
                        value={button_color}
                        onChange={(color: any) => setButtonColor(color)}
                      />
                      <div title={`Also applies to \n1) Hallmark border color. \n2) Hallmark hover bg color.\n3) Button hover text color.`}>
                        <i className="icon-[mage--message-info-round-fill] bg-gray-500"></i>
                      </div>
                    </div>
                  </div>
                  <div
                    className="inline-flex max-w-32 items-center justify-center p-3 align-middle"
                    style={{
                      backgroundColor: `${button_color}`,
                      color: `${hexcodeforBg}`,
                    }}
                  >
                    Button
                  </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>

            {/* Social Share Images Section */}
            <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">
                  Social Share Images
                </div>
              </div>
              <div className="grid grid-cols-1 gap-5 md:grid-cols-2 md:gap-10 lg:grid-cols-3 xl:grid-cols-5">
                {/* X (Twitter) Share Image */}
                <div className="flex flex-col gap-1">
                  <p className="label">X (Twitter)</p>
                  <div>
                    <Image
                      src={socialShareImages.x}
                      width={200}
                      height={100}
                      alt="X share image"
                      className="h-[100px] w-[200px] rounded object-cover"
                    />
                  </div>
                  <div className="flex flex-row gap-2">
                    <button
                      type="button"
                      onClick={() => handleSocialShareImageRemove("x")}
                      disabled={savingSocialShares}
                      className="btn-link text-xs disabled:opacity-50"
                    >
                      {savingSocialShares ? "Processing..." : "Remove"}
                    </button>
                    <label className="btn-link cursor-pointer text-xs">
                      <input
                        type="file"
                        accept="image/*"
                        className="hidden"
                        disabled={savingSocialShares}
                        onChange={(e) => {
                          const file = e.target.files?.[0];
                          if (file) handleSocialShareImageUpload("x", file);
                        }}
                      />
                      {savingSocialShares ? "Processing..." : "Change"}
                    </label>
                  </div>
                </div>

                {/* Facebook Share Image */}
                <div className="flex flex-col gap-1">
                  <p className="label">Facebook</p>
                  <div>
                    <Image
                      src={socialShareImages.facebook}
                      width={200}
                      height={100}
                      alt="Facebook share image"
                      className="h-[100px] w-[200px] rounded object-cover"
                    />
                  </div>
                  <div className="flex flex-row gap-2">
                    <button
                      type="button"
                      onClick={() => handleSocialShareImageRemove("facebook")}
                      disabled={savingSocialShares}
                      className="btn-link text-xs disabled:opacity-50"
                    >
                      {savingSocialShares ? "Processing..." : "Remove"}
                    </button>
                    <label className="btn-link cursor-pointer text-xs">
                      <input
                        type="file"
                        accept="image/*"
                        className="hidden"
                        disabled={savingSocialShares}
                        onChange={(e) => {
                          const file = e.target.files?.[0];
                          if (file)
                            handleSocialShareImageUpload("facebook", file);
                        }}
                      />
                      {savingSocialShares ? "Processing..." : "Change"}
                    </label>
                  </div>
                </div>

                {/* LinkedIn Share Image */}
                <div className="flex flex-col gap-1">
                  <p className="label">LinkedIn</p>
                  <div>
                    <Image
                      src={socialShareImages.linkedin}
                      width={200}
                      height={100}
                      alt="LinkedIn share image"
                      className="h-[100px] w-[200px] rounded object-cover"
                    />
                  </div>
                  <div className="flex flex-row gap-2">
                    <button
                      type="button"
                      onClick={() => handleSocialShareImageRemove("linkedin")}
                      disabled={savingSocialShares}
                      className="btn-link text-xs disabled:opacity-50"
                    >
                      {savingSocialShares ? "Processing..." : "Remove"}
                    </button>
                    <label className="btn-link cursor-pointer text-xs">
                      <input
                        type="file"
                        accept="image/*"
                        className="hidden"
                        disabled={savingSocialShares}
                        onChange={(e) => {
                          const file = e.target.files?.[0];
                          if (file)
                            handleSocialShareImageUpload("linkedin", file);
                        }}
                      />
                      {savingSocialShares ? "Processing..." : "Change"}
                    </label>
                  </div>
                </div>

                {/* Pinterest Share Image */}
                <div className="flex flex-col gap-1">
                  <p className="label">Pinterest</p>
                  <div>
                    <Image
                      src={socialShareImages.pinterest}
                      width={200}
                      height={100}
                      alt="Pinterest share image"
                      className="h-[100px] w-[200px] rounded object-cover"
                    />
                  </div>
                  <div className="flex flex-row gap-2">
                    <button
                      type="button"
                      onClick={() => handleSocialShareImageRemove("pinterest")}
                      disabled={savingSocialShares}
                      className="btn-link text-xs disabled:opacity-50"
                    >
                      {savingSocialShares ? "Processing..." : "Remove"}
                    </button>
                    <label className="btn-link cursor-pointer text-xs">
                      <input
                        type="file"
                        accept="image/*"
                        className="hidden"
                        disabled={savingSocialShares}
                        onChange={(e) => {
                          const file = e.target.files?.[0];
                          if (file)
                            handleSocialShareImageUpload("pinterest", file);
                        }}
                      />
                      {savingSocialShares ? "Processing..." : "Change"}
                    </label>
                  </div>
                </div>

                {/* WhatsApp Share Image */}
                <div className="flex flex-col gap-1">
                  <p className="label">WhatsApp</p>
                  <div>
                    <Image
                      src={socialShareImages.whatsapp}
                      width={200}
                      height={100}
                      alt="WhatsApp share image"
                      className="h-[100px] w-[200px] rounded object-cover"
                    />
                  </div>
                  <div className="flex flex-row gap-2">
                    <button
                      type="button"
                      onClick={() => handleSocialShareImageRemove("whatsapp")}
                      disabled={savingSocialShares}
                      className="btn-link text-xs disabled:opacity-50"
                    >
                      {savingSocialShares ? "Processing..." : "Remove"}
                    </button>
                    <label className="btn-link cursor-pointer text-xs">
                      <input
                        type="file"
                        accept="image/*"
                        className="hidden"
                        disabled={savingSocialShares}
                        onChange={(e) => {
                          const file = e.target.files?.[0];
                          if (file)
                            handleSocialShareImageUpload("whatsapp", file);
                        }}
                      />
                      {savingSocialShares ? "Processing..." : "Change"}
                    </label>
                  </div>
                </div>
              </div>
              <div className="text-sm text-gray-600">
                <p>Recommended image sizes:</p>
                <ul className="mt-1 list-inside list-disc text-xs">
                  <li>X (Twitter): 1200 x 630 pixels</li>
                  <li>Facebook: 1200 x 630 pixels</li>
                  <li>LinkedIn: 1200 x 630 pixels</li>
                  <li>Pinterest: 1000 x 1500 pixels (2:3 ratio)</li>
                  <li>WhatsApp: 1200 x 630 pixels</li>
                </ul>
              </div>
            </div>
            <form onSubmit={handleSaveShowcase}>
              <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 6-20 images per upload batch that cover:
                  </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) => (
                          console.log(
                            "Image URL:",
                            `${AWS_CDN_URL}/${carouselImg}`,
                          ),
                          (
                            <div key={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"
                              />
                              {/* Remove icon - show on hover */}
                              <button
                                type="button"
                                onClick={() =>
                                  deleteShowcaseImage(carouselImg.id)
                                }
                                className="absolute top-2 right-2 rounded-full bg-red-500 p-1 text-white opacity-0 transition-opacity duration-200 group-hover:opacity-100 hover:bg-red-600"
                                title="Remove image"
                              >
                                <svg
                                  width="16"
                                  height="16"
                                  viewBox="0 0 24 24"
                                  fill="none"
                                  xmlns="http://www.w3.org/2000/svg"
                                >
                                  <path
                                    d="M18 6L6 18M6 6l12 12"
                                    stroke="currentColor"
                                    strokeWidth="2"
                                    strokeLinecap="round"
                                    strokeLinejoin="round"
                                  />
                                </svg>
                              </button>
                            </div>
                          )
                        ),
                      )}
                    </div>
                  </div>
                )}

                {/* Upload new images section - hide if 20 or more images */}
                {carouselImage.length < 20 && (
                  <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>
                )}

                {/* Add new image button - hide if 20 or more images */}
                {carouselImage.length < 20 && (
                  <div>
                    <button
                      type="button"
                      onClick={handleAddShowcase}
                      disabled={
                        showcaseImg.length >= showcaseLimit ||
                        carouselImage.length + showcaseImg.length >= 20
                      }
                      className={`flex px-2 py-2 text-xs ${
                        showcaseImg.length >= showcaseLimit ||
                        carouselImage.length + showcaseImg.length >= 20
                          ? "bg-gray-300 text-gray-600"
                          : "btn-outline"
                      }`}
                    >
                      {carouselImage.length + showcaseImg.length >= 20
                        ? "You have reached the limit (20 images max)"
                        : showcaseImg.length >= showcaseLimit
                          ? "You have reached the batch limit"
                          : "Add New Image"}
                    </button>
                  </div>
                )}

                {/* Message when limit is reached */}
                {carouselImage.length >= 20 && (
                  <div className="rounded-lg border border-amber-200 bg-amber-50 p-4">
                    <p className="text-sm text-amber-800">
                      <strong>Upload limit reached!</strong> You have uploaded
                      the maximum of 20 showcase images. To add new images,
                      please remove some existing ones first using the remove
                      button that appears when you hover over each image.
                    </p>
                  </div>
                )}
              </div>
            </form>
            <div className="mt-5 flex flex-col gap-5 bg-white p-5 md:gap-10 md:p-10">
              <div>
                <h4 className="med">My Team</h4>
                <p className="label">
                  You can add up to {teamLimit} members. Current:{" "}
                  {team.length + newMembers.length}
                </p>
              </div>

              {/* Display existing team members */}
              {team.length > 0 && (
                <div>
                  <h5 className="mb-3 font-medium">Current Team Members</h5>
                  <div className="mb-5 grid grid-cols-1 gap-5 md:grid-cols-2">
                    {team.map((member, index) => (
                      <div
                        key={member.id}
                        className="flex flex-col gap-3 rounded border bg-gray-50 p-4"
                      >
                        <div className="flex items-center gap-3">
                          {member.imagePreview ||
                          member.artisan_profile_photo ? (
                            <Image
                              src={
                                member.imagePreview ||
                                `${AWS_CDN_URL}/${member.artisan_profile_photo}`
                              }
                              width={60}
                              height={60}
                              alt={member.name}
                              className="h-15 w-15 rounded-full border object-cover"
                            />
                          ) : (
                            <div className="flex h-15 w-15 items-center justify-center rounded-full bg-gray-200">
                              <span className="text-xs text-gray-500">
                                No Image
                              </span>
                            </div>
                          )}
                          <div className="flex-1">
                            <h6 className="text-lg font-medium">
                              {member.name || "Unnamed Member"}
                            </h6>
                            <p className="text-sm text-gray-600">
                              {member.role}
                            </p>
                          </div>
                        </div>
                        <div className="grid grid-cols-2 gap-2 text-sm">
                          <div>
                            <span className="font-medium">Rate:</span> $
                            {member.hourly_rate}/hr
                          </div>
                          <div>
                            <span className="font-medium">Experience:</span>{" "}
                            {member.years_of_experience} years
                          </div>
                          <div className="col-span-2">
                            <span className="font-medium">Status:</span>
                            <span
                              className={`ml-1 rounded px-2 py-1 text-xs ${
                                member.availability_status === "Available"
                                  ? "bg-green-100 text-green-800"
                                  : member.availability_status === "Busy"
                                    ? "bg-yellow-100 text-yellow-800"
                                    : "bg-red-100 text-red-800"
                              }`}
                            >
                              {member.availability_status}
                            </span>
                          </div>
                        </div>
                        {member.bio && (
                          <div className="text-sm">
                            <span className="font-medium">Bio:</span>{" "}
                            {member.bio}
                          </div>
                        )}
                        <button
                          type="button"
                          onClick={() => handleRemoveMember(member.id)}
                          className="self-start text-sm font-medium text-red-600 underline underline-offset-4"
                        >
                          Remove Member
                        </button>
                      </div>
                    ))}
                  </div>
                </div>
              )}

              {/* Add new team members form */}
              {newMembers.length > 0 && (
                <div>
                  <h5 className="mb-3 font-medium">Add New Team Members</h5>
                  <div className="flex flex-col gap-5">
                    {newMembers.map((member, index) => (
                      <div
                        key={member.id}
                        className="flex flex-col gap-2 bg-gray-100 p-5"
                      >
                        <div>
                          {member.imagePreview ? (
                            <Image
                              src={member.imagePreview}
                              width={100}
                              height={100}
                              alt="Preview"
                              className="h-24 w-24 rounded-full border object-cover"
                            />
                          ) : (
                            <div className="flex h-24 w-24 items-center justify-center rounded-full bg-gray-200">
                              <span className="text-sm text-gray-500">
                                No Image
                              </span>
                            </div>
                          )}
                          <input
                            type="file"
                            accept="image/*"
                            onChange={(e: ChangeEvent<HTMLInputElement>) =>
                              e.target.files?.[0] &&
                              handleNewMemberImageChange(
                                member.id,
                                e.target.files[0],
                              )
                            }
                          />
                        </div>
                        <div className="mt-5 grid grid-cols-1 gap-5 md:grid-cols-2">
                          <div>
                            <label className="mb-1 block text-sm font-medium text-gray-700">
                              Full name <span className="text-red-500">*</span>
                            </label>
                            <input
                              type="text"
                              placeholder="Enter full name"
                              value={member.name}
                              onChange={(e) =>
                                handleNewMemberChange(
                                  member.id,
                                  "name",
                                  e.target.value,
                                )
                              }
                              className="w-full rounded border p-2"
                              required
                            />
                          </div>
                          <div>
                            <label className="mb-1 block text-sm font-medium text-gray-700">
                              Role <span className="text-red-500">*</span>
                            </label>
                            <select
                              value={member.role}
                              onChange={(e) =>
                                handleNewMemberChange(
                                  member.id,
                                  "role",
                                  e.target.value,
                                )
                              }
                              className="w-full rounded border p-2"
                              required
                            >
                              <option value="">Select Role</option>
                              {roleOptions.map((option) => (
                                <option key={option.value} value={option.value}>
                                  {option.label}
                                </option>
                              ))}
                            </select>
                          </div>
                          <div>
                            <label className="mb-1 block text-sm font-medium text-gray-700">
                              Hourly Rate
                            </label>
                            <input
                              type="text"
                              placeholder="Enter hourly rate"
                              value={member.hourly_rate}
                              onChange={(e) =>
                                handleNewMemberChange(
                                  member.id,
                                  "hourly_rate",
                                  e.target.value,
                                )
                              }
                              className="w-full rounded border p-2"
                            />
                          </div>
                          <div>
                            <label className="mb-1 block text-sm font-medium text-gray-700">
                              Years of Experience
                            </label>
                            <input
                              type="text"
                              placeholder="Enter years of experience"
                              value={member.years_of_experience}
                              onChange={(e) =>
                                handleNewMemberChange(
                                  member.id,
                                  "years_of_experience",
                                  e.target.value,
                                )
                              }
                              className="w-full rounded border p-2"
                            />
                          </div>
                          <div className="md:col-span-2">
                            <label className="mb-1 block text-sm font-medium text-gray-700">
                              Availability Status
                            </label>
                            <select
                              value={member.availability_status}
                              onChange={(e) =>
                                handleNewMemberChange(
                                  member.id,
                                  "availability_status",
                                  e.target.value,
                                )
                              }
                              className="w-full rounded border p-2"
                            >
                              {statusOptions.map((option) => (
                                <option key={option.value} value={option.value}>
                                  {option.label}
                                </option>
                              ))}
                            </select>
                          </div>
                        </div>
                        <div className="flex w-full flex-col">
                          <label className="mb-1 block text-sm font-medium text-gray-700">
                            Bio
                          </label>
                          <textarea
                            placeholder="Enter bio..."
                            value={member.bio}
                            onChange={(e) =>
                              handleNewMemberChange(
                                member.id,
                                "bio",
                                e.target.value,
                              )
                            }
                            className="h-24 w-full rounded border p-2"
                            rows={3}
                          />
                        </div>
                        <div className="flex w-full flex-col">
                          <button
                            type="button"
                            onClick={() => handleRemoveNewMember(member.id)}
                            className="text-sm font-medium text-amber-600 underline underline-offset-4"
                          >
                            Remove
                          </button>
                        </div>
                      </div>
                    ))}
                  </div>
                </div>
              )}

              <div>
                <button
                  type="button"
                  onClick={handleAddMember}
                  disabled={team.length + newMembers.length >= teamLimit}
                  className={`flex px-2 py-2 text-xs ${team.length + newMembers.length >= teamLimit ? "bg-gray-300 text-gray-600" : "btn-outline"}`}
                >
                  {team.length + newMembers.length >= teamLimit
                    ? "You have reached the limit"
                    : "Add New Member"}
                </button>
              </div>
              <div className="flex w-full py-5 md:w-[30%]">
                <FormButton
                  id="btn_save_my_team"
                  label={savingTeam ? "Saving..." : "Save my team"}
                  type="button"
                  color="gray"
                  hairline=""
                  disabled={
                    savingTeam ||
                    newMembers.length === 0 ||
                    newMembers.some((member) => !member.name || !member.role)
                  }
                  onClick={handleSaveNewMembers}
                />
              </div>
              {newMembers.length > 0 &&
                newMembers.some((member) => !member.name || !member.role) && (
                  <div className="text-sm text-red-600">
                    Please fill in the required fields (Name and Role) for all
                    team members before saving.
                  </div>
                )}
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}
