"use client";
import Link from "next/link";
import Image from "next/image";
import { usePathname, useRouter } from "next/navigation";
import { useEffect } from "react";
import {
  Home,
  Film,
  Video,
  Music,
  Mic,
  Radio,
  Heart,
  Clock,
  History,
  Users,
  Wallet,
  Coins,
  Newspaper,
  LogIn,
  LogOut,
  Globe,
  Mail,
  ExternalLink,
  LayoutGrid,
  RadioTower,
  HardDriveDownload,
  Gift,
} from "lucide-react";
import { cn } from "@/utils/cn";
import { IMAGES } from "@/branding/images";
import { TEXT } from "@/branding";
import { useAppDispatch, useAppSelector } from "@/store/hooks";
import { logoutUser } from "@/store/slices/authSlice";
import { fetchMoreProducts } from "@/store/slices/moreProductsSlice";
import { useGeneralSettings } from "@/lib/GeneralSettingsContext";
import { useTranslation } from "@/i18n";

interface SidebarProps {
  collapsed: boolean;
  mobileOpen: boolean;
  onClose: () => void;
}

function SidebarItem({
  label,
  icon: Icon,
  path,
  isActive,
  collapsed,
  onClick,
}: {
  label: string;
  icon: React.ComponentType<{
    size?: number | string;
    strokeWidth?: number | string;
  }>;
  path: string;
  isActive: boolean;
  collapsed: boolean;
  onClick?: () => void;
}) {
  return (
    <Link
      href={path}
      onClick={onClick}
      title={collapsed ? label : undefined}
      className={cn(
        "flex items-center rounded-lg text-xs font-medium transition-all duration-150",
        collapsed
          ? "mx-1.5 px-0 py-2.5 justify-center"
          : "mx-2 px-4 py-2.5 gap-3",
      )}
      style={{
        borderLeft:
          !collapsed && isActive
            ? "3px solid var(--accent)"
            : "3px solid transparent",
        background: isActive ? "rgba(var(--accent-rgb),0.08)" : "transparent",
        color: isActive ? "var(--text-primary)" : "var(--text-muted)",
        fontWeight: isActive ? 600 : 500,
        width: collapsed ? "calc(100% - 12px)" : undefined,
      }}
      onMouseEnter={(e) => {
        if (!isActive) {
          (e.currentTarget as HTMLElement).style.background = "var(--card)";
          (e.currentTarget as HTMLElement).style.color = "var(--text-primary)";
        }
      }}
      onMouseLeave={(e) => {
        if (!isActive) {
          (e.currentTarget as HTMLElement).style.background = "transparent";
          (e.currentTarget as HTMLElement).style.color = "var(--text-muted)";
        }
      }}
    >
      <Icon size={collapsed ? 20 : 16} strokeWidth={1.6} />
      {!collapsed && <span>{label}</span>}
    </Link>
  );
}

/* ── Company info panel ─────────────────────────────────────────────────── */
function CompanyPanel({
  settings,
  pages,
}: {
  settings: ReturnType<typeof useGeneralSettings>["settings"];
  pages: ReturnType<typeof useGeneralSettings>["pages"];
}) {
  const year = new Date().getFullYear();
  const hasLogo = !!settings?.companyLogo;
  const hasCompany = !!settings?.companyName;
  const hasMeta = hasLogo || hasCompany;

  return (
    <div
      style={{
        borderTop: "1px solid var(--border-soft)",
        paddingTop: 14,
        paddingBottom: 6,
        paddingLeft: 16,
        paddingRight: 16,
        display: "flex",
        flexDirection: "column",
        gap: 10,
      }}
    >
      {hasMeta && (
        <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
          {hasLogo ? (
            <div
              style={{
                width: 22,
                height: 22,
                borderRadius: 5,
                overflow: "hidden",
                flexShrink: 0,
                background: "var(--btn-ghost)",
                border: "1px solid var(--border-soft)",
                display: "flex",
                alignItems: "center",
                justifyContent: "center",
              }}
            >
              <Image
                src={settings!.companyLogo}
                alt={settings?.companyName ?? ""}
                width={22}
                height={22}
                className="object-contain"
                unoptimized
              />
            </div>
          ) : (
            <Image
              src={IMAGES.appIcon}
              alt={settings?.appName ?? "Doliplay"}
              width={20}
              height={20}
              className="rounded shrink-0"
              style={{ opacity: 0.55 }}
              priority={false}
            />
          )}
          <div style={{ minWidth: 0, flex: 1 }}>
            <p
              style={{
                fontSize: 11,
                fontWeight: 700,
                color: "var(--text-secondary)",
                overflow: "hidden",
                textOverflow: "ellipsis",
                whiteSpace: "nowrap",
                lineHeight: 1.3,
              }}
            >
              {settings?.companyName || settings?.appName || "Doliplay"}
            </p>
          </div>
          {settings?.appVersion && (
            <span
              style={{
                fontSize: 9,
                fontWeight: 800,
                letterSpacing: "0.04em",
                padding: "2px 6px",
                borderRadius: 4,
                background: "rgba(var(--accent-rgb),0.1)",
                color: "var(--accent)",
                border: "1px solid rgba(var(--accent-rgb),0.2)",
                flexShrink: 0,
              }}
            >
              v{settings.appVersion}
            </span>
          )}
        </div>
      )}

      {pages.length > 0 && (
        <div style={{ display: "flex", flexDirection: "column", gap: 3 }}>
          {pages.map((page) => (
            <a
              key={page.url}
              href={page.url}
              target="_blank"
              rel="noopener noreferrer"
              style={{
                display: "flex",
                alignItems: "center",
                gap: 4,
                fontSize: 10,
                fontWeight: 500,
                color: "var(--text-muted)",
                textDecoration: "none",
                transition: "color 140ms ease",
                lineHeight: 1.5,
              }}
              onMouseEnter={(e) => {
                (e.currentTarget as HTMLAnchorElement).style.color =
                  "var(--text-primary)";
              }}
              onMouseLeave={(e) => {
                (e.currentTarget as HTMLAnchorElement).style.color =
                  "var(--text-muted)";
              }}
            >
              <ExternalLink
                size={9}
                strokeWidth={1.8}
                style={{ flexShrink: 0, opacity: 0.6 }}
              />
              {page.title}
            </a>
          ))}
        </div>
      )}

      {(pages.length > 0 || hasMeta) &&
        (settings?.supportEmail || settings?.website) && (
          <div style={{ height: 1, background: "var(--border-soft)" }} />
        )}

      <div style={{ display: "flex", flexDirection: "column", gap: 3 }}>
        {settings?.supportEmail && (
          <a
            href={`mailto:${settings.supportEmail}`}
            style={{
              display: "flex",
              alignItems: "center",
              gap: 5,
              fontSize: 9.5,
              color: "var(--text-muted)",
              textDecoration: "none",
              transition: "color 130ms ease",
              overflow: "hidden",
              textOverflow: "ellipsis",
              whiteSpace: "nowrap",
            }}
            onMouseEnter={(e) => {
              (e.currentTarget as HTMLAnchorElement).style.color =
                "var(--text-secondary)";
            }}
            onMouseLeave={(e) => {
              (e.currentTarget as HTMLAnchorElement).style.color =
                "var(--text-muted)";
            }}
          >
            <Mail size={8.5} strokeWidth={1.8} style={{ flexShrink: 0 }} />
            {settings.supportEmail}
          </a>
        )}
        {settings?.website && (
          <a
            href={settings.website}
            target="_blank"
            rel="noopener noreferrer"
            style={{
              display: "flex",
              alignItems: "center",
              gap: 5,
              fontSize: 9.5,
              color: "var(--text-muted)",
              textDecoration: "none",
              transition: "color 130ms ease",
              overflow: "hidden",
              textOverflow: "ellipsis",
              whiteSpace: "nowrap",
            }}
            onMouseEnter={(e) => {
              (e.currentTarget as HTMLAnchorElement).style.color =
                "var(--text-secondary)";
            }}
            onMouseLeave={(e) => {
              (e.currentTarget as HTMLAnchorElement).style.color =
                "var(--text-muted)";
            }}
          >
            <Globe size={8.5} strokeWidth={1.8} style={{ flexShrink: 0 }} />
            {settings.website.replace(/^https?:\/\//, "").replace(/\/$/, "")}
          </a>
        )}
      </div>

      <p
        style={{
          fontSize: 9,
          color: "var(--text-muted)",
          letterSpacing: "0.02em",
          marginTop: 1,
        }}
      >
        © {year} {settings?.appName ?? "Doliplay"}
        {settings?.author && settings.author !== settings?.appName
          ? ` · ${settings.author}`
          : ""}
      </p>
    </div>
  );
}

/* ── More Apps Panel ────────────────────────────────────────────────────── */
function MoreAppsPanel({ collapsed }: { collapsed: boolean }) {
  const items = useAppSelector((s) => s.moreProducts.items);
  const isLoading = useAppSelector((s) => s.moreProducts.isLoading);

  if (isLoading || items.length === 0) return null;

  if (collapsed) {
    return (
      <div className="flex flex-col items-center gap-1.5 py-2 px-1.5">
        {items.slice(0, 4).map((item) => (
          <a
            key={item.id}
            href={item.redirect_url}
            target="_blank"
            rel="noopener noreferrer"
            title={item.name}
            className="w-9 h-9 rounded-xl flex items-center justify-center transition-all duration-150 group"
            style={{
              background: "var(--card)",
              border: "1px solid var(--border)",
            }}
            onMouseEnter={(e) => {
              (e.currentTarget as HTMLElement).style.background =
                "rgba(var(--accent-rgb),0.10)";
              (e.currentTarget as HTMLElement).style.borderColor =
                "rgba(var(--accent-rgb),0.3)";
              (e.currentTarget as HTMLElement).style.transform = "scale(1.08)";
            }}
            onMouseLeave={(e) => {
              (e.currentTarget as HTMLElement).style.background = "var(--card)";
              (e.currentTarget as HTMLElement).style.borderColor =
                "var(--border)";
              (e.currentTarget as HTMLElement).style.transform = "scale(1)";
            }}
          >
            <Image
              src={item.icon}
              alt={item.name}
              width={22}
              height={22}
              className="rounded-lg object-contain"
              unoptimized
            />
          </a>
        ))}
      </div>
    );
  }

  return (
    <div style={{ padding: "4px 10px 10px" }}>
      {/* Section header */}
      <div className="flex items-center gap-1.5 px-2 py-2 mb-1">
        <LayoutGrid
          size={11}
          strokeWidth={2}
          style={{ color: "var(--text-muted)", opacity: 0.7 }}
        />
        <span
          className="text-[10px] font-semibold uppercase tracking-[0.12em]"
          style={{ color: "var(--text-muted)" }}
        >
          More Apps
        </span>
      </div>

      {/* 2-column grid */}
      <div
        style={{
          display: "grid",
          gridTemplateColumns: "1fr 1fr",
          gap: 6,
        }}
      >
        {items.map((item) => (
          <a
            key={item.id}
            href={item.redirect_url}
            target="_blank"
            rel="noopener noreferrer"
            title={item.name}
            className="flex flex-col items-center gap-1.5 rounded-xl p-2 transition-all duration-150"
            style={{
              background: "var(--card)",
              border: "1px solid var(--border)",
              textDecoration: "none",
              cursor: "pointer",
            }}
            onMouseEnter={(e) => {
              (e.currentTarget as HTMLElement).style.background =
                "rgba(var(--accent-rgb),0.07)";
              (e.currentTarget as HTMLElement).style.borderColor =
                "rgba(var(--accent-rgb),0.25)";
              (e.currentTarget as HTMLElement).style.transform =
                "translateY(-2px)";
              (e.currentTarget as HTMLElement).style.boxShadow =
                "0 4px 12px rgba(var(--accent-rgb),0.12)";
            }}
            onMouseLeave={(e) => {
              (e.currentTarget as HTMLElement).style.background = "var(--card)";
              (e.currentTarget as HTMLElement).style.borderColor =
                "var(--border)";
              (e.currentTarget as HTMLElement).style.transform =
                "translateY(0)";
              (e.currentTarget as HTMLElement).style.boxShadow = "none";
            }}
          >
            <div
              className="w-9 h-9 rounded-xl flex items-center justify-center overflow-hidden"
              style={{ background: "var(--deep)" }}
            >
              <Image
                src={item.icon}
                alt={item.name}
                width={28}
                height={28}
                className="object-contain"
                unoptimized
              />
            </div>
            <span
              className="text-[10px] font-medium text-center leading-tight w-full truncate px-0.5"
              style={{ color: "var(--text-secondary)" }}
            >
              {item.name}
            </span>
          </a>
        ))}
      </div>
    </div>
  );
}

export function Sidebar({ collapsed, mobileOpen, onClose }: SidebarProps) {
  const pathname = usePathname();
  const dispatch = useAppDispatch();
  const router = useRouter();
  const isAuthenticated = useAppSelector((s) => s.auth.isAuthenticated);
  const { settings, pages } = useGeneralSettings();
  const { t } = useTranslation();

  useEffect(() => {
    dispatch(fetchMoreProducts());
  }, [dispatch]);

  const SIDEBAR_PRIMARY = [
    { label: t("nav_home"), icon: Home, path: "/" },
    { label: t("nav_shorts"), icon: Film, path: "/shorts" },
  ];

  const SIDEBAR_CONTENT = [
    { label: t("nav_videos"), icon: Video, path: "/videos" },
    { label: t("nav_music"), icon: Music, path: "/music" },
    { label: t("nav_podcasts"), icon: Mic, path: "/podcasts" },
    { label: t("nav_radio"), icon: Radio, path: "/radio" },
    { label: t("nav_live"), icon: RadioTower, path: "/live" },
    { label: t("nav_feeds"), icon: Newspaper, path: "/feeds" },
  ];

  const SIDEBAR_CONTENT_AUTH = [
    { label: t("nav_subscription"), icon: Users, path: "/subscription" },
  ];

  const SIDEBAR_LIBRARY = [
    { label: t("nav_subscriptions"), icon: Users, path: "/subscriptions" },
    { label: t("nav_rent"), icon: Wallet, path: "/rent" },
    { label: t("nav_wallet"), icon: Coins, path: "/wallet" },
    { label: t("nav_liked"), icon: Heart, path: "/liked" },
    { label: t("nav_watchLater"), icon: Clock, path: "/watch-later" },
    { label: t("nav_history"), icon: History, path: "/history" },
    { label: t("nav_downloads"), icon: HardDriveDownload, path: "/downloads" },
    { label: t("nav_referral"), icon: Gift, path: "/referral" },
  ];

  const handleLogout = async () => {
    await dispatch(logoutUser());
    router.push("/auth/login");
  };

  return (
    <>
      {mobileOpen && (
        <div
          className="fixed inset-0 z-[55] md:hidden"
          style={{
            top: "56px",
            background: "rgba(0,0,0,0.55)",
            backdropFilter: "blur(2px)",
          }}
          onClick={onClose}
        />
      )}

      <aside
        className={cn(
          "fixed top-14 left-0 z-[60] flex flex-col gap-1.5 overflow-y-auto py-2.5",
          "border-r scrollbar-thin",
          "md:relative md:top-auto md:left-auto md:z-auto md:translate-x-0 md:h-full",
          "h-[calc(100vh-56px)]",
          mobileOpen ? "translate-x-0" : "-translate-x-full md:translate-x-0",
        )}
        style={{
          background: "var(--bg)",
          borderColor: "var(--border)",
          width: collapsed ? "56px" : "200px",
          transition: "width 0.22s ease",
          overflowX: "hidden",
          scrollbarWidth: "none",
        }}
      >
        {/* Primary nav */}
        <nav className="flex flex-col gap-0.5">
          {SIDEBAR_PRIMARY.map((item) => (
            <SidebarItem
              key={item.path}
              {...item}
              isActive={pathname === item.path}
              collapsed={collapsed}
              onClick={onClose}
            />
          ))}
        </nav>

        <div
          className="h-px mx-3 my-1"
          style={{ background: "var(--border)" }}
        />

        {/* Content nav */}
        <div className="flex flex-col gap-0.5">
          {!collapsed && (
            <p
              className="px-[18px] py-2 text-[10px] font-semibold uppercase tracking-[0.12em]"
              style={{ color: "var(--text-muted)" }}
            >
              {t("sidebar_content")}
            </p>
          )}
          {SIDEBAR_CONTENT.map((item) => (
            <SidebarItem
              key={item.path}
              {...item}
              isActive={pathname === item.path}
              collapsed={collapsed}
              onClick={onClose}
            />
          ))}
          {isAuthenticated &&
            SIDEBAR_CONTENT_AUTH.map((item) => (
              <SidebarItem
                key={item.path}
                {...item}
                isActive={pathname === item.path}
                collapsed={collapsed}
                onClick={onClose}
              />
            ))}
        </div>

        {/* Library — authenticated only */}
        {isAuthenticated && (
          <>
            <div
              className="h-px mx-3 my-1"
              style={{ background: "var(--border)" }}
            />
            <div className="flex flex-col gap-0.5">
              {!collapsed && (
                <p
                  className="px-[18px] py-2 text-[10px] font-semibold uppercase tracking-[0.12em]"
                  style={{ color: "var(--text-muted)" }}
                >
                  {t("sidebar_library")}
                </p>
              )}
              {SIDEBAR_LIBRARY.map((item) => (
                <SidebarItem
                  key={item.path}
                  {...item}
                  isActive={pathname === item.path}
                  collapsed={collapsed}
                  onClick={onClose}
                />
              ))}
            </div>
          </>
        )}

        {/* More Apps */}
        <div
          className="h-px mx-3 my-1"
          style={{ background: "var(--border)" }}
        />
        <MoreAppsPanel collapsed={collapsed} />

        {/* ── Bottom section ─────────────────────────────────────────── */}
        <div
          className={cn(
            "mt-auto",
            collapsed ? "px-1.5 pt-4 pb-2" : "pt-3 pb-1",
          )}
        >
          <div className={cn(collapsed ? "" : "px-[18px] mt-2 mb-2")}>
            {isAuthenticated ? (
              <button
                onClick={handleLogout}
                title={collapsed ? t("nav_logout") : undefined}
                className={cn(
                  "w-full flex items-center rounded-lg transition-colors text-xs font-semibold",
                  collapsed ? "justify-center p-2" : "gap-2 px-3 py-2",
                )}
                style={{ background: "rgba(239,68,68,0.08)", color: "#ef4444" }}
              >
                <LogOut size={collapsed ? 18 : 14} />
                {!collapsed && <span>{t("nav_logout")}</span>}
              </button>
            ) : (
              <Link
                href="/auth/login"
                title={collapsed ? t("nav_login") : undefined}
                className={cn(
                  "flex items-center rounded-lg transition-colors text-xs font-semibold",
                  collapsed ? "justify-center p-2" : "gap-2 px-3 py-2",
                )}
                style={{
                  background: "rgba(var(--accent-rgb),0.1)",
                  color: "var(--accent)",
                }}
              >
                <LogIn size={collapsed ? 18 : 14} />
                {!collapsed && <span>{t("nav_login")}</span>}
              </Link>
            )}
          </div>

          {!collapsed && <CompanyPanel settings={settings} pages={pages} />}

          {collapsed && (
            <div className="flex justify-center pt-2 pb-1 opacity-30">
              <Image
                src={IMAGES.appIcon}
                alt="Doliplay"
                width={18}
                height={18}
                className="rounded"
                priority={false}
              />
            </div>
          )}
        </div>
      </aside>
    </>
  );
}
