import {
  TooltipContent,
  TooltipProvider,
  TooltipTrigger,
  Tooltip,
} from "@/shared/common/ui/tooltip";
import { motion } from "framer-motion";
import { Share2 as Facebook, Globe, Globe as Linkedin, Mail, MapPin, Phone } 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";
import { useNavigate } from "react-router-dom";
import { useTenantConfig } from "@/layout/components/TenantConfig";

const Footer = () => {
  const [activeTab, setActiveTab] = useState("");
  const navigate = useNavigate();
  const { t } = useTranslation();
  const { config: tenantConfig } = useTenantConfig();
  const defaultFooterData = {
    address: "XQXP+J6C Lingo Tower, Namibia St, Addis Ababa",
    phone: "+251-955-232323",
    email: "sales@triaplc.com",
  };

  const footerData = tenantConfig?.footerData || defaultFooterData;
  const navItems = [
    { id: "overview", label: t("landingPage.overview") },
    { id: "features", label: t("landingPage.features") },
    { id: "workflow", label: t("landingPage.workflow") },
    { id: "howto", label: t("landingPage.manual") },
  ];
  const navigateTo = "/";
  const handleAddressClick = () => {
    const address =
      footerData.address || "XQXP+J6C Lingo Tower, Namibia St, Addis Ababa";
    const query = encodeURIComponent(address);
    window.open(
      `https://www.google.com/maps/search/?api=1&query=${query}`,
      "_blank",
      "noopener noreferrer",
    );
  };
  const handleEmailClick = () => {
    const email = footerData.email || "sales@triaplc.com";
    const subject = "";
    const body = "";
    const gmailParams = new URLSearchParams();
    gmailParams.append("to", email);
    if (subject) gmailParams.append("su", subject);
    if (body) gmailParams.append("body", body);

    const gmailUrl = `https://mail.google.com/mail/?view=cm&fs=1&${gmailParams.toString()}`;
    const mailtoUrl = `mailto:${email}?subject=${encodeURIComponent(subject || "")}&body=${encodeURIComponent(body || "")}`;

    window.open(gmailUrl, "_blank", "noopener noreferrer");

    setTimeout(() => {
      window.open(mailtoUrl, "_blank", "noopener noreferrer");
    }, 500);
  };
  const socials = tenantConfig?.socials || {};
  const socialLinks = {
    facebook: socials.facebook || "https://web.facebook.com/Triaplc",
    twitter: socials.twitter || "https://x.com/Triaplc",
    linkedin: socials.linkedin || "https://www.linkedin.com/company/triaplc",
    telegram: socials.telegram || "",
    tiktok: socials.tiktok || "",
    website: socials.website || "https://triaplc.com/",
  };
  const optionalSocialLinks = [
    {
      href: socialLinks.telegram,
      label: t("landingPage.telegram"),
      icon: FaTelegramPlane,
    },
    {
      href: socialLinks.tiktok,
      label: t("landingPage.tiktok"),
      icon: FaTiktok,
    },
  ].filter((item) => item.href);

  return (
    <footer className="bg-gradient-to-b from-gray-900 to-gray-800 dark:bg-gradient-to-b dark:from-gray-900 dark:to-gray-800">
      <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">
          <div className="space-y-8 xl:col-span-1">
            <div className="flex items-center">
              {tenantConfig?.logo ? (
                <div className="relative group inline-flex">
                  {/* Glow */}
                  <div className="absolute inset-0 rounded-2xl bg-gradient-to-r from-primary/20 to-secondary/20 blur-xl opacity-0 group-hover:opacity-100 transition-all duration-500 scale-110" />

                  {/* Footer Logo Wrapper */}
                  <motion.div
                    whileHover={{ scale: 1.04 }}
                    whileTap={{ scale: 0.97 }}
                    transition={{ type: "spring", stiffness: 220, damping: 16 }}
                    className="relative inline-flex items-center justify-center cursor-pointer group"
                    onClick={() => (window.location.href = "/")}
                    title={t("nav.homePage")}
                  >
                    <motion.img
                      src={tenantConfig.logo}
                      alt="Footer Logo"
                      className="
      h-35
      w-auto
      object-contain
      group-hover:scale-105
      transition-transform
      duration-300
    "
                      onError={(e) => {
                        const fallback =
                          e.currentTarget.parentElement?.querySelector(
                            ".footer-logo-fallback",
                          );

                        if (fallback) {
                          fallback.classList.remove("hidden");
                        }

                        e.currentTarget.remove();
                      }}
                    />

                    {/* Fallback when logo fails to load */}
                    <div
                      className="
      footer-logo-fallback
      hidden
      h-20
      w-20
      items-center
      justify-center
      rounded-full
      bg-primary
      text-primary-foreground
      font-bold
      text-2xl
      pointer-events-none
    "
                    >
                      {tenantConfig?.organizationName
                        ?.split(/[\s\-–—]+/)
                        .filter(Boolean)
                        .map((word) => word.charAt(0))
                        .join("")
                        .toUpperCase() || "SO"}
                    </div>
                  </motion.div>
                </div>
              ) : (
                <div className="h-10 w-10 rounded-full bg-primary flex items-center justify-center text-white font-bold text-xl">
                  SO
                </div>
              )}
              <span className="ml-3 text-2xl font-bold text-white">
                {tenantConfig?.organizationName || t("landingPage.smartOffice")}
              </span>
            </div>
            <p className="text-gray-300 text-lg max-h-20 overflow-y-auto pr-2">
              {tenantConfig?.footerText ||
                t("landingPage.digitalTransformation")}
            </p>
            <div className="flex space-x-6">
              <a
                href={socialLinks.facebook}
                target="_blank"
                rel="noopener noreferrer"
                className="text-gray-400 hover:text-primary transition-colors duration-300"
              >
                <li className="flex items-center space-x-2 text-base text-gray-400 hover:text-primary transition-colors duration-300 cursor-pointer">
                  <TooltipProvider>
                    <Tooltip>
                      <TooltipTrigger asChild>
                        <Facebook className="h-6 w-6 hover:text-primary" />
                      </TooltipTrigger>
                      <TooltipContent>
                        <span>{t("landingPage.facebook")}</span>
                      </TooltipContent>
                    </Tooltip>
                  </TooltipProvider>
                  <span className="sr-only">{t("landingPage.facebook")}</span>
                </li>
              </a>
              <a
                href={socialLinks.twitter}
                target="_blank"
                rel="noopener noreferrer"
                className="text-gray-400 hover:text-primary transition-colors duration-300"
              >
                <li className="flex items-center space-x-2 text-base text-gray-400 hover:text-primary transition-colors duration-300 cursor-pointer">
                  <TooltipProvider>
                    <Tooltip>
                      <TooltipTrigger asChild>
                        <FaXTwitter className="h-6 w-6 hover:text-primary" />
                      </TooltipTrigger>
                      <TooltipContent>
                        <span>{t("landingPage.twitter")}</span>
                      </TooltipContent>
                    </Tooltip>
                  </TooltipProvider>

                  <span className="sr-only">{t("landingPage.twitter")}</span>
                </li>
              </a>
              <a
                href={socialLinks.linkedin}
                target="_blank"
                rel="noopener noreferrer"
                className="text-gray-400 hover:text-primary transition-colors duration-300"
              >
                <li className="flex items-center space-x-2 text-base text-gray-400 hover:text-primary transition-colors duration-300 cursor-pointer">
                  <TooltipProvider>
                    <Tooltip>
                      <TooltipTrigger asChild>
                        <Linkedin className="h-6 w-6 hover:text-primary" />
                      </TooltipTrigger>
                      <TooltipContent>
                        <span>{t("landingPage.linkedIn")}</span>
                      </TooltipContent>
                    </Tooltip>
                  </TooltipProvider>

                  <span className="sr-only">{t("landingPage.linkedIn")}</span>
                </li>
              </a>
              {optionalSocialLinks.map(({ href, label, icon: Icon }) => (
                <a
                  key={label}
                  href={href}
                  target="_blank"
                  rel="noopener noreferrer"
                  className="text-gray-400 hover:text-primary transition-colors duration-300"
                >
                  <li className="flex items-center space-x-2 text-base text-gray-400 hover:text-primary transition-colors duration-300 cursor-pointer">
                    <TooltipProvider>
                      <Tooltip>
                        <TooltipTrigger asChild>
                          <Icon className="h-6 w-6 hover:text-primary" />
                        </TooltipTrigger>
                        <TooltipContent>
                          <span>{label}</span>
                        </TooltipContent>
                      </Tooltip>
                    </TooltipProvider>

                    <span className="sr-only">{label}</span>
                  </li>
                </a>
              ))}
              <a
                href={socialLinks.website}
                target="_blank"
                rel="noopener noreferrer"
                className="text-gray-400 hover:text-primary transition-colors duration-300"
              >
                <li className="flex items-center space-x-2 text-base text-gray-400 hover:text-primary transition-colors duration-300 cursor-pointer">
                  <TooltipProvider>
                    <Tooltip>
                      <TooltipTrigger asChild>
                        <Globe className="h-6 w-6 hover:text-primary" />
                      </TooltipTrigger>
                      <TooltipContent>
                        <span>{t("landingPage.website")}</span>
                      </TooltipContent>
                    </Tooltip>
                  </TooltipProvider>
                  <span className="sr-only">{t("landingPage.website")}</span>
                </li>
              </a>
            </div>
          </div>

          <div className="mt-12 xl:mt-0 xl:col-span-2">
            <div className="grid grid-cols-1 md:grid-cols-2 gap-8">
              <div>
                <h3 className="text-sm font-semibold text-gray-300 tracking-wider uppercase">
                  {t("landingPage.contactUs")}
                </h3>
                <ul className="mt-4 space-y-4">
                  <li
                    onClick={handleEmailClick}
                    title={footerData.email || "sales@triaplc.com"}
                    className="flex items-center space-x-3 text-base text-gray-400 hover:text-primary transition-colors duration-300 cursor-pointer"
                  >
                    <Mail className="h-5 w-5 hover:text-primary" />
                    <span className="font-medium">
                      {footerData.email || "sales@triaplc.com"}
                    </span>
                  </li>
                  <li className="flex items-center space-x-3 text-base text-gray-400 hover:text-primary transition-colors duration-300 cursor-pointer">
                    <Phone className="h-5 w-5 hover:text-primary" />
                    <span className="font-medium">
                      {footerData.phone || "+251-955-232323"}
                    </span>
                  </li>

                  <li
                    onClick={handleAddressClick}
                    title={
                      footerData.address ||
                      "XQXP+J6C Lingo Tower, Namibia St, Addis Ababa"
                    }
                    className="flex items-center space-x-3 text-base text-gray-400 hover:text-primary transition-colors duration-300 cursor-pointer"
                  >
                    <MapPin className="h-5 w-5 hover:text-primary" />
                    <span className="font-medium">
                      {footerData.address || t("landingPage.address")}
                    </span>
                  </li>
                </ul>
              </div>

              <div>
                <h3 className="text-sm font-semibold text-gray-300 tracking-wider uppercase">
                  {t("landingPage.quickLinks")}
                </h3>
                <ul className="mt-4 space-y-4">
                  {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={`cursor-pointer text-base text-gray-400 hover:text-primary transition-colors duration-300 flex items-center ${
                        activeTab === item.id
                          ? "text-gray-400"
                          : "text-gray-400"
                      }`}
                    >
                      {item.label}
                      {activeTab === item.id && (
                        <motion.div
                          layoutId="activeTabIndicator"
                          className="absolute bottom-0 left-0 right-0 h-0.5 bg-primary"
                          transition={{
                            type: "spring",
                            bounce: 0.2,
                            duration: 0.6,
                          }}
                        />
                      )}
                    </button>
                  ))}
                </ul>
              </div>
            </div>
          </div>
        </div>

        <div className="mt-12 border-t border-gray-700 pt-8 flex flex-col items-center justify-center text-center">
          <p className="text-base text-gray-400">
            &copy; {t("landingPage.copyright")}
            {new Date().getFullYear()} {t("landingPage.rightsReserved")}
          </p>
        </div>
      </div>
    </footer>
  );
};

export default Footer;
