import React, { useState } from 'react';
import { StyleSheet, TouchableOpacity, Animated, Easing } from 'react-native';
import { useRouter } from 'expo-router';
import Svg, { Path } from 'react-native-svg';
import { useSettings } from '@/theme';

export function FloatingActionButton() {
  const router = useRouter();
  const { theme } = useSettings();
  const [scaleAnim] = React.useState(new Animated.Value(1));
  const [rotateAnim] = React.useState(new Animated.Value(0));
  const [rotation, setRotation] = useState(0);

  const handlePressIn = () => {
    Animated.timing(scaleAnim, {
      toValue: 0.9,
      duration: 100,
      useNativeDriver: true,
    }).start();
  };

  const handlePressOut = () => {
    Animated.spring(scaleAnim, {
      toValue: 1,
      friction: 5,
      tension: 200,
      useNativeDriver: true,
    }).start();
  };

  const handlePress = () => {
    const nextRotation = rotation + 90;
    setRotation(nextRotation);
    Animated.timing(rotateAnim, {
      toValue: nextRotation / 90,
      duration: 200,
      easing: Easing.out(Easing.cubic),
      useNativeDriver: true,
    }).start(() => {
      router.push('/add-task');
    });
  };

  const rotate = rotateAnim.interpolate({
    inputRange: [0, 1],
    outputRange: ['0deg', '90deg'],
  });

  return (
    <Animated.View
      style={[
        styles.container,
        { transform: [{ scale: scaleAnim }] },
      ]}
    >
      <TouchableOpacity
        style={[styles.button, { backgroundColor: theme.accent, shadowColor: theme.accent }]}
        onPress={handlePress}
        onPressIn={handlePressIn}
        onPressOut={handlePressOut}
        activeOpacity={1}
        accessibilityRole="button"
        accessibilityLabel="Add new task"
        hitSlop={12}
      >
        <Animated.View
          style={{
            transform: [{ rotate }],
          }}
        >
          <Svg width={24} height={24} viewBox="0 0 24 24">
            <Path
              d="M12 5v14M5 12h14"
              stroke={theme.accentText}
              strokeWidth={2.5}
              strokeLinecap="round"
              strokeLinejoin="round"
            />
          </Svg>
        </Animated.View>
      </TouchableOpacity>
    </Animated.View>
  );
}

const styles = StyleSheet.create({
  container: {
    position: 'absolute',
    bottom: 24,
    right: 24,
    shadowOffset: { width: 0, height: 4 },
    shadowOpacity: 0.3,
    shadowRadius: 12,
    elevation: 6,
  },
  button: {
    width: 56,
    height: 56,
    borderRadius: 16,
    alignItems: 'center',
    justifyContent: 'center',
  },
});