import { Ionicons } from "@expo/vector-icons";
import type { FC } from "react";
import { Platform, TouchableOpacity, View } from "react-native";
import { Text } from "@/components/common/Text";
import { Loader } from "@/components/Loader";
import { SyncPlaySpinner } from "@/components/syncplay/SyncPlaySpinner";
import { useControlsSafeAreaInsets } from "@/hooks/useControlsSafeAreaInsets";
import { useSyncPlay } from "@/providers/SyncPlay/SyncPlayProvider";
import { useSettings } from "@/utils/atoms/settings";
import AudioSlider from "./AudioSlider";
import BrightnessSlider from "./BrightnessSlider";
import { ICON_SIZES } from "./constants";

// SyncPlay cyan color (matches Jellyfin-web)
const SYNC_PLAY_COLOR = "#00a4dc";

interface CenterControlsProps {
  showControls: boolean;
  isPlaying: boolean;
  isBuffering: boolean;
  showAudioSlider: boolean;
  setShowAudioSlider: (show: boolean) => void;
  togglePlay: () => void;
  handleSkipBackward: () => void;
  handleSkipForward: () => void;
  // Chapter navigation props
  hasChapters?: boolean;
  hasPreviousChapter?: boolean;
  hasNextChapter?: boolean;
  goToPreviousChapter?: () => void;
  goToNextChapter?: () => void;
}

export const CenterControls: FC<CenterControlsProps> = ({
  showControls,
  isPlaying,
  isBuffering,
  showAudioSlider,
  setShowAudioSlider,
  togglePlay,
  handleSkipBackward,
  handleSkipForward,
  hasChapters = false,
  hasPreviousChapter = false,
  hasNextChapter = false,
  goToPreviousChapter,
  goToNextChapter,
}) => {
  const { settings } = useSettings();
  const insets = useControlsSafeAreaInsets();

  // SyncPlay state from global provider
  const {
    isEnabled: isSyncPlayEnabled,
    groupInfo,
    pendingPlaybackCommand,
  } = useSyncPlay();
  const isSyncPlayWaiting = isSyncPlayEnabled && groupInfo?.State === "Waiting";
  // Show the rotating SyncPlay icon ("schedule-play" in jellyfin-web) while a
  // play/pause request is in flight to the server.
  const isSyncPlayScheduling =
    isSyncPlayEnabled && pendingPlaybackCommand !== null;

  return (
    <View
      style={{
        position: "absolute",
        top: "50%",
        left: insets.left,
        right: insets.right,
        flexDirection: "row",
        justifyContent: "space-between",
        alignItems: "center",
        transform: [{ translateY: -22.5 }],
        paddingHorizontal: hasChapters ? "18%" : "28%",
      }}
      pointerEvents={showControls ? "box-none" : "none"}
    >
      {!settings?.hideBrightnessSlider && (
        <View
          style={{
            position: "absolute",
            alignItems: "center",
            transform: [{ rotate: "270deg" }],
            left: 0,
            bottom: 30,
          }}
        >
          <BrightnessSlider />
        </View>
      )}

      {!Platform.isTV && (
        <TouchableOpacity onPress={handleSkipBackward}>
          <View
            style={{
              position: "relative",
              justifyContent: "center",
              alignItems: "center",
            }}
          >
            <Ionicons
              name='refresh-outline'
              size={ICON_SIZES.CENTER}
              color='white'
              style={{
                transform: [{ scaleY: -1 }, { rotate: "180deg" }],
              }}
            />
            <Text
              style={{
                position: "absolute",
                color: "white",
                fontSize: 16,
                fontWeight: "bold",
                bottom: 10,
              }}
            >
              {settings?.rewindSkipTime}
            </Text>
          </View>
        </TouchableOpacity>
      )}

      {!Platform.isTV && hasChapters && (
        <TouchableOpacity
          onPress={goToPreviousChapter}
          disabled={!hasPreviousChapter}
          style={{ opacity: hasPreviousChapter ? 1 : 0.3 }}
        >
          <Ionicons
            name='play-back'
            size={ICON_SIZES.CENTER - 10}
            color='white'
          />
        </TouchableOpacity>
      )}

      <View style={Platform.isTV ? { flex: 1, alignItems: "center" } : {}}>
        <TouchableOpacity onPress={togglePlay}>
          {isSyncPlayScheduling ? (
            // SyncPlay command in flight - rotating spinner ("schedule-play")
            <SyncPlaySpinner size={ICON_SIZES.CENTER} />
          ) : isSyncPlayWaiting ? (
            // SyncPlay waiting indicator - clock icon, still pressable to toggle
            <Ionicons
              name='time'
              size={ICON_SIZES.CENTER}
              color={SYNC_PLAY_COLOR}
            />
          ) : !isBuffering ? (
            <Ionicons
              name={isPlaying ? "pause" : "play"}
              size={ICON_SIZES.CENTER}
              color='white'
            />
          ) : (
            <Loader size={"large"} />
          )}
        </TouchableOpacity>
      </View>

      {!Platform.isTV && hasChapters && (
        <TouchableOpacity
          onPress={goToNextChapter}
          disabled={!hasNextChapter}
          style={{ opacity: hasNextChapter ? 1 : 0.3 }}
        >
          <Ionicons
            name='play-forward'
            size={ICON_SIZES.CENTER - 10}
            color='white'
          />
        </TouchableOpacity>
      )}

      {!Platform.isTV && (
        <TouchableOpacity onPress={handleSkipForward}>
          <View
            style={{
              position: "relative",
              justifyContent: "center",
              alignItems: "center",
            }}
          >
            <Ionicons
              name='refresh-outline'
              size={ICON_SIZES.CENTER}
              color='white'
            />
            <Text
              style={{
                position: "absolute",
                color: "white",
                fontSize: 16,
                fontWeight: "bold",
                bottom: 10,
              }}
            >
              {settings?.forwardSkipTime}
            </Text>
          </View>
        </TouchableOpacity>
      )}

      {!settings?.hideVolumeSlider && (
        <View
          style={{
            position: "absolute",
            alignItems: "center",
            transform: [{ rotate: "270deg" }],
            bottom: 30,
            right: 0,
            opacity: showAudioSlider || showControls ? 1 : 0,
          }}
        >
          <AudioSlider setVisibility={setShowAudioSlider} />
        </View>
      )}
    </View>
  );
};
