"use client";
import { useState, useEffect, useCallback } from "react";
import { useRouter } from "next/navigation";
import { StreamVideoClient } from "@stream-io/video-react-sdk";
import { Radio, RefreshCw, Plus } from "lucide-react";
import { useAppSelector } from "@/store/hooks";
import { useGeneralSettings } from "@/lib/GeneralSettingsContext";
import { useLoginPrompt } from "@/lib/LoginPromptContext";
import { useTranslation } from "@/i18n";
import { LiveCard } from "./LiveCard";
import { MotionSection, MotionItem } from "@/components/motion/MotionSection";
import type { LiveUser } from "@/types/live";

/* Dummy streams shown when is_live_streaming_fake = "1" */
const DUMMY_USERS: LiveUser[] = [
  {
    id: "dummy-1",
    callId: "dummy-1",
    hostName: "Priya Patel",
    hostImage: "https://images.unsplash.com/photo-1529626455594-4ff0802cfb7e?w=400&auto=format&fit=crop",
    viewerCount: 15400,
    isFake: true,
  },
  {
    id: "dummy-2",
    callId: "dummy-2",
    hostName: "Rahul Sharma",
    hostImage: "https://i.pravatar.cc/400?img=11",
    viewerCount: 8200,
    isFake: true,
  },
  {
    id: "dummy-3",
    callId: "dummy-3",
    hostName: "Anjali Desai",
    hostImage: "https://i.pravatar.cc/400?img=5",
    viewerCount: 21000,
    isFake: true,
  },
  {
    id: "dummy-4",
    callId: "dummy-4",
    hostName: "Jane Smith",
    hostImage: "https://images.unsplash.com/photo-1513207565459-d7f36bfa1222?w=400&auto=format&fit=crop",
    viewerCount: 21000,
    isFake: true,
  },
  {
    id: "dummy-5",
    callId: "dummy-5",
    hostName: "Alice Johnson",
    hostImage: "https://images.unsplash.com/photo-1533435137002-455932c8538f?w=400&auto=format&fit=crop",
    viewerCount: 15000,
    isFake: true,
  },
  {
    id: "dummy-6",
    callId: "dummy-6",
    hostName: "Bob Brown",
    hostImage: "https://plus.unsplash.com/premium_photo-1682614334089-da623bdcaf2d?w=400&auto=format&fit=crop",
    viewerCount: 1200,
    isFake: true,
  },
];

/* ── Skeleton card ─────────────────────────────────────────────────────── */
function LiveCardSkeleton() {
  return (
    <div
      className="rounded-2xl overflow-hidden animate-pulse"
      style={{ background: "var(--card)", border: "1px solid var(--border-soft)" }}
    >
      <div className="animate-pulse" style={{ height: 180, background: "var(--deep)" }} />
      <div className="flex items-center gap-2 px-3 py-2.5">
        <div className="w-7 h-7 rounded-full shrink-0" style={{ background: "var(--deep)" }} />
        <div className="h-3 rounded-full flex-1" style={{ background: "var(--deep)", maxWidth: 100 }} />
      </div>
    </div>
  );
}

/* ── Main component ────────────────────────────────────────────────────── */
export function LivePage() {
  const [liveUsers, setLiveUsers] = useState<LiveUser[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [isRefreshing, setIsRefreshing] = useState(false);
  const router = useRouter();
  const { t } = useTranslation();
  const { settings } = useGeneralSettings();
  const user = useAppSelector((s) => s.auth.user);
  const isAuthenticated = useAppSelector((s) => s.auth.isAuthenticated);
  const { open: openLoginPrompt } = useLoginPrompt();

  const fetchStreams = useCallback(async (refreshing = false) => {
    if (refreshing) setIsRefreshing(true);
    else setIsLoading(true);

    try {
      if (!settings?.streamApiKey || !user?.stream_token) {
        setLiveUsers(settings?.isLiveStreamingFake ? DUMMY_USERS : []);
        return;
      }

      const streamClient = new StreamVideoClient({
        apiKey: settings.streamApiKey,
        user: {
          id: String(user.id),
          name: user.channel_name || user.full_name,
          image: user.image,
        },
        token: user.stream_token,
      });

      try {
        const res = await (streamClient as any).queryCalls({
          filterConditions: {
            type: { $eq: "livestream" },
            ongoing: { $eq: true },
          },
          sort: [{ field: "created_at", direction: -1 }],
          watch: false,
          limit: 30,
        });

        const calls: any[] = res?.calls ?? [];
        const realStreams: LiveUser[] = calls.map((call: any) => ({
          id: call.cid ?? call.id,
          callId: call.id,
          hostName: call.data?.created_by?.name ?? "Unknown",
          hostImage: call.data?.created_by?.image ?? "",
          viewerCount: call.data?.session?.participant_count?.total ?? 0,
          isFake: false,
        }));

        const fakeStreams = settings.isLiveStreamingFake ? DUMMY_USERS : [];
        setLiveUsers([...realStreams, ...fakeStreams]);
      } finally {
        streamClient.disconnectUser().catch(() => {});
      }
    } catch (e) {
      console.error("Failed to fetch live streams", e);
      setLiveUsers(settings?.isLiveStreamingFake ? DUMMY_USERS : []);
    } finally {
      setIsLoading(false);
      setIsRefreshing(false);
    }
  }, [settings, user]);

  useEffect(() => {
    if (settings !== null) {
      fetchStreams();
    }
  }, [settings, fetchStreams]);

  const handleGoLive = () => {
    if (!isAuthenticated) {
      openLoginPrompt();
      return;
    }
    const callId = `stream_${Date.now()}`;
    router.push(`/live/${callId}?host=true`);
  };

  const handleJoinStream = (live: LiveUser) => {
    if (!isAuthenticated) {
      openLoginPrompt();
      return;
    }
    if (live.isFake) {
      // Dummy streams just show a "not available" state for now
      router.push(`/live/${live.callId}?dummy=true`);
    } else {
      router.push(`/live/${live.callId}`);
    }
  };

  return (
    <div className="min-h-screen pb-24" style={{ background: "var(--bg)" }}>
      {/* ── Header ─────────────────────────────────────────────────────── */}
      <div
        className="sticky top-14 z-20 flex items-center justify-between px-5 py-4 border-b"
        style={{ background: "var(--bg)", borderColor: "var(--border-soft)" }}
      >
        <div className="flex items-center gap-2.5">
          <div
            className="w-8 h-8 rounded-lg flex items-center justify-center"
            style={{ background: "rgba(220,38,38,0.12)", border: "1px solid rgba(220,38,38,0.25)" }}
          >
            <Radio size={16} color="#dc2626" />
          </div>
          <h1 className="text-sm font-black tracking-tight" style={{ color: "var(--text-primary)" }}>
            {t("live_streaming")}
          </h1>
        </div>

        <div className="flex items-center gap-2">
          {/* Refresh */}
          <button
            onClick={() => fetchStreams(true)}
            disabled={isRefreshing}
            className="w-8 h-8 rounded-full flex items-center justify-center transition-all active:scale-90 disabled:opacity-50"
            style={{ background: "var(--card)", color: "var(--text-muted)" }}
          >
            <RefreshCw size={14} className={isRefreshing ? "animate-spin" : ""} />
          </button>

          {/* Go Live */}
          <button
            onClick={handleGoLive}
            className="flex items-center gap-1.5 px-3.5 py-1.5 rounded-xl text-xs font-black text-white transition-all active:scale-95"
            style={{
              background: "linear-gradient(135deg, #dc2626, #b91c1c)",
              boxShadow: "0 4px 18px rgba(220,38,38,0.35)",
            }}
          >
            <Plus size={13} strokeWidth={2.5} />
            {t("live_goLive")}
          </button>
        </div>
      </div>

      {/* ── Content ────────────────────────────────────────────────────── */}
      <div className="px-4 py-5">
        {isLoading ? (
          <div className="grid grid-cols-2 gap-3">
            {Array.from({ length: 6 }).map((_, i) => (
              <LiveCardSkeleton key={i} />
            ))}
          </div>
        ) : liveUsers.length === 0 ? (
          /* Empty state */
          <div className="flex flex-col items-center justify-center py-24 gap-4">
            <div
              className="w-20 h-20 rounded-full flex items-center justify-center"
              style={{ background: "var(--card)", border: "1px solid var(--border-soft)" }}
            >
              <Radio size={32} style={{ color: "var(--text-muted)" }} />
            </div>
            <div className="text-center">
              <p className="text-sm font-semibold mb-1" style={{ color: "var(--text-muted)" }}>
                {t("live_noStreams")}
              </p>
              <p className="text-xs" style={{ color: "var(--text-muted)" }}>
                {t("live_noStreamsDesc")}
              </p>
            </div>
            <button
              onClick={handleGoLive}
              className="flex items-center gap-1.5 px-4 py-2 rounded-xl text-xs font-bold text-white mt-2"
              style={{ background: "linear-gradient(135deg, #dc2626, #b91c1c)" }}
            >
              <Plus size={13} />
              {t("live_goLive")}
            </button>
          </div>
        ) : (
          <MotionSection className="grid grid-cols-2 gap-3">
            {liveUsers.map((live) => (
              <MotionItem key={live.id}>
                <LiveCard live={live} onClick={() => handleJoinStream(live)} />
              </MotionItem>
            ))}
          </MotionSection>
        )}
      </div>
    </div>
  );
}
