import { useLocalizedName } from "@/shared/common/localizedName";
import { useContactUs } from "@/user-management/web-Management/hooks/useContactUs";
import { useSocialMedia } from "@/user-management/web-Management/hooks/useSocialMedia";
import { useTheme } from "@/user-management/web-Management/hooks/useTheme";
import { motion } from "framer-motion";
import {
  Facebook,
  Globe,
  Instagram,
  Linkedin,
  Mail,
  MapPin,
  Phone,
  Youtube,
} from "lucide-react";
import { FaTelegramPlane, FaTiktok } from "react-icons/fa";
import { FaXTwitter } from "react-icons/fa6";
import { useState } from "react";
import { useTranslation } from "react-i18next";

interface BrandColors {
  primary: string; // main accent color (e.g. var(--primary))
  gradientFrom: string;
  gradientTo: string;
  textColor: string;
  mutedText: string;
  borderColor: string;
}

const Footer = ({
  brandColors = {
    primary: "var(--primary)",
    gradientFrom: "#1f2937", // gray-900
    gradientTo: "#111827", // gray-800
    textColor: "#111827",
    mutedText: "#9ca3af", // gray-400
    borderColor: "#374151", // gray-700
  },
}: {
  brandColors?: BrandColors;
}) => {
  const [activeTab, setActiveTab] = useState("");
  const { t } = useTranslation();
  const baseParams = {
    isActive: true,
  };
  const { items: social } = useSocialMedia(baseParams);
  const { items: contact } = useContactUs(baseParams);
  const localizedName = useLocalizedName();
  const { items: theme, unit } = useTheme();

  //icons
  const SOCIAL_ICONS: Record<
    string,
    { icon: React.ElementType; color: string; labelKey: string }
  > = {
    FACEBOOK: {
      icon: Facebook,
      color: "#1877F2",
      labelKey: "landingPage.facebook",
    },
    TWITTER: {
      icon: FaXTwitter,
      color: "#000000",
      labelKey: "landingPage.twitter",
    },
    LINKEDIN: {
      icon: Linkedin,
      color: "#0077B5",
      labelKey: "landingPage.linkedin",
    },
    TELEGRAM: {
      icon: FaTelegramPlane,
      color: "#0088cc",
      labelKey: "landingPage.telegram",
    },
    TIKTOK: {
      icon: FaTiktok,
      color: "#ffffff",
      labelKey: "landingPage.tiktok",
    },
    INSTAGRAM: {
      icon: Instagram,
      color: "#E1306C",
      labelKey: "landingPage.instagram",
    }, // example
    WEBSITE: { icon: Globe, color: "#0077B5", labelKey: "landingPage.website" },
    YOUTUBE: {
      icon: Youtube,
      color: "#0077B5",
      labelKey: "landingPage.website",
    },
  };
  // === Dynamic Navigation Items ===
  const navItems: any[] = [
    { id: "OfficeHeadMessage", label: t("nav.officeHeadMessage") },
    { id: "DeputyMessage", label: t("nav.deputyMessage") },
    {
      id: "OrganizationGoal",
      label: t("nav.orgGoal"),
    },
    { id: "NewsSection", label: t("nav.news") },
  ];

  // === Dynamic Social Links ===
  // Filter only active socials
  const socialLinks: any[] =
    social
      ?.filter((s) => SOCIAL_ICONS[s.type])
      .map((s) => ({
        id: s.name || s.type.toLowerCase(),
        icon: SOCIAL_ICONS[s.type].icon,
        url: s.link,
        color: SOCIAL_ICONS[s.type].color,
        label: t(SOCIAL_ICONS[s.type].labelKey),
      })) ?? [];
  function lightenColor(color: string, percent: number) {
    const R = parseInt(color.substring(1, 3), 16);
    const G = parseInt(color.substring(3, 5), 16);
    const B = parseInt(color.substring(5, 7), 16);

    const newR = Math.min(255, R + Math.round((255 - R) * (percent / 100)));
    const newG = Math.min(255, G + Math.round((255 - G) * (percent / 100)));
    const newB = Math.min(255, B + Math.round((255 - B) * (percent / 100)));

    return `#${newR.toString(16).padStart(2, "0")}${newG
      .toString(16)
      .padStart(2, "0")}${newB.toString(16).padStart(2, "0")}`;
  }
  return (
    <footer
      className="transition-colors duration-500"
      style={{
        background: `linear-gradient(
      to top, 
     ${
       theme?.find((i) => i.type === "PRIMARY_COLOR")?.value
         ? lightenColor(theme.find((i) => i.type === "PRIMARY_COLOR")!.value, 5)
         : "var(--primary-300)"
     }, 
      ${
        theme?.find((i) => i.type === "PRIMARY_COLOR")?.value
          ? lightenColor(
              theme.find((i) => i.type === "PRIMARY_COLOR")!.value,
              10
            )
          : "var(--primary-300)"
      }
    )`,
      }}
    >
      <div className="max-w-7xl mx-auto py-12 px-4 sm:px-6 lg:py-16 lg:px-8">
        <div className="xl:grid xl:grid-cols-3 xl:gap-8">
          {/* === Left Section === */}
          <div className="space-y-2 xl:col-span-1">
            <div className="flex items-center">
              <div
                className="overflow-hidden"
                style={{
                  width: "150px", // container width
                  height: "150px", // container height
                  borderRadius: "16px", // soft rounded corners, change to "50%" for circle
                  backgroundColor: brandColors.primary,
                  flexShrink: 0, // prevents shrinking
                }}
              >
                <img
                  src={
                    theme?.find((i) => i.type === "LOGO")?.presigned ||
                    "https://www.w3.org/Icons/w3c_home"
                  }
                  alt={localizedName(unit?.name)}
                  className="w-full h-full object-cover"
                />
              </div>
            </div>
            <span className="ml-4 text-xl md:text-2xl font-bold">
              {t("landingPage.smartOffice")}
            </span>
            <p className="text-lg" style={{ color: brandColors.mutedText }}>
              {t("landingPage.digitalTransformation")}
            </p>

            {/* === Social Links (Dynamic) === */}
            <div className="flex space-x-6">
              {socialLinks.map(({ id, icon: Icon, url, color, label }) => (
                <a
                  key={id}
                  href={url}
                  target="_blank"
                  rel="noopener noreferrer"
                  className="transition-transform hover:scale-110"
                >
                  <Icon
                    className="h-6 w-6 transition-colors duration-300"
                    style={{
                      color: brandColors.mutedText,
                    }}
                    onMouseEnter={(e: any) =>
                      (e.currentTarget.style.color = color)
                    }
                    onMouseLeave={(e: any) =>
                      (e.currentTarget.style.color = brandColors.mutedText)
                    }
                  />
                  <span className="sr-only">{label}</span>
                </a>
              ))}
            </div>
          </div>

          {/* === Right Section === */}
          <div className="mt-12 xl:mt-0 xl:col-span-2">
            <div className="grid grid-cols-1 md:grid-cols-2 gap-8">
              {/* === Contact Info === */}
              <div>
                <h3
                  className="text-sm font-semibold tracking-wider uppercase"
                  style={{ color: brandColors.textColor }}
                >
                  {t("landingPage.contactUs")}
                </h3>
                <ul className="mt-4 space-y-4">
                  <li className="flex items-center space-x-3 text-base transition-colors duration-300 cursor-pointer">
                    <Mail
                      className="h-5 w-5"
                      style={{ color: brandColors.mutedText }}
                    />
                    <span
                      className="font-medium"
                      style={{ color: brandColors.textColor }}
                    >
                      {
                        contact?.find((i) => i.type === "EMAIL" && i.isActive)
                          ?.value
                      }
                    </span>
                  </li>
                  <li className="flex items-center space-x-3 text-base cursor-pointer">
                    <Phone
                      className="h-5 w-5"
                      style={{ color: brandColors.mutedText }}
                    />
                    <span
                      className="font-medium"
                      style={{ color: brandColors.textColor }}
                    >
                      {
                        contact?.find(
                          (i) => i.type === "PHONE_NUMBER" && i.isActive
                        )?.value
                      }
                    </span>
                  </li>
                  <li className="flex items-center space-x-3 text-base">
                    <MapPin
                      className="h-5 w-5 flex-shrink-0"
                      style={{ color: brandColors.mutedText }}
                    />

                    {(() => {
                      const location = contact?.find(
                        (i) => i.type === "LOCATION" && i.isActive
                      )?.value;

                      if (!location) {
                        return (
                          <span
                            className="font-medium"
                            style={{ color: brandColors.textColor }}
                          >
                            Not available
                          </span>
                        );
                      }

                      const shortText =
                        location.length > 25
                          ? location.slice(0, 25) + "…"
                          : location;

                      return (
                        <a
                          href={`https://www.google.com/maps/search/?api=1&query=${encodeURIComponent(
                            location
                          )}`}
                          target="_blank"
                          rel="noopener noreferrer"
                          className="font-medium hover:underline truncate max-w-[180px] inline-block align-middle"
                          style={{ color: brandColors.textColor }}
                          title={location} // tooltip shows full text on hover
                        >
                          {shortText}
                        </a>
                      );
                    })()}
                  </li>
                </ul>
              </div>

              {/* === Quick Links === */}
              <div>
                <h3
                  className="text-sm font-semibold tracking-wider uppercase"
                  style={{ color: brandColors.textColor }}
                >
                  {t("landingPage.quickLinks")}
                </h3>
                <ul className="mt-4 space-y-4 relative">
                  {navItems.map((item) => (
                    <button
                      key={item.id}
                      onClick={() => {
                        setActiveTab(item.id);
                        const el = document.getElementById(item.id);
                        if (el) {
                          el.scrollIntoView({
                            behavior: "smooth",
                            block: "start",
                          });
                        }
                      }}
                      className="relative flex items-center text-base transition-colors duration-300 cursor-pointer"
                      style={{
                        color:
                          activeTab === item.id
                            ? brandColors.primary
                            : brandColors.mutedText,
                      }}
                    >
                      {item.label}
                      {activeTab === item.id && (
                        <motion.div
                          layoutId="activeTabIndicator"
                          className="absolute bottom-0 left-0 right-0 h-0.5"
                          style={{ backgroundColor: brandColors.primary }}
                          transition={{
                            type: "spring",
                            bounce: 0.2,
                            duration: 0.6,
                          }}
                        />
                      )}
                    </button>
                  ))}
                </ul>
              </div>
            </div>
          </div>
        </div>

        {/* === Bottom Section === */}
        <div
          className="mt-12 pt-8 flex flex-col items-center justify-center text-center"
          style={{ borderTop: `1px solid ${brandColors.borderColor}` }}
        >
          <p style={{ color: brandColors.mutedText }}>
            &copy; {t("landingPage.copyright")} {new Date().getFullYear()}{" "}
            {t("landingPage.rightsReserved")}
          </p>
        </div>
      </div>
    </footer>
  );
};

export default Footer;
