"use client";

import { useCallback, useEffect, useState } from "react";
import Image from "next/image";
import {
  Users,
  BadgeCheck,
  CheckCircle2,
  Globe,
  AlertCircle,
  Bell,
  Link2,
} from "lucide-react";
import { useRouter } from "next/navigation";
import { useAppDispatch, useAppSelector } from "@/store/hooks";
import { fetchSubscribeList, removeSubscription } from "@/store/slices/subscriberSlice";
import { useSubscribe } from "@/hooks/useSubscribe";
import { SubscriberChannel } from "@/services/subscriberService";
import { useInfiniteScroll } from "@/hooks/useInfiniteScroll";
import { useTranslation } from "@/i18n";

/* ─────────────────────────────────────────────────────────────────────────────
   Cover gradient fallbacks — keyed to channel name initial
───────────────────────────────────────────────────────────────────────────── */

const COVER_GRADIENTS = [
  "linear-gradient(135deg,#1a1a4e 0%,#0f3460 100%)",
  "linear-gradient(135deg,#16213e 0%,#1a4e3a 100%)",
  "linear-gradient(135deg,#2d1b4e 0%,#0f3460 100%)",
  "linear-gradient(135deg,#1a2e1a 0%,#0f3460 100%)",
  "linear-gradient(135deg,#3a1a1a 0%,#1a1a4e 100%)",
  "linear-gradient(135deg,#1a3a1a 0%,#16213e 100%)",
  "linear-gradient(135deg,#1a1a2e 0%,#3a2d1a 100%)",
  "linear-gradient(135deg,#2d2d1a 0%,#0f3460 100%)",
];

function coverGradient(name: string) {
  return COVER_GRADIENTS[(name.charCodeAt(0) || 0) % COVER_GRADIENTS.length];
}

/* ─────────────────────────────────────────────────────────────────────────────
   Avatar with initial fallback
───────────────────────────────────────────────────────────────────────────── */

function ChannelAvatar({ channel, size = 64 }: { channel: SubscriberChannel; size?: number }) {
  const initials = (channel.channelName || channel.fullName || "?")[0].toUpperCase();
  return (
    <div
      className="relative rounded-full overflow-hidden flex-shrink-0"
      style={{
        width: size,
        height: size,
        border: "3px solid var(--card)",
        boxShadow: channel.isVerified
          ? "0 0 0 2px var(--accent)"
          : "0 0 0 2px var(--border)",
        background: "var(--deep)",
      }}
    >
      {channel.avatar ? (
        <Image src={channel.avatar} alt={channel.channelName} fill className="object-cover" unoptimized sizes={`${size}px`} />
      ) : (
        <div
          className="w-full h-full flex items-center justify-center text-[#ffffff] font-black"
          style={{
            background: coverGradient(channel.channelName),
            fontSize: size * 0.38,
          }}
        >
          {initials}
        </div>
      )}
    </div>
  );
}

/* ─────────────────────────────────────────────────────────────────────────────
   Subscription channel card
───────────────────────────────────────────────────────────────────────────── */

function ChannelCard({ channel, index }: { channel: SubscriberChannel; index: number }) {
  const dispatch = useAppDispatch();
  const router = useRouter();
  const [exiting, setExiting] = useState(false);
  const [showConfirm, setShowConfirm] = useState(false);
  const delay = Math.min(index * 50, 600);

  const hasSocials = channel.website || channel.facebook || channel.instagram || channel.twitter;
  const isDefaultDesc = channel.description === "Hey, I am user on Doliplay App." || !channel.description;

  const { t } = useTranslation();
  const { loading: subLoading, toggle: toggleSubscribe } = useSubscribe(
    channel.id,
    true,                           // always subscribed on this page
    channel.isCreator ? 2 : 1,
  );

  const handleUnsubscribe = async () => {
    if (!showConfirm) { setShowConfirm(true); return; }
    // call API then animate card out
    await toggleSubscribe();
    setExiting(true);
    setTimeout(() => dispatch(removeSubscription(channel.id)), 320);
  };

  return (
    <div
      className="flex flex-col rounded-2xl overflow-hidden cursor-pointer transition-transform duration-150 hover:scale-[1.02] active:scale-[0.99]"
      style={{
        background: "var(--card)",
        border: "1px solid var(--border-soft)",
        boxShadow: "0 4px 20px rgba(0,0,0,0.25)",
        animation: exiting
          ? "sub-card-out 0.32s ease forwards"
          : `sub-card-in 0.42s ease forwards`,
        animationDelay: exiting ? "0ms" : `${delay}ms`,
        opacity: 0,
      }}
      onClick={() => router.push(`/profile/${channel.id}`)}
    >
      {/* Cover banner */}
      <div
        className="relative w-full overflow-hidden"
        style={{ height: 80 }}
      >
        {channel.coverImg ? (
          <Image src={channel.coverImg} alt="" fill className="object-cover" unoptimized sizes="400px" />
        ) : (
          <div className="w-full h-full" style={{ background: coverGradient(channel.channelName) }} />
        )}
        {/* Vignette */}
        <div
          className="absolute inset-0 pointer-events-none"
          style={{ background: "linear-gradient(to bottom, transparent 40%, rgba(0,0,0,0.55) 100%)" }}
        />

        {/* Creator badge */}
        {channel.isCreator && (
          <div
            className="absolute top-2 right-2 text-[8px] font-black uppercase tracking-[0.18em] px-2 py-[3px] rounded-sm"
            style={{ background: "var(--accent)", color: "white" }}
          >
            {t("subscriptions_creator")}
          </div>
        )}
      </div>

      {/* Avatar row — overlaps the cover */}
      <div className="px-4 flex items-end justify-between" style={{ marginTop: -32 }}>
        <ChannelAvatar channel={channel} size={64} />

        {/* Social links */}
        {hasSocials && (
          <div className="flex items-center gap-1.5 pb-1">
            {channel.website && (
              <a
                href={channel.website.startsWith("http") ? channel.website : `https://${channel.website}`}
                target="_blank"
                rel="noopener noreferrer"
                className="w-7 h-7 rounded-full flex items-center justify-center transition-all hover:brightness-125"
                style={{ background: "var(--btn-ghost-hover)", border: "1px solid var(--border)" }}
                onClick={(e) => e.stopPropagation()}
              >
                <Globe size={12} color="#888" strokeWidth={1.8} />
              </a>
            )}
            {(channel.instagram || channel.twitter || channel.facebook) && (
              <a
                href="#"
                className="w-7 h-7 rounded-full flex items-center justify-center transition-all hover:brightness-125"
                style={{ background: "var(--btn-ghost-hover)", border: "1px solid var(--border)" }}
                onClick={(e) => e.stopPropagation()}
              >
                <Link2 size={12} color="#888" strokeWidth={1.8} />
              </a>
            )}
          </div>
        )}
      </div>

      {/* Channel info */}
      <div className="px-4 pt-2 pb-4 flex flex-col flex-1">
        {/* Name + verified */}
        <div className="flex items-center gap-1.5 flex-wrap">
          <p className="text-[13px] font-black leading-tight truncate" style={{ color: "var(--text-primary)" }}>
            {channel.channelName}
          </p>
          {channel.isVerified && (
            <BadgeCheck size={14} style={{ color: "var(--accent)", flexShrink: 0 }} strokeWidth={2} />
          )}
        </div>

        {/* Full name */}
        {channel.fullName && channel.fullName !== channel.channelName && (
          <p className="text-[10px] mt-0.5 truncate" style={{ color: "#666" }}>
            {channel.fullName}
          </p>
        )}

        {/* Stats row */}
        <div className="flex items-center gap-2 mt-2 flex-wrap">
          <div className="flex items-center gap-1">
            <Users size={10} style={{ color: "var(--accent)" }} strokeWidth={2} />
            <span className="text-[10px] font-bold" style={{ color: "var(--text-muted)" }}>
              {channel.totalSubscribers}
            </span>
            <span className="text-[10px]" style={{ color: "#555" }}>
              {channel.totalSubscribersRaw === 1 ? t("subscriptions_subscriber") : t("subscriptions_subscribers")}
            </span>
          </div>
          {channel.countryName && channel.countryName !== channel.channelName && (
            <>
              <span style={{ color: "#444", fontSize: 9 }}>·</span>
              <span className="text-[10px]" style={{ color: "#555" }}>{channel.countryName}</span>
            </>
          )}
        </div>

        {/* Description */}
        {!isDefaultDesc && (
          <p className="text-[11px] mt-2 leading-relaxed line-clamp-2" style={{ color: "#777" }}>
            {channel.description}
          </p>
        )}

        {/* Unsubscribe button — stopPropagation so card click doesn't also navigate */}
        <div className="mt-3" onClick={(e) => e.stopPropagation()}>
          {showConfirm ? (
            <div className="flex items-center gap-2">
              <button
                className="flex-1 py-1.5 rounded-full text-[11px] font-bold text-[#ffffff] transition-all active:scale-95 disabled:opacity-60"
                style={{ background: "rgba(220,38,38,0.85)", boxShadow: "0 2px 10px rgba(220,38,38,0.3)" }}
                onClick={handleUnsubscribe}
                disabled={subLoading}
              >
                {subLoading ? "…" : t("subscriptions_yesUnsub")}
              </button>
              <button
                className="py-1.5 px-3 rounded-full text-[11px] font-semibold transition-all active:scale-95"
                style={{ background: "var(--border)", color: "var(--text-muted)", border: "1px solid var(--border)" }}
                onClick={() => setShowConfirm(false)}
              >
                {t("subscriptions_cancel")}
              </button>
            </div>
          ) : (
            <button
              className="w-full flex items-center justify-center gap-1.5 py-1.5 rounded-full text-[11px] font-bold text-[#ffffff] transition-all duration-150 active:scale-95 hover:brightness-90"
              style={{
                background: "rgba(var(--accent-rgb),0.15)",
                color: "var(--accent)",
                border: "1px solid rgba(var(--accent-rgb),0.3)",
              }}
              onClick={() => setShowConfirm(true)}
            >
              <CheckCircle2 size={12} strokeWidth={2.5} />
              {t("subscriptions_subscribed")}
            </button>
          )}
        </div>
      </div>
    </div>
  );
}

/* ─────────────────────────────────────────────────────────────────────────────
   Skeleton card
───────────────────────────────────────────────────────────────────────────── */

function CardSkeleton() {
  return (
    <div className="rounded-2xl overflow-hidden animate-pulse" style={{ background: "var(--card)", border: "1px solid var(--border-soft)" }}>
      <div style={{ height: 80, background: "var(--deep)" }} />
      <div className="px-4" style={{ marginTop: -20 }}>
        <div className="w-16 h-16 rounded-full" style={{ background: "var(--deep)", border: "3px solid var(--card)" }} />
      </div>
      <div className="px-4 py-3 flex flex-col gap-2.5">
        <div className="h-3.5 rounded-full" style={{ background: "var(--deep)", width: "65%" }} />
        <div className="h-2.5 rounded-full" style={{ background: "var(--deep)", width: "42%" }} />
        <div className="h-2.5 rounded-full" style={{ background: "var(--deep)", width: "55%" }} />
        <div className="h-8 rounded-full mt-1" style={{ background: "var(--deep)" }} />
      </div>
    </div>
  );
}

/* ─────────────────────────────────────────────────────────────────────────────
   SubscriptionsPage
───────────────────────────────────────────────────────────────────────────── */

export default function SubscriptionsPage() {
  const dispatch = useAppDispatch();
  const { t } = useTranslation();

  const { channels, isLoading, isLoadingMore, error, hasMore, currentPage, totalRows } =
    useAppSelector((s) => s.subscriber);

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

  const handleLoadMore = useCallback(() => {
    dispatch(fetchSubscribeList(currentPage + 1));
  }, [dispatch, currentPage]);

  const sentinelRef = useInfiniteScroll({
    hasMore,
    isLoading: isLoading || isLoadingMore,
    onLoadMore: handleLoadMore,
  });

  return (
    <>
      {/* ── Header ──────────────────────────────────────────────────────── */}
      <div
        className="relative px-5 pt-6 pb-5 overflow-hidden"
        style={{
          background: "linear-gradient(180deg,rgba(var(--accent-rgb),0.06) 0%,transparent 100%)",
          borderBottom: "1px solid var(--border-soft)",
        }}
      >
        <div
          className="absolute -top-4 -right-4 w-40 h-40 rounded-full pointer-events-none"
          style={{ background: "radial-gradient(circle,rgba(var(--accent-rgb),0.09) 0%,transparent 70%)" }}
        />
        <div className="flex items-center justify-between">
          <div className="flex items-center gap-3.5">
            <div
              className="w-11 h-11 rounded-xl flex items-center justify-center shrink-0"
              style={{ background: "rgba(var(--accent-rgb),0.11)", border: "1px solid rgba(var(--accent-rgb),0.2)" }}
            >
              <Bell size={20} style={{ color: "var(--accent)" }} strokeWidth={1.8} />
            </div>
            <div>
              <h1 className="text-base font-black tracking-tight leading-tight" style={{ color: "var(--text-primary)" }}>{t("subscriptions_title")}</h1>
              {!isLoading && (
                <p className="text-[11px] mt-0.5" style={{ color: "#666" }}>
                  {totalRows > 0
                    ? `${totalRows} ${totalRows !== 1 ? t("subscriptions_channelsSuffix") : t("subscriptions_channelSuffix")}`
                    : t("subscriptions_channelsFollow")}
                </p>
              )}
            </div>
          </div>

          {/* Live count badge */}
          {channels.length > 0 && !isLoading && (
            <div
              className="flex items-center gap-1.5 px-3 py-1.5 rounded-full"
              style={{ background: "rgba(var(--accent-rgb),0.1)", border: "1px solid rgba(var(--accent-rgb),0.18)" }}
            >
              <Users size={12} style={{ color: "var(--accent)" }} strokeWidth={2} />
              <span className="text-[11px] font-bold" style={{ color: "var(--accent)" }}>
                {channels.length}
              </span>
            </div>
          )}
        </div>
      </div>

      {/* ── Content ─────────────────────────────────────────────────────── */}
      <div className="px-5 py-5 pb-28">
        {isLoading ? (
          <div className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-4 gap-4">
            {Array.from({ length: 8 }).map((_, i) => <CardSkeleton key={i} />)}
          </div>
        ) : error ? (
          <div className="flex flex-col items-center justify-center py-24 gap-4">
            <AlertCircle size={36} color="#555" strokeWidth={1.2} />
            <p className="text-sm" style={{ color: "#888" }}>{error}</p>
            <button
              onClick={() => dispatch(fetchSubscribeList(1))}
              className="px-5 py-2 rounded-full text-xs font-bold text-[#ffffff] active:scale-95"
              style={{ background: "var(--accent)" }}
            >
              {t("state_tryAgain")}
            </button>
          </div>
        ) : channels.length === 0 ? (
          <div className="flex flex-col items-center justify-center py-24 gap-5">
            <div
              className="w-20 h-20 rounded-full flex items-center justify-center"
              style={{ background: "rgba(var(--accent-rgb),0.07)", border: "1px solid rgba(var(--accent-rgb),0.14)" }}
            >
              <Bell size={34} style={{ color: "var(--accent)", opacity: 0.4 }} strokeWidth={1.2} />
            </div>
            <div className="text-center">
              <p className="text-sm font-semibold" style={{ color: "var(--text-primary)" }}>{t("subscriptions_noSubs")}</p>
              <p className="text-xs mt-1" style={{ color: "#555" }}>
                {t("subscriptions_subscribeTo")}
              </p>
            </div>
          </div>
        ) : (
          <>
            <div className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-4 gap-4">
              {channels.map((ch, i) => (
                <ChannelCard key={ch.id} channel={ch} index={i} />
              ))}
            </div>

            <div ref={sentinelRef} className="h-1 mt-5" />

            {isLoadingMore && (
              <div className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-4 gap-4 mt-4">
                {Array.from({ length: 4 }).map((_, i) => <CardSkeleton key={i} />)}
              </div>
            )}

            {!hasMore && channels.length > 0 && !isLoading && !isLoadingMore && (
              <div className="flex items-center justify-center gap-2 py-8 mt-2">
                <div className="h-px flex-1" style={{ background: "var(--border-soft)" }} />
                <div className="flex items-center gap-1.5">
                  <Users size={11} style={{ color: "#444" }} strokeWidth={1.5} />
                  <span className="text-[11px] font-medium" style={{ color: "#444" }}>
                    {t("subscriptions_allShown")}
                  </span>
                </div>
                <div className="h-px flex-1" style={{ background: "var(--border-soft)" }} />
              </div>
            )}
          </>
        )}
      </div>
    </>
  );
}
