"use client";

import React, { useState, useEffect, useCallback } from "react";
import { Copy, Search, X, Check } from "react-feather";
import apiClient from "@/lib/apiClient";
import "../../../styles/general-style.css";
import { format } from "date-fns";
import DateRangeFilter from "@/components/DateRangeFilter";
import { logger } from "@/lib/logger";

// Types for the API responses
interface Platform {
  id: number;
  name: string;
  platform_logo: string;
  is_active: boolean;
  created_at: string;
}

interface StoreFrontUrl {
  platform_id: number;
  platform_name: string;
  platform_logo: string;
  store_front_url: string;
}

interface PlatformsResponse {
  success: boolean;
  data: {
    platforms: Platform[];
    total_count: number;
  };
}

interface StoreFrontUrlsResponse {
  success: boolean;
  data: {
    partner_id: number;
    store_front_urls: StoreFrontUrl[];
    total_count: number;
  };
}

interface PlatformItem {
  image_url: string | null;
  source_url: string;
  deeplink_url: string;
  short_url: string;
  product_name: string;
  domain: string;
  created_at: string;
}

interface PaginationInfo {
  currentPage: number;
  totalPages: number;
  totalItems: number;
  itemsPerPage: number;
  startItem: number;
  endItem: number;
}

// Format date as YYYY-MM-DD
const formatDate = (date: Date) => {
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, "0");
  const day = String(date.getDate()).padStart(2, "0");
  return `${year}-${month}-${day}`;
};

// Calculate default last 7 days range
const today = new Date();
const end = new Date(today);
end.setDate(today.getDate());
const start = new Date(end);
start.setDate(end.getDate() - 6);
const LOGO_API_BASE =
  process.env.NODE_ENV === "production"
    ? "https://api.theagency.com"
    : "https://devapi.theagency.com";
export default function MyLinks() {
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [platforms, setPlatforms] = useState<Platform[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  // const [platformUrls, setPlatformUrls] = useState<Record<string, string>>({});
  const [modalPlatformUrls, setModalPlatformUrls] = useState<
    Record<string, string>
  >({});
  const [dateRange, setDateRange] = useState<{
    startDate: string;
    endDate: string;
  }>({
    startDate: formatDate(start),
    endDate: formatDate(end),
  });
  const [submitting, setSubmitting] = useState(false);
  const [copiedButtons, setCopiedButtons] = useState<Set<string>>(new Set());
  const [searchTerm, setSearchTerm] = useState("");
  const [selectedPlatform, setSelectedPlatform] = useState<string>("all");
  const [platformData, setPlatformData] = useState<{
    recent: PlatformItem[];
  }>({ recent: [] });
  const [searchLoading, setSearchLoading] = useState(false);
  const [pagination, setPagination] = useState<PaginationInfo>({
    currentPage: 1,
    totalPages: 1,
    totalItems: 0,
    itemsPerPage: 10,
    startItem: 0,
    endItem: 0,
  });
  const [failedImages, setFailedImages] = useState<Set<string>>(new Set());

  // Convert relative image URLs to absolute URLs
  const makeAbsoluteUrl = (url: string, domain?: string) => {
    if (!url) return "";
    // Already absolute
    if (url.startsWith("http://") || url.startsWith("https://")) return url;
    // If domain is provided, make relative URL absolute
    if (domain && url.startsWith("/")) {
      // Remove "www." for safety if needed
      const cleanDomain = domain.replace(/^www\./, "");
      return `https://${cleanDomain}${url}`;
    }
    return url; // fallback if no domain
  };

  // Function to fetch platforms and storefront URLs

const getLogoUrl = (domainOrPlatform: string | Platform): string => {
  // :one: If string is passed (domain)
  if (typeof domainOrPlatform === "string") {
    const cleanDomain = domainOrPlatform
      .replace(/^https?:\/\//, "")
      .replace(/^www\./, "")
      .split("/")[0];

    return `${LOGO_API_BASE}/logo/${cleanDomain}`;
  }

  // :two: If object missing
  if (!domainOrPlatform) return "/img/placeholder.png";

  // :three: platform_logo exists → try to extract domain
  if (domainOrPlatform.platform_logo?.trim()) {
    try {
      const url = new URL(domainOrPlatform.platform_logo);
      return `${LOGO_API_BASE}/logo/${url.hostname}`;
    } catch (err) {
      logger.error("Failed to parse platform_logo:", err);
    }
  }

  // :four: NAME fallback (bestbuy → bestbuy.com)
  const domainFromName = `${domainOrPlatform.name.toLowerCase()}.com`;
  return `${LOGO_API_BASE}/logo/${domainFromName}`;
};

  // Handle image loading errors
  const handleImageError = useCallback((imageUrl: string) => {
    setFailedImages((prev) => new Set(prev).add(imageUrl));
  }, []);

  // Get the appropriate image source with fallback logic
  const getImageSource = useCallback(
    (item: PlatformItem): string => {
      //
      // Use absolute image_url first
      if (item.image_url && !failedImages.has(item.image_url)) {
        return makeAbsoluteUrl(item.image_url, item.domain);
      }

      // If image_url failed or doesn't exist, use getLogoUrl
      return getLogoUrl(item.domain);
    },
    [failedImages]
  );

  const fetchData = async () => {
    try {
      setLoading(true);
      setError(null);

      // First fetch platforms
      const platformsResponse = await apiClient.get<PlatformsResponse>(
        "/accounts/platforms"
      );

      if (platformsResponse.data.success) {
        setPlatforms(platformsResponse.data.data.platforms);

        // Then fetch storefront URLs
        const storeFrontUrlsResponse =
          await apiClient.get<StoreFrontUrlsResponse>(
            "/accounts/store-front-urls"
          );

        if (storeFrontUrlsResponse.data.success) {
          // Initialize platformUrls with fetched data
          const initialUrls: Record<string, string> = {};
          platformsResponse.data.data.platforms.forEach((platform) => {
            const storeFrontUrl =
              storeFrontUrlsResponse.data.data.store_front_urls.find(
                (url) => url.platform_id === platform.id
              );
            initialUrls[platform.name.toLowerCase()] =
              storeFrontUrl?.store_front_url || "";
          });
          // setPlatformUrls(initialUrls);
        }
      }
    } catch (err) {
      logger.error("Failed to load platforms and storefront URLs:", err);
      setError("Failed to load platforms and storefront URLs");
    } finally {
      setLoading(false);
    }
  };

  // Function to fetch platform-specific data
  const fetchPlatformData = async (
    platform: string,
    search: string = "",
    startDate?: string,
    endDate?: string,
    page: number = 1
  ) => {
    try {
      setSearchLoading(true);
      const params = new URLSearchParams();

      params.append("page", page.toString());
      params.append("limit", pagination.itemsPerPage.toString());

      if (platform && platform !== "all") {
        params.append("domain", platform);
      }
      if (search) {
        params.append("search", search);
      }
      if (startDate && endDate) {
        params.append("start_date", startDate);
        params.append("end_date", endDate);
      }

      const recentResponse = await apiClient.get(
        `/accounts/affiliate-links?${params.toString()}`
      );

      const recentData = recentResponse.data;

      if (recentData.success) {
        const { links, total_count } = recentData.data;

        setPlatformData({ recent: links });
        // Clear failed images when new data is fetched
        setFailedImages(new Set());
        setPagination((prev) => {
          const startItem = (page - 1) * prev.itemsPerPage + 1;
          const endItem = Math.min(page * prev.itemsPerPage, total_count);

          return {
            ...prev,
            currentPage: page,
            totalPages: Math.ceil(total_count / prev.itemsPerPage),
            totalItems: total_count,
            startItem,
            endItem,
          };
        });
      }
    } catch (error) {
      logger.error("Failed to fetch platform data:", error);
    } finally {
      setSearchLoading(false);
    }
  };


  const handlePageChange = (page: number) => {
    if (page >= 1 && page <= pagination.totalPages) {
      fetchPlatformData(
        selectedPlatform,
        searchTerm,
        dateRange.startDate,
        dateRange.endDate,
        page
      );
    }
  };

  // Handle platform selection
  const handlePlatformSelect = (platform: string) => {
    setSelectedPlatform(platform);
  };

  // Render platform cards based on selected platform and tab
  const renderPlatformCards = () => {
    // const items =
    //   productSubTab === "recent"
    //     ? platformData.recent
    //     : platformData.top_clicked;
    const items = platformData.recent || [];
    if (items.length === 0) {
      return (
        <div className="col-12 text-center py-4">
          <p className="text-muted">No items found</p>
        </div>
      );
    }

    return items.map((item, i) => (
      <div
        key={i}
        className="col-12 col-sm-12 col-md-12 col-lg-12 col-xl-12 col-xxl-12 mb-0"
      >
        <div className="platform-card my-card my-links-card card p-0">
          <div className="card-body d-md-flex d-block w-100">
            <div className="ps-md-4 card-image order-md-2">
              <div className="my-p tag-id d-flex justify-content-md-end justify-content-between"></div>
              <img
                src={getImageSource(item)}
                alt="product"
                loading="lazy"
                className="link-card-img"
                onError={() =>
                  item.image_url && handleImageError(item.image_url)
                }
              />
            </div>
            <div className="card-text order-md-1 flex-grow-1">
              <p className="platform-name fw-semibold">
                {item.domain
                  .replace(/^www\./, "")
                  .split(".")[0]
                  .toUpperCase()}
              </p>
              {item?.product_name?.trim() && (
                <p className="my-p my-pro-name">{item.product_name}</p>
              )}
              <ul className="card-ul">
                <li>
                  <p className="my-p list-name">Date Created</p>
                  <p className="my-p list-value">
                    {item.created_at
                      ? format(new Date(item.created_at), "dd-MM-yyyy hh:mm a")
                      : "-"}
                  </p>
                </li>
              </ul>
              <div className="card-btn-area">
                <button
                  onClick={() =>
                    handleCopyUrl(
                      item.short_url || item.deeplink_url || item.source_url
                    )
                  }
                  style={{ minWidth: "130px" }}
                  className="button btn-first btn-first-pink small-btn code-copy-button"
                >
                  {copiedButtons.has(
                    item.short_url || item.deeplink_url || item.source_url
                  ) ? (
                    <Check />
                  ) : (
                    <Copy />
                  )}{" "}
                  {copiedButtons.has(
                    item.short_url || item.deeplink_url || item.source_url
                  )
                    ? "Copied"
                    : " Copy Link"}
                </button>
              </div>
            </div>
          </div>
        </div>
      </div>
    ));
  };

  // Fetch platforms and storefront URLs on component mount
  useEffect(() => {
    fetchData();
    // Fetch initial platform data for Amazon
    fetchPlatformData(
      "all",
      searchTerm,
      dateRange.startDate,
      dateRange.endDate,
      1
    );
  }, []);

  // Handle escape key to close modal
  useEffect(() => {
    const handleEscapeKey = (event: KeyboardEvent) => {
      if (event.key === "Escape" && isModalOpen) {
        handleCloseModal();
      }
    };

    if (isModalOpen) {
      document.addEventListener("keydown", handleEscapeKey);
    }

    return () => {
      document.removeEventListener("keydown", handleEscapeKey);
    };
  }, [isModalOpen]);

  useEffect(() => {
    const delayDebounce = setTimeout(() => {
      if (searchTerm.length >= 3 || searchTerm.length === 0) {
        fetchPlatformData(
          selectedPlatform,
          searchTerm,
          dateRange.startDate,
          dateRange.endDate,
          1
        );
      }
    }, 500);

    return () => clearTimeout(delayDebounce);
  }, [searchTerm, selectedPlatform, dateRange]);

  const handleCloseModal = () => {
    setIsModalOpen(false);
  };

  const handleInputChange = (platform: string, value: string) => {
    setModalPlatformUrls((prev) => ({
      ...prev,
      [platform]: value,
    }));
  };

  // Validate URL format
  const isValidUrl = (url: string): boolean => {
    if (!url.trim()) return true; // Empty URLs are valid (not required)
    try {
      new URL(url);
      return true;
    } catch {
      return false;
    }
  };

  // Validate all URLs in modal
  const validateModalUrls = (): boolean => {
    for (const [, url] of Object.entries(modalPlatformUrls)) {
      if (!isValidUrl(url)) {
        return false;
      }
    }
    return true;
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();

    // Validate URLs before submitting
    if (!validateModalUrls()) {
      alert("Please enter valid URLs for the platforms you want to save.");
      return;
    }

    try {
      setSubmitting(true);

      // Prepare request data
      const requestData = {
        platforms: Object.entries(modalPlatformUrls)
          .filter(([, url]) => url.trim()) // Only include non-empty URLs
          .map(([platformName, url]) => {
            const platformId =
              platforms.find((p) => p.name.toLowerCase() === platformName)
                ?.id || 0;
            return {
              platform_id: platformId,
              store_front_url: url.trim(),
            };
          }),
      };

      // Make API call to update storefront URLs
      const response = await apiClient.put(
        "/accounts/update-store-front-urls",
        requestData
      );

      if (response.data.success) {
        // Refresh data from API
        await fetchData();
        // Close modal
        handleCloseModal();
      } else {
        throw new Error(
          response.data.message || "Failed to update storefront URLs"
        );
      }
    } catch (error) {
      alert("Failed to save storefront URLs. Please try again.");
    } finally {
      setSubmitting(false);
    }
  };

  // Get platform logo by name
  const getPlatformLogo = (platformName: string): string => {
    const platform = platforms.find(
      (p) => p.name.toLowerCase() === platformName.toLowerCase()
    );
    return platform?.platform_logo || `/img/${platformName.toLowerCase()}.svg`;
  };

  // Handle copying URL to clipboard with visual feedback
  const handleCopyUrl = async (url: string) => {
    try {
      await navigator.clipboard.writeText(url);

      // Track copied state using the url itself
      setCopiedButtons((prev) => new Set(prev).add(url));

      // Revert back to copy icon after 2 seconds
      setTimeout(() => {
        setCopiedButtons((prev) => {
          const newSet = new Set(prev);
          newSet.delete(url);
          return newSet;
        });
      }, 2000);
    } catch (error) {
      logger.error("Failed to copy URL:", error);
      // Fallback for older browsers
      const textArea = document.createElement("textarea");
      textArea.value = url;
      document.body.appendChild(textArea);
      textArea.select();
      document.execCommand("copy");
      document.body.removeChild(textArea);

      setCopiedButtons((prev) => new Set(prev).add(url));

      setTimeout(() => {
        setCopiedButtons((prev) => {
          const newSet = new Set(prev);
          newSet.delete(url);
          return newSet;
        });
      }, 2000);
    }
  };

  if (loading) {
    return (
      <div className="pcoded-main-container bg-light webContent">
        <div className="pcoded-content">
          <div
            className="d-flex flex-column justify-content-center align-items-center"
            style={{ minHeight: "400px" }}
          >
            <div
              className="spinner-border mb-2"
              role="status"
              style={{ color: "#C600BA" }}
            >
              <span className="visually-hidden">Loading...</span>
            </div>
            <div className="text-muted text-center">
              Loading your links, please wait...
            </div>
          </div>
        </div>
      </div>
    );
  }

  if (error) {
    return (
      <div className="pcoded-main-container bg-light webContent">
        <div className="pcoded-content">
          <div className="alert alert-danger m-3" role="alert">
            <div className="d-flex justify-content-between align-items-center">
              <span>{error}</span>
              <button
                onClick={() => fetchData()}
                className="btn btn-sm btn-outline-danger"
                disabled={loading}
              >
                {loading ? "Retrying..." : "Retry"}
              </button>
            </div>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className="pcoded-main-container bg-light webContent">
      <div className="pcoded-content">
        <div className="pagename-section">
          <div className="row align-items-center">
            <div className="col-xxl-5 col-xl-5 col-lg-5 col-md-5 col-sm-12 col-12 text-md-start text-center mb-md-0 mb-2">
              <h3 className="subHeading mb-0">My Links</h3>
            </div>
            <div className="col-xxl-7 col-xl-7 col-lg-7 col-md-7 col-sm-12 col-12 text-md-start text-center mb-md-0 mb-2">
              <div className="d-md-flex justify-content-md-end justify-content-center gap-2 w-100"></div>
            </div>
          </div>
        </div>
        <section className="storefront-section my-links-page my-link-page mt-3 mt-md-4 mb-3">
          <div className="card mb-3 p-3 p-md-4">
            <div className="row">
              <div className="col-12 col-sm-12 col-md-12 col-lg-12 col-xl-12 col-xxl-12 mb-3 d-lg-flex flex-lg-column justify-content-lg-end">
                <div className="d-flex flex-wrap gap-2 gap-md-3">
                  {/* Show All only if data available */}
                  {
                    platforms.length > 0 && (
                      <div
                        key="all"
                        className={`affiliate-link card p-0 ${selectedPlatform === "all" ? "active" : ""} m-0 mb-0`}
                        style={{ cursor: "pointer" }}
                        onClick={() => handlePlatformSelect("all")}
                      >
                        <a className="storeImg affiliate-btn p-0 m-0 d-flex align-items-center justify-content-center">
                          <div className="storeImg d-flex align-items-center justify-content-center m-0">
                            All
                          </div>
                        </a>
                      </div>
                    )
                  }

                  {/* Then loop through API platforms */}
                  {platforms.length === 0 ? (
                    <div className="text-center py-2">
                      <p className="text-muted mb-0 small">

                      </p>
                    </div>
                  ) : (
                    platforms.map((platform) => {
                      const platformName = platform.name.toLowerCase();
                      const isSelected = selectedPlatform === platformName;

                      return (
                        <div
                          key={platform.id}
                          className={`affiliate-link card p-0 ${isSelected ? "active" : ""
                            } m-0 mb-0`}
                          style={{ cursor: "pointer" }}
                          onClick={() => handlePlatformSelect(platformName)}
                        >
                          <a className="storeImg affiliate-btn p-0 m-0">
                            <div className="storeImg d-flex align-items-center justify-content-center m-0">
                              <img
                                src={
                                  platform.platform_logo || getLogoUrl(platform)
                                }
                                alt={`${platform.name} logo`}
                                className="m-0"
                                onError={(e) => {
                                  // If both platform_logo and first fallback fail, use logo api
                                  const clearbitUrl = getLogoUrl(platform);
                                  if (e.currentTarget.src !== clearbitUrl) {
                                    e.currentTarget.src = clearbitUrl;
                                  } else {
                                    // Final fallback
                                    e.currentTarget.src =
                                      "/img/placeholder.png";
                                    e.currentTarget.onerror = null; // Prevent infinite loop
                                  }
                                }}
                              />
                            </div>
                          </a>
                        </div>
                      );
                    })
                  )}
                </div>
              </div>
              <div className="col-12 col-sm-12 col-md-12 col-lg-12 col-xl-12 col-xxl-12 mb-3">
                <div className="search-section links-search d-flex gap-2">
                  <div className="search-input-group">
                    <input
                      type="text"
                      className="form-control form-control-light"
                      placeholder="Search by product name, URL, or keywords…"
                      value={searchTerm}
                      onChange={(e) => setSearchTerm(e.target.value)}
                    />
                    <button className="search-btn" type="button">
                      <Search />
                    </button>
                  </div>
                  <div>
                    <DateRangeFilter
                      className="p-1"
                      onApply={(range) => setDateRange(range)}
                      initialRange={dateRange}
                    />
                  </div>
                </div>
              </div>
            </div>
          </div>
          <div className="tab-content " id="nav-pro-tabContent">
            <div className="">
              <div className="platform-cards mb-3">
                <div className="card-tab">
                  <div className="tab-content " id="nav-tabContent1">
                    {/* loader */}
                    {searchLoading && (
                      <div className="col-12 d-flex justify-content-center align-items-center py-4 text-primary">
                        <span
                          style={{ color: "#C600BA" }}
                          className="spinner-border spinner-border-sm me-2"
                        ></span>
                        <span style={{ color: "#C600BA" }}>
                          Fetching your records...
                        </span>
                      </div>
                    )}
                    {/* no records found */}
                    {!searchLoading && platformData.recent.length === 0 && (
                      <div className="col-12 text-center py-4">
                        <p className="text-muted">No records found</p>
                      </div>
                    )}
                    {/* display records */}
                    {!searchLoading && platformData.recent.length > 0 && (
                      <div className="row mb-3">{renderPlatformCards()}</div>
                    )}
                    {/* pagination */}
                    {!loading &&
                      !searchLoading &&
                      platformData.recent.length > 0 && (
                        <div
                          className="d-flex flex-wrap justify-content-center align-items-center gap-2"
                          style={{ rowGap: "0.5rem" }}
                        >
                          <div
                            className="pagination-info text-muted small text-center"
                            aria-live="polite"
                          >
                            Showing {pagination.startItem} to{" "}
                            {pagination.endItem} of {pagination.totalItems}{" "}
                            entries
                          </div>
                          <div className="d-flex align-items-center gap-1">
                            <button
                              className="btn btn-outline-secondary btn-sm"
                              onClick={() =>
                                handlePageChange(pagination.currentPage - 1)
                              }
                              disabled={
                                pagination.currentPage === 1 || searchLoading
                              }
                            >
                              &lt; Prev
                            </button>
                            {pagination.currentPage}
                            <button
                              className="btn btn-outline-secondary btn-sm"
                              onClick={() =>
                                handlePageChange(pagination.currentPage + 1)
                              }
                              disabled={
                                pagination.currentPage ===
                                pagination.totalPages || searchLoading
                              }
                            >
                              Next &gt;
                            </button>
                          </div>
                        </div>
                      )}
                  </div>
                </div>
              </div>
            </div>
          </div>
        </section>
      </div>

      {/* Add Storefront URLs Modal */}
      {isModalOpen && (
        <>
          {/* Backdrop */}
          <div
            className="modal-backdrop fade show"
            style={{
              position: "fixed",
              top: 0,
              left: 0,
              width: "100vw",
              height: "100vh",
              backgroundColor: "rgba(0, 0, 0, 0.5)",
              zIndex: 1040,
              cursor: "pointer",
            }}
            onClick={handleCloseModal}
            title="Click outside to close"
          />

          {/* Modal */}
          <section
            className="modal fade my-modal show d-block"
            id="add-id-modal-1"
            style={{
              position: "fixed",
              top: 0,
              left: 0,
              width: "100vw",
              height: "100vh",
              zIndex: 1050,
            }}
            aria-hidden="false"
            onClick={handleCloseModal}
          >
            <div
              className="modal-dialog modal-dialog-centered"
              onClick={(e) => e.stopPropagation()}
            >
              <div
                className="modal-content"
                onClick={(e) => e.stopPropagation()}
              >
                <div className="modal-body">
                  <div className="modal-name mb-4 align-items-start">
                    <div>
                      <h4 className="thirdHeading mb-2">
                        Add Storefronts URLs
                      </h4>
                      <small className="mb-0">
                        Paste your storefront URLs (if any) here to sync your
                        products, boards, etc.
                      </small>
                    </div>
                    <button
                      type="button"
                      className="btn-close"
                      onClick={handleCloseModal}
                      aria-label="Close"
                      style={{ fontSize: "18px", fontWeight: "bold" }}
                    >
                      <X></X>
                    </button>
                  </div>
                  <form className="modal-form" onSubmit={handleSubmit}>
                    {loading ? (
                      <div className="text-center py-4">
                        <div
                          className="spinner-border"
                          role="status"
                          style={{ color: "#C600BA" }}
                        >
                          <span className="visually-hidden">
                            Loading platforms...
                          </span>
                        </div>
                        <p className="mt-2 text-muted">Loading platforms...</p>
                      </div>
                    ) : platforms.length === 0 ? (
                      <div className="text-center py-4">
                        <p className="text-muted mb-0">

                        </p>
                      </div>
                    ) : (
                      <>
                        {platforms.map((platform) => {
                          const platformName = platform.name.toLowerCase();

                          return (
                            <div
                              key={platform.id}
                              className="url-logo-area mb-3"
                            >
                              <img
                                src={
                                  platform.platform_logo ||
                                  getPlatformLogo(platformName)
                                }
                                alt={`${platform.name} logo`}
                                className="url-logo-input"
                              />
                              <input
                                type="text"
                                placeholder={`Enter your ${platform.name} Storefront URL`}
                                value={modalPlatformUrls[platformName] || ""}
                                onChange={(e) =>
                                  handleInputChange(
                                    platformName,
                                    e.target.value
                                  )
                                }
                                className={`form-control ${modalPlatformUrls[platformName] &&
                                  !isValidUrl(modalPlatformUrls[platformName])
                                  ? "is-invalid"
                                  : ""
                                  }`}
                              />
                              {modalPlatformUrls[platformName] &&
                                !isValidUrl(
                                  modalPlatformUrls[platformName]
                                ) && (
                                  <div className="invalid-feedback">
                                    Please enter a valid URL
                                  </div>
                                )}
                            </div>
                          );
                        })}
                        <button
                          type="submit"
                          className="btn-first w-100"
                          disabled={
                            submitting ||
                            Object.values(modalPlatformUrls).every(
                              (url) => !url.trim()
                            )
                          }
                        >
                          {submitting ? "Saving..." : "Save"}
                        </button>
                      </>
                    )}
                  </form>
                </div>
              </div>
            </div>
          </section>
        </>
      )}
    </div>
  );
}
