import React, { useEffect, useMemo, useRef, useState } from 'react';
import {
  View,
  Text,
  TouchableOpacity,
  Pressable,
  StyleSheet,
  Dimensions,
} from 'react-native';
import { BlurView } from 'expo-blur';
import { RiveView, useRiveFile, useViewModelInstance, useRiveBoolean, useRive, Fit } from '@rive-app/react-native';
import Animated, {
  useAnimatedStyle,
  withTiming,
  useSharedValue,
  Easing,
} from 'react-native-reanimated';
import * as Haptics from 'expo-haptics';
import { useSafeAreaInsets } from 'react-native-safe-area-context';
import CloseCircleIcon from './icons/CloseCircleIcon';
import { useTheme } from '../../context/ThemeContext';
import { ThemeColors } from '../../constants/ThemeColors';
import LightIconActive from './icons/LightIconActive';
import LightIconInactive from './icons/LightIconInactive';
import DarkIconActive from './icons/DarkIconActive';
import DarkIconInactive from './icons/DarkIconInactive';

interface ThemeSwitcherProps {
  visible: boolean;
  onClose: () => void;
}

export default function ThemeSwitcher({ visible, onClose }: ThemeSwitcherProps) {
  const { theme, isDark, setTheme } = useTheme();
  const colors = ThemeColors[theme];
  const insets = useSafeAreaInsets();
  
  // Calculate modal width inside component
  const modalWidth = useMemo(() => {
    const { width: screenWidth } = Dimensions.get('window');
    return screenWidth; // Full width minus padding (20px each side)
  }, []);

  // theme_switch3.riv / abc.riv: ThemeSwitch view model, isDark boolean, light/dark triggers
  const { riveViewRef, setHybridRef } = useRive();
  const { riveFile, isLoading: riveLoading, error: riveError } = useRiveFile(
    require('../../assets/abc.riv')
  );
  const viewModelInstance = useViewModelInstance(riveFile, {
    viewModelName: 'ThemeSwitch',
  });
  const { value: riveIsDarkValue, setValue: setRiveIsDark } = useRiveBoolean('isDark', viewModelInstance);
  const [hasSynced, setHasSynced] = useState(false);

  // Debug: log when Rive file loads
  useEffect(() => {
    if (riveFile) {
      console.log('[ThemeSwitcher] Rive file loaded');
    }
  }, [riveFile]);

  // Debug: log isDark (app) and riveIsDark (Rive) when they change
  useEffect(() => {
    console.log('[ThemeSwitcher] isDark (app):', isDark, '| riveIsDark (Rive):', riveIsDarkValue);
  }, [isDark, riveIsDarkValue]);

  // Animation values
  const opacity = useSharedValue(0);
  const scale = useSharedValue(0.9);
  const translateY = useSharedValue(20);

  // Sync when modal CLOSED: keep view model in sync with app theme
  useEffect(() => {
    if (!visible && riveFile && setRiveIsDark) {
      setRiveIsDark(isDark);
      setHasSynced(true);
    }
  }, [visible, riveFile, isDark, setRiveIsDark]);

  // When modal opens: sync Rive to app once RiveView is ready (ref can be null on first render)
  const hasSyncedThisOpenRef = useRef(false);
  useEffect(() => {
    if (!visible) {
      hasSyncedThisOpenRef.current = false;
      return;
    }
    if (!riveViewRef || !setRiveIsDark || hasSyncedThisOpenRef.current) return;
    hasSyncedThisOpenRef.current = true;
    setRiveIsDark(isDark);
    // Defer so RiveView has time to initialize; triggerInput forces correct state
    const id = setTimeout(() => {
      riveViewRef?.triggerInput(isDark ? 'dark' : 'light');
      riveViewRef?.playIfNeeded?.();
    }, 150);
    return () => clearTimeout(id);
  }, [visible, riveViewRef, isDark, setRiveIsDark]);

  // Animate modal appearance/disappearance
  useEffect(() => {
    if (visible) {
      // Animate in
      opacity.value = withTiming(1, {
        duration: 200,
        easing: Easing.out(Easing.ease),
      });
      scale.value = withTiming(1, {
        duration: 200,
        easing: Easing.out(Easing.ease),
      });
      translateY.value = withTiming(0, {
        duration: 200,
        easing: Easing.out(Easing.ease),
      });
    } else {
      // Animate out
      opacity.value = withTiming(0, { duration: 150 });
      scale.value = withTiming(0.9, { duration: 150 });
      translateY.value = withTiming(20, { duration: 150 });
    }
  }, [visible]);

  // Animated styles
  const backdropAnimatedStyle = useAnimatedStyle(() => ({
    opacity: opacity.value,
  }));

  const modalAnimatedStyle = useAnimatedStyle(() => {
    return {
      opacity: opacity.value,
      transform: [
        { scale: scale.value },
        { translateY: translateY.value },
      ] as const,
    };
  });

  // Handle button presses - fire Rive triggers and update theme (notes: triggerInput on ref)
  const handleLightPress = async () => {
    await Haptics.impactAsync(Haptics.ImpactFeedbackStyle.Light);
    riveViewRef?.triggerInput('light');
    await setTheme('light');
  };

  const handleDarkPress = async () => {
    await Haptics.impactAsync(Haptics.ImpactFeedbackStyle.Light);
    riveViewRef?.triggerInput('dark');
    await setTheme('dark');
  };

  // Handle close button press
  const handleClose = async () => {
    await Haptics.impactAsync(Haptics.ImpactFeedbackStyle.Light);
    onClose();
  };

  if (!visible) {
    return null;
  }

  return (
    <>
      {/* Scrim Background */}
      <Animated.View
        style={[
          StyleSheet.absoluteFill,
          { zIndex: 99 },
          backdropAnimatedStyle,
        ]}
      >
        <Pressable
          style={StyleSheet.absoluteFill}
          onPress={onClose}
        >
          {/* Semi-transparent overlay for better legibility */}
          <View
            style={[
              StyleSheet.absoluteFill,
              {
                backgroundColor: 'rgba(168, 168, 168, 0.8)',
              },
            ]}
          />
          <BlurView
            intensity={60}
            tint="dark"
            style={StyleSheet.absoluteFill}
          />
        </Pressable>
      </Animated.View>

      {/* Theme Switcher Modal */}
      <Animated.View
        style={[
          styles.modalContainer,
          { zIndex: 100, paddingBottom: 32 + insets.bottom },
          modalAnimatedStyle,
        ]}
        pointerEvents="box-none"
      >
        <View style={[styles.modalContent, { width: modalWidth }]}>
          {/* Close Button - Centered */}
          <View style={[styles.closeButtonWrapper, { top: 72 }]}>
            <TouchableOpacity
              onPress={handleClose}
              style={styles.closeButton}
              activeOpacity={0.7}
            >
              <CloseCircleIcon color={isDark ? colors.staticBlack : colors.staticWhite} size={48} />
            </TouchableOpacity>
          </View>

          {/* Rive Animation - icon, title, and box come from Rive file */}
          {riveLoading ? (
            <View style={[styles.rivePlaceholder, { height: modalWidth * 0.8 }]}>
              <Text
                style={{
                  color: colors.textPrimary,
                  fontSize: 12,
                }}
              >
                Loading...
              </Text>
            </View>
          ) : riveError ? (
            <View style={[styles.rivePlaceholder, { height: modalWidth * 0.8 }]}>
              <Text
                style={{
                  color: colors.errorText,
                  fontSize: 12,
                }}
              >
                Error: {typeof riveError === 'string' ? riveError : (riveError as Error).message || 'Failed to load'}
              </Text>
            </View>
          ) : !riveFile ? (
            <View style={[styles.rivePlaceholder, { height: modalWidth * 0.8 }]}>
              <Text
                style={{
                  color: colors.errorText,
                  fontSize: 12,
                }}
              >
                Rive file not loaded
              </Text>
            </View>
          ) : !hasSynced ? (
            <View style={[styles.rivePlaceholder, { height: modalWidth * 0.8 }]}>
              <Text
                style={{
                  color: colors.textPrimary,
                  fontSize: 12,
                }}
              >
                Syncing theme...
              </Text>
            </View>
          ) : (
            <View style={styles.riveContainer}>
              <RiveView
                hybridRef={setHybridRef}
                file={riveFile}
                artboardName="Final"
                stateMachineName="State Machine 1"
                dataBind={viewModelInstance ?? undefined}
                autoPlay={true}
                fit={Fit.Contain}
                style={[styles.riveAnimation, { height: modalWidth * 1 }]}
              />
            </View>
          )}

          {/* Theme Buttons */}
          <View style={styles.buttonContainer}>
            {/* Light Button */}
            <TouchableOpacity
              onPress={handleLightPress}
              style={[
                styles.themeButton,
                {
                  backgroundColor: colors.surfaceCanvas,
                },
              ]}
              activeOpacity={0.7}
            >
              {/* Highlight Overlay */}
              <View
                style={[
                  styles.buttonHighlight,
                  {
                    backgroundColor: colors.surfaceButtonSelected,
                    opacity: !isDark ? 1 : 0,
                  },
                ]}
              />
              {/* Icon */}
              {!isDark ? (
                <LightIconActive color={colors.iconActive} size={24} />
              ) : (
                <LightIconInactive color={colors.iconInactive} size={24} />
              )}
            </TouchableOpacity>

            {/* Dark Button */}
            <TouchableOpacity
              onPress={handleDarkPress}
              style={[
                styles.themeButton,
                {
                  backgroundColor: colors.surfaceCanvas,
                },
              ]}
              activeOpacity={0.7}
            >
              {/* Highlight Overlay */}
              <View
                style={[
                  styles.buttonHighlight,
                  {
                    backgroundColor: colors.surfaceButtonSelected,
                    opacity: isDark ? 1 : 0,
                  },
                ]}
              />
              {/* Icon */}
              {isDark ? (
                <DarkIconActive color={colors.iconActive} size={24} />
              ) : (
                <DarkIconInactive color={colors.iconInactive} size={24} />
              )}
            </TouchableOpacity>
          </View>
        </View>
      </Animated.View>
    </>
  );
}

const styles = StyleSheet.create({
  modalContainer: {
    position: 'absolute',
    top: 0,
    left: 0,
    right: 0,
    bottom: 0,
    justifyContent: 'flex-end',
    alignItems: 'center',
  },
  modalContent: {
    alignItems: 'flex-start',
    flexDirection: 'column',
    flex: 1,
    position: 'relative',
    width: '100%',
    paddingHorizontal: 20,
  },
  closeButtonWrapper: {
    position: 'absolute',
    left: 0,
    right: 0,
    alignItems: 'center',
    zIndex: 101,
  },
  closeButton: {
    width: 48,
    height: 48,
    justifyContent: 'center',
    alignItems: 'center',
    borderRadius: 20,
  },
  riveContainer: {
    width: '100%',
    flex: 1,
    flexDirection: 'column',
    alignItems: 'flex-end',
    justifyContent: 'flex-end',
    marginBottom: 0,
    minHeight: 200,
  },
  rivePlaceholder: {
    width: '100%',
    justifyContent: 'flex-start',
    alignItems: 'center',
    marginBottom: 0,
  },
  riveAnimation: {
    width: '100%',
  },
  buttonContainer: {
    flexDirection: 'row',
    gap: 16,
    width: '100%',
    alignItems: 'center',
    justifyContent: 'center',
  },
  themeButton: {
    paddingHorizontal: 24,
    paddingVertical: 12,
    borderRadius: 32,
    alignItems: 'center',
    justifyContent: 'center',
    position: 'relative',
  },
  buttonHighlight: {
    position: 'absolute',
    top: 4,
    left: 4,
    right: 4,
    bottom: 4,
    borderRadius: 28,
  },
});
