import { useState, useEffect, useCallback, useReducer, useRef } from "react";
import { useNavigate } from "react-router-dom";
import { useAuthStore } from "@/stores/auth-store";
import type { Particle } from "@/api/types";
import { useLiveParticleChildren } from "@/hooks/use-particle";
import { parseParticlePath, toFirestoreDocPath, type ParticlePath } from "@/lib/particle-path";
import { ComposeOverlay } from "@/features/compose/compose-overlay";
import { PlaybackPageIndicator } from "@/features/playback/playback-page-indicator";
import { ParticleRenderer } from "@/features/playback/particle-renderer";
import { Avatar, AvatarFallback } from "@/components/ui/avatar";
import ControlsIndicator from "@/features/compose/controls-indicator";
import { updateStreamPlaybackMarker } from "@/lib/firestore-particles";

// --- Playback reducer ---

type PlaybackStatus = "idle" | "playing" | "ended";

interface PlaybackState {
  currentIndex: number;
  status: PlaybackStatus;
  paused: boolean;
}

type PlaybackAction =
  | { type: "INIT"; particleCount: number, initialIndex?: number }
  | { type: "NEXT"; particleCount: number }
  | { type: "PREV" }
  | { type: "GO_TO"; index: number; particleCount: number }
  | { type: "PAUSE" }
  | { type: "RESUME" }
  | { type: "SYNC_PARTICLES"; particleCount: number };

function playbackReducer(
  state: PlaybackState,
  action: PlaybackAction,
): PlaybackState {
  switch (action.type) {
    case "INIT":
      return {
        currentIndex: action.initialIndex ?? 0,
        status: action.particleCount > 0 ? "playing" : "idle",
        paused: false,
      };
    case "NEXT":
      if (state.currentIndex < action.particleCount - 1) {
        return { ...state, currentIndex: state.currentIndex + 1, paused: false };
      }
      return { ...state, status: "ended", paused: false };
    case "PREV":
      if (state.currentIndex > 0) {
        return {
          ...state,
          currentIndex: state.currentIndex - 1,
          status: "playing",
          paused: false,
        };
      }
      return state;
    case "GO_TO":
      if (action.index >= 0 && action.index < action.particleCount) {
        return {
          ...state,
          currentIndex: action.index,
          status: "playing",
          paused: false,
        };
      }
      return state;
    case "PAUSE":
      return { ...state, paused: true };
    case "RESUME":
      return { ...state, paused: false };
    case "SYNC_PARTICLES":
      // Clamp index if particles were removed; don't reset position
      if (action.particleCount === 0) {
        return { currentIndex: 0, status: "idle", paused: state.paused };
      }
      if (state.currentIndex >= action.particleCount) {
        return { ...state, currentIndex: action.particleCount - 1 };
      }
      return state;
  }
}

const initialState: PlaybackState = {
  currentIndex: 0,
  status: "idle",
  paused: false,
};

// --- StreamView ---

interface StreamViewProps {
  streamParticle: Particle & { type: "stream" };
  path: ParticlePath;
}

export function StreamView({ path, streamParticle }: StreamViewProps) {
  const { networkId } = parseParticlePath(path);
  const navigate = useNavigate();
  const { children } = useLiveParticleChildren(path, "created_at", "asc");

  const [state, dispatch] = useReducer(playbackReducer, initialState);
  const [composeActive, setComposeActive] = useState(false);
  const hasInitializedRef = useRef<string | null>(null);

  const userId = useAuthStore((s) => s.user?.id);

  // Init playback once per stream entry, only after children have loaded
  useEffect(() => {
    if (children.length === 0) return;
    if (hasInitializedRef.current === streamParticle.id) return;
    hasInitializedRef.current = streamParticle.id;

    const playbackPosition = streamParticle.playback_markers?.[userId ?? ""];
    let initialIndex = 0;

    if (playbackPosition) {
      const foundIndex = children.findIndex(
        (c) => c.created_at.getTime() === playbackPosition.getTime(),
      );
      if (foundIndex !== -1) {
        initialIndex = foundIndex;
      }
    }

    dispatch({ type: "INIT", particleCount: children.length, initialIndex });
  }, [streamParticle.id, userId, children]);

  // Sync on subsequent changes (new particle appended, removed, etc.)
  useEffect(() => {
    if (hasInitializedRef.current !== streamParticle.id) return;
    dispatch({ type: "SYNC_PARTICLES", particleCount: children.length });
  }, [children.length, streamParticle.id]);

  // Pause/resume playback when compose overlay opens/closes
  useEffect(() => {
    if (composeActive) dispatch({ type: "PAUSE" });
    else dispatch({ type: "RESUME" });
  }, [composeActive]);

  const next = useCallback(() => {
    dispatch({ type: "NEXT", particleCount: children.length });
  }, [children.length]);

  const prev = useCallback(() => {
    dispatch({ type: "PREV" });
  }, []);

  const goTo = useCallback(
    (index: number) => {
      dispatch({ type: "GO_TO", index, particleCount: children.length });
    },
    [children.length],
  );

  // Playback keyboard: arrows, escape

  useEffect(() => {
    const handleKeyDown = (e: KeyboardEvent) => {
      if (composeActive) return;

      const target = e.target as HTMLElement;
      if (
        target.tagName === "INPUT" ||
        target.tagName === "TEXTAREA" ||
        target.isContentEditable
      ) {
        return;
      }

      switch (e.key) {
        case "ArrowRight":
        case "ArrowDown":
          e.preventDefault();
          next();
          break;
        case "ArrowLeft":
        case "ArrowUp":
          e.preventDefault();
          prev();
          break;
        case "Escape":
          e.preventDefault();
          navigate(`/${networkId}`);
          break;
      }
    }
    window.addEventListener("keydown", handleKeyDown);
    return () => window.removeEventListener("keydown", handleKeyDown);
  },
    [composeActive, next, prev, navigate, networkId],
  );

  const currentParticle = children[state.currentIndex] ?? null;

  useEffect(() => {
    if (!userId || !currentParticle) return;

    const streamDocPath = toFirestoreDocPath(path);
    updateStreamPlaybackMarker(streamDocPath, userId, currentParticle.created_at);
  }, [currentParticle, path])

  // Stream name from properties (narrowed to stream type)
  const streamName = streamParticle.properties.name

  // Author info from current particle
  const authorEmail = currentParticle?.created_by_email ?? "";
  const authorInitials = authorEmail.split("@")[0]?.slice(0, 2).toUpperCase() ?? "";

  if (children.length === 0) {
    return (
      <div className="flex h-full flex-col items-center justify-center gap-4 bg-black text-white">
        <p className="text-muted-foreground text-sm">
          No particles in this stream yet
        </p>
        <ControlsIndicator type="reply" />
        <ComposeOverlay
          networkId={networkId!}
          targetPath={path}
          onActiveChange={setComposeActive}
        />
      </div>
    );
  }

  return (
    <div className="relative flex h-full flex-col bg-black text-white">
      {/* Progress indicator */}
      <div className="z-10 absolute left-0 right-0">
        <PlaybackPageIndicator
          total={children.length}
          current={state.currentIndex}
          onGoTo={goTo}
        />
      </div>

      {/* Author overlay */}
      {currentParticle && (
        <div className="absolute top-5 left-0 right-0 z-10 flex items-center justify-center gap-2">
          <Avatar size="sm">
            <AvatarFallback className="bg-white/20 text-[10px] font-medium text-white">
              {authorInitials}
            </AvatarFallback>
          </Avatar>
          <span className="text-xs text-white/70">
            {authorEmail.split("@")[0]}
          </span>
        </div>
      )}

      {/* Main playback area */}
      <div className="flex-1 overflow-hidden">
        {currentParticle && (
          <ParticleRenderer
            particle={currentParticle}
            paused={state.paused}
            onNext={next}
            onPrev={prev}
          />
        )}
      </div>

      <ComposeOverlay
        networkId={networkId!}
        targetPath={path}
        onActiveChange={setComposeActive}
      />

      {/* Bottom overlay: stream info + reply */}
      <div className="absolute right-0 bottom-0 z-10 flex justify-center p-2">
        <div className="flex w-full items-center gap-2.5 rounded-full pl-1 pr-2 py-1 bg-black/30 backdrop-blur-sm">
          <ControlsIndicator type={"reply"} />
        </div>
      </div>
    </div>
  );
}
