"use client";

import Link from "next/link";
import Image from "next/image";
import { useState, useEffect, useRef } from "react";
import { useSession } from "@/auth/session-provider";
import { useTranslations } from "next-intl";
import type {
  FooterLink,
  GeneralSettingValue,
  GeneralSettingsMap,
} from "@/lib/api";

const linkFx =
  "transition-all duration-300 ease-in-out hover:font-bold hover:scale-[1.03] inline-block focus:outline-none focus-visible:ring-2 focus-visible:ring-primary/40 rounded";
const linkMuted = "text-white/85 " + linkFx;
const socialFx =
  "transition-all duration-300 ease-in-out hover:scale-[1.08] hover:opacity-90 focus:outline-none focus-visible:ring-2 focus-visible:ring-primary/40 rounded-full";

const asString = (value: GeneralSettingValue | undefined) => {
  if (value === null || value === undefined) return undefined;
  if (typeof value === "string") return value;
  if (typeof value === "number" || typeof value === "boolean") {
    return String(value);
  }
  return undefined;
};

const asImageUrl = (value: GeneralSettingValue | undefined) => {
  if (value === null || value === undefined) return undefined;
  if (typeof value === "string") return value;
  if (typeof value !== "object") return undefined;

  const maybe = value as { url?: unknown };
  if (typeof maybe.url === "string") return maybe.url;

  if (maybe.url && typeof maybe.url === "object") {
    const nested = maybe.url as { url?: unknown };
    if (typeof nested.url === "string") return nested.url;
  }

  return undefined;
};

const getNestedImageUrl = (value: unknown): string | undefined => {
  if (!value || typeof value !== "object") return undefined;
  const maybe = value as { url?: unknown; image?: unknown };

  const direct = asImageUrl(maybe as any);
  if (direct) return direct;

  if (maybe.image) {
    const nested = asImageUrl(maybe.image as any);
    if (nested) return nested;
  }

  return undefined;
};

export default function Footer({
  footerSettings,
  footerLinks,
}: {
  footerSettings?: GeneralSettingsMap;
  footerLinks?: FooterLink[];
}) {
  const session = useSession();
  const t = useTranslations("FOOTER");
  const [isFooterOpen, setIsFooterOpen] = useState(false);
  const footerRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    if (isFooterOpen && footerRef.current && window.innerWidth < 640) {
      setTimeout(() => {
        footerRef.current?.scrollIntoView({
          behavior: "smooth",
          block: "end",
        });
      }, 100);
    }
  }, [isFooterOpen]);

  const safeFooterLinks = footerLinks ?? [];

  const getText = (key: string, fallback: string): string =>
    asString(footerSettings?.[key]) ?? fallback;

  const getImg = (key: string, fallback: string): string =>
    asImageUrl(footerSettings?.[key]) ?? fallback;

  const title = getText("ataya_title", t("title"));
  const description = getText("ataya_description", t("description"));
  const location = getText("location", t("location"));
  const email = getText("email", "info@ataya.sa");
  const logoUrl = getImg("ataya_logo", "/logo.png");

  const supportTitle = getText("support_help", t("support_title"));
  const importantLinksTitle = getText(
    "important_links",
    t("important_links_title"),
  );
  const followUs = getText("follow_us", t("follow_us"));

  const contactUs = getText("contact_us", t("contact"));
  const faqs = getText("faq", t("faqs"));
  const privacy = getText("privacy_policy", t("privacy"));
  const terms = getText("terms_conditions", t("terms"));

  const horsePlatform = getText("horse_platform", t("horse_platform"));
  const camelPlatform = getText("camel_platform", t("camel_platform"));

  const getSocialUrl = (key: string, fallback: string) => {
    const value = footerSettings?.[key];
    if (value && typeof value === "object") {
      const maybe = value as { value?: unknown };
      if (typeof maybe.value === "string") return maybe.value;
    }
    if (typeof value === "string") return value;
    // Legacy support for *_url keys
    return getText(`${key}_url`, fallback);
  };

  const getSocialLogo = (key: string, fallback: string) => {
    const value = footerSettings?.[key];
    const img = getNestedImageUrl(value);
    if (img) return img;
    // Legacy support for *_logo keys
    return getImg(`${key}_logo`, fallback);
  };

  const twitterUrl = getSocialUrl("twitter", "https://twitter.com/");
  const instagramUrl = getSocialUrl("instagram", "https://instagram.com/");
  const youtubeUrl = getSocialUrl("youtube", "https://youtube.com/");
  const facebookUrl = getSocialUrl("facebook", "https://facebook.com/");

  const appStoreUrl = getText("ios_app_url", "#");
  const googlePlayUrl = getText("android_app_url", "#");
  const starTechUrl = getText("startech_url", "https://sta.sa/");

  const twitterLogo = "/images/icons/x.png";
  const instagramLogo = "/images/icons/in.png";
  const youtubeLogo = "/images/icons/yot.png";
  const facebookLogo = "/images/icons/f.png";

  const copyright = getText(
    "copyright",
    ` ${new Date().getFullYear()} ${t("title")} — ${t("rights")}`,
  );

  return (
    <footer className="bg-[#02684B] border-t" role="contentinfo">
      {/* Mobile Toggle Button - Only visible on mobile */}
      <div className="sm:hidden max-w-7xl mx-auto px-6 py-2">
        <button
          onClick={() => setIsFooterOpen(!isFooterOpen)}
          className="w-full flex items-center justify-between px-2 py-2 hover:bg-white/10 transition-all duration-500 ease-in-out"
        >
          <svg
            className={`w-5 h-5 text-white/80 transition-transform duration-500 ease-in-out ${isFooterOpen ? "rotate-180" : ""}`}
            fill="none"
            stroke="currentColor"
            viewBox="0 0 24 24"
          >
            <path
              strokeLinecap="round"
              strokeLinejoin="round"
              strokeWidth={2}
              d="M19 9l-7 7-7-7"
            />
          </svg>
          <img
            src={logoUrl}
            alt={t("alt")}
            width={32}
            height={32}
            className="h-8 w-auto object-contain"
          />
        </button>
      </div>

      {/* Footer Content - Always visible on tablet and desktop, toggle only on mobile */}
      <div
        ref={footerRef}
        className={`max-w-7xl mx-auto px-6 md:py-12 transition-all duration-500 ease-in-out overflow-hidden sm:block sm:max-h-none sm:opacity-100 ${
          isFooterOpen
            ? "max-h-500 opacity-100 py-12"
            : "max-h-0 opacity-0 py-0"
        }`}
      >
        {/*
          استخدمنا شبكة من عمودين على الموبايل بحيث:
          - القسم الأول (عن عطايا) يأخذ عرض العمودين كاملة.
          - قسما "الدعم الفني" و"الروابط المهمة" يظهران جنب بعض في نفس الصف.
          على الشاشات الكبيرة يرجع التخطيط الطبيعي بأربعة أعمدة.
        */}
        <div className="grid grid-cols-2 lg:grid-cols-4 items-start gap-10 text-sm">
          <div className="space-y-3 col-span-2 lg:col-span-1 max-sm:text-center ">
            <Link
              href="/"
              className="flex items-center max-sm:flex-col max-sm:justify-center gap-2 group"
            >
              <img
                src={logoUrl}
                alt={t("alt")}
                width={40}
                height={40}
                className="h-10 w-auto object-contain transition-all duration-300 ease-in-out group-hover:scale-[1.02]"
              />
              <span className="font-extrabold text-white">{title}</span>
            </Link>
            <p className="text-white/75">{description}</p>
            <p className="text-white/85">{location}</p>
            <a href={`mailto:${email}`} className={`text-white ${linkFx}`}>
              {email}
            </a>
          </div>

          <nav aria-label={supportTitle ?? t("support_title")}>
            <h4 className="text-base font-semibold mb-4 text-white text-center">
              {supportTitle}
            </h4>
            <ul className="space-y-2 text-center">
              <li>
                <Link href="/contact" className={linkMuted}>
                  {contactUs}
                </Link>
              </li>
              <li>
                <Link href="/faqs" className={linkMuted}>
                  {faqs}
                </Link>
              </li>
              <li>
                <Link href="/privacy" className={linkMuted}>
                  {privacy}
                </Link>
              </li>
              <li>
                <Link href="/term-conditions" className={linkMuted}>
                  {terms}
                </Link>
              </li>
            </ul>
          </nav>

          <nav aria-label={importantLinksTitle ?? t("important_links_title")}>
            <h4 className="text-base font-semibold mb-4 text-white text-center">
              {importantLinksTitle}
            </h4>
            <ul className="space-y-2 text-center">
              {safeFooterLinks.length > 0 ? (
                safeFooterLinks.map((l) => (
                  <li key={`${l.name}-${l.url}`}>
                    <a
                      href={l.url}
                      target="_blank"
                      rel="noopener noreferrer"
                      className={linkMuted}
                    >
                      {l.name}
                    </a>
                  </li>
                ))
              ) : (
                <>
                  {/*                   <li>
                    <Link href="/#horse" className={linkMuted}>
                      {horsePlatform}
                    </Link>
                  </li>
                  <li>
                    <Link href="/#camel" className={linkMuted}>
                      {camelPlatform}
                    </Link>
                  </li> */}
                </>
              )}
              {session && (
                <li>
                  <Link href="/buyer" className={linkMuted}>
                    {t("dashboard")}
                  </Link>
                </li>
              )}
            </ul>
          </nav>

          <div className="text-center col-span-2 lg:col-span-1">
            <h4 className="text-base font-semibold mb-4 text-white text-center">
              {followUs}
            </h4>
            <div className="flex gap-3 justify-center">
              <a
                href={twitterUrl}
                target="_blank"
                rel="noopener noreferrer"
                aria-label="Twitter / X"
                className={socialFx}
              >
                <img
                  src={twitterLogo}
                  alt="Twitter"
                  width={36}
                  height={36}
                  className="rounded-full"
                />
              </a>

              <a
                href={instagramUrl}
                target="_blank"
                rel="noopener noreferrer"
                aria-label="Instagram"
                className={socialFx}
              >
                <img
                  src={instagramLogo}
                  alt="Instagram"
                  width={36}
                  height={36}
                  className="rounded-full object-cover"
                />
              </a>

              <a
                href={youtubeUrl}
                target="_blank"
                rel="noopener noreferrer"
                aria-label="YouTube"
                className={socialFx}
              >
                <img
                  src={youtubeLogo}
                  alt="YouTube"
                  width={36}
                  height={36}
                  className="rounded-full"
                />
              </a>

              <a
                href={facebookUrl}
                target="_blank"
                rel="noopener noreferrer"
                aria-label="Facebook"
                className={socialFx}
              >
                <img
                  src={facebookLogo}
                  alt="Facebook"
                  width={36}
                  height={36}
                  className="rounded-full"
                />
              </a>
            </div>

            <div className="mt-5">
              <p className="text-sm mb-3 font-bold text-center text-white">
                {getText("download_app_text", t("download_app_text"))}
              </p>

              <div className="flex items-center max-sm:flex-col justify-center gap-0.5 md:gap-3">
                <a
                  href={appStoreUrl}
                  target="_blank"
                  rel="noopener noreferrer"
                  className="inline-flex items-center font-bold transition-all duration-300 ease-in-out hover:opacity-90 focus:outline-none focus-visible:ring-2 focus-visible:ring-primary/40 rounded"
                  aria-label={t("app_store_aria_label")}
                >
                  <Image
                    src="/images/icons/apple.png"
                    alt={t("app_store_label")}
                    width={150}
                    height={50}
                    className="h-20 w-auto object-none"
                  />
                </a>

                <a
                  href={googlePlayUrl}
                  target="_blank"
                  rel="noopener noreferrer"
                  className="inline-flex items-center transition-all duration-300 ease-in-out hover:opacity-90 focus:outline-none focus-visible:ring-2 focus-visible:ring-primary/40 rounded"
                  aria-label={t("google_play_aria_label")}
                >
                  <Image
                    src="/images/icons/google.png"
                    alt={t("google_play_label")}
                    width={170}
                    height={50}
                    className="h-20 w-auto object-none"
                  />
                </a>
              </div>
            </div>
          </div>
        </div>

        <div className="mt-10 pt-6 flex justify-between border-t border-white/20 max-md:flex-col text-white/70 text-center text-xs">
          {copyright}
          <a
            href={starTechUrl}
            target="_blank"
            rel="noopener noreferrer"
            className="md:mt-[-12px] mt-0 flex items-end justify-center gap-3 font-bold  text-white px-4 py-3 transition-all duration-300 ease-in-out hover:bg-white/10"
            aria-label={t("development_aria_label")}
          >
            <span className="text-md text-white font-bold">
              {t("development_label")}
            </span>
            <Image
              src="/golden-logo.png"
              alt="Stars Tech"
              width={90}
              height={22}
              className="h-10 w-auto"
            />
          </a>
        </div>
      </div>
    </footer>
  );
}
