import React, { useEffect, useState, useMemo } from 'react';
import { 
  View, 
  Text, 
  StyleSheet, 
  ScrollView, 
  TouchableOpacity, 
  ActivityIndicator, 
  Dimensions, 
  Platform,
  StatusBar,
  Alert
} from 'react-native';
import { useLocalSearchParams, useRouter, Stack } from 'expo-router';
import { Image as ExpoImage } from 'expo-image';
import { Ionicons } from '@expo/vector-icons';
import { Colors } from '../../../constants/theme';
import api from '../../../services/api';
import { useAuthStore } from '../../../store/authStore';
import Animated, { 
  FadeInDown, 
  FadeInRight, 
  useAnimatedScrollHandler, 
  useAnimatedStyle, 
  useSharedValue, 
  interpolate,
  Extrapolate
} from 'react-native-reanimated';
import { LinearGradient } from 'expo-linear-gradient';
import GlassCard from '@/components/common/GlassCard';

const { width, height: SCREEN_HEIGHT } = Dimensions.get('window');
const HEADER_HEIGHT = SCREEN_HEIGHT * 0.45;

export default function ServiceDetailScreen() {
  const { slug } = useLocalSearchParams();
  const router = useRouter();
  const { isAuthenticated, user_type } = useAuthStore();
  
  const [service, setService] = useState<any>(null);
  const [loading, setLoading] = useState(true);
  const [errorStatus, setErrorStatus] = useState<string | null>(null);

  const scrollY = useSharedValue(0);

  const scrollHandler = useAnimatedScrollHandler({
    onScroll: (event) => {
      scrollY.value = event.contentOffset.y;
    },
  });

  useEffect(() => {
    const fetchDetail = async () => {
      setLoading(true);
      setErrorStatus(null);
      try {
        console.log('Fetching detail for slug:', slug);
        const response = await api.get(`/servicedetail/${slug}?is_mobile=yes`);
        if (response.data) {
          setService(response.data);
        } else {
          setErrorStatus('Resposta vazia da API');
        }
      } catch (error: any) {
        console.error('Error fetching service detail:', error.message);
        setErrorStatus(`Erro: ${error.message}${error.response ? ' (Status: ' + error.response.status + ')' : ''}`);
      } finally {
        setLoading(false);
      }
    };
    fetchDetail();
  }, [slug]);

  // Derived data with fallbacks (Extremely resilient)
  const serviceData = service?.data || service?.service || service;
  
  const title = serviceData?.source_name || serviceData?.name || 'Detalhe do Serviço';
  
  const formatPrice = (p: any) => {
    const num = parseFloat(String(p).replace(/[^0-9.-]+/g, ""));
    return !isNaN(num) 
      ? new Intl.NumberFormat('pt-BR', { maximumFractionDigits: 0 }).format(num) + ' Kz' 
      : p + ' Kz';
  };
  const price = formatPrice(serviceData?.price || serviceData?.source_price || '0');
  const description = serviceData?.source_description || serviceData?.description || 'Nenhuma descrição disponível.';
  
  // Handle image path
  const galleryImage = serviceData?.products_gallery?.source_Values || serviceData?.image;
  const baseUrl = `http://172.20.10.7/ecabral/public/storage/`;
  const mainImage = galleryImage 
    ? (galleryImage.startsWith('http') ? galleryImage : `${baseUrl}${galleryImage}`)
    : (serviceData?.image || service?.firstImage);

  const categoryName = serviceData?.category?.name || serviceData?.category_name || serviceData?.name || 'Serviço';
  const rating = serviceData?.rating || serviceData?.ratings?.avg_rating || '4.8';
  const ratingCount = serviceData?.rating_count || serviceData?.ratings?.total_count || '120';

  const handleBooking = () => {
    if (!isAuthenticated) {
      router.push('/login');
    } else if (user_type === 4) {
      Alert.alert(
        "Acesso Restrito",
        "Apenas clientes finais podem solicitar serviços. Para contratar, crie ou aceda com uma conta de Cliente."
      );
    } else {
      router.push({
        pathname: `/(auth)/booking/${serviceData?.id}` as any,
      });
    }
  };

  const headerImageStyle = useAnimatedStyle(() => {
    return {
      transform: [
        {
          translateY: interpolate(
            scrollY.value,
            [-HEADER_HEIGHT, 0, HEADER_HEIGHT],
            [-HEADER_HEIGHT / 2, 0, HEADER_HEIGHT * 0.75],
            Extrapolate.CLAMP
          ),
        },
        {
          scale: interpolate(
            scrollY.value,
            [-HEADER_HEIGHT, 0, HEADER_HEIGHT],
            [2, 1, 1],
            Extrapolate.CLAMP
          ),
        },
      ],
    };
  });

  if (loading) {
    return (
      <View style={[styles.loader, { backgroundColor: Colors.light.background }]}>
        <ActivityIndicator size="large" color={Colors.light.primary} />
      </View>
    );
  }

  return (
    <View style={styles.container}>
      <Stack.Screen options={{ headerShown: false }} />
      {/* Immersive Header Image */}
      <Animated.View style={[styles.header, headerImageStyle]}>
        <ExpoImage 
          source={{ uri: mainImage }} 
          style={styles.image} 
          contentFit="cover" 
        />
        <LinearGradient
          colors={['rgba(0,0,0,0.1)', 'transparent', 'rgba(0,0,0,0.6)']}
          style={StyleSheet.absoluteFill}
        />
      </Animated.View>

      <Animated.ScrollView
        onScroll={scrollHandler}
        scrollEventThrottle={16}
        showsVerticalScrollIndicator={false}
        contentContainerStyle={styles.scrollContent}
      >
        <View style={styles.spacer} />
        
        <View style={[styles.mainContent, { backgroundColor: Colors.light.background }]}>
          {/* Summary Card */}
          <Animated.View entering={FadeInDown.duration(600).delay(200)}>
            <GlassCard style={styles.summaryCard}>
              <View style={styles.categoryBadge}>
                <Text style={styles.categoryText}>{categoryName}</Text>
              </View>
              <Text style={styles.title}>{title}</Text>
              
              <View style={styles.ratingRow}>
                <View style={[styles.ratingBadge, { backgroundColor: Colors.light.warning + '20' }]}>
                  <Ionicons name="star" size={14} color={Colors.light.warning} />
                  <Text style={styles.ratingText}>
                    {rating} ({ratingCount} avaliações)
                  </Text>
                </View>
              </View>

              <View style={styles.priceRow}>
                <View>
                  <Text style={styles.priceLabel}>A partir de</Text>
                  <Text style={styles.priceValue}>{price}</Text>
                </View>
              </View>
            </GlassCard>
          </Animated.View>

          {/* Description */}
          <Animated.View entering={FadeInDown.duration(600).delay(400)} style={styles.section}>
            <Text style={styles.sectionTitle}>Sobre o Serviço</Text>
            <Text style={styles.description}>{description}</Text>
          </Animated.View>

          <View style={{ height: 180 }} />
        </View>
      </Animated.ScrollView>

      {/* Premium Footer - Elevated to avoid Bottom Nav */}
      <View style={[styles.footer, { backgroundColor: Colors.light.surface }]}>
        <TouchableOpacity 
          style={styles.bookButton} 
          onPress={handleBooking}
          activeOpacity={0.9}
        >
          <LinearGradient
            colors={Colors.light.gradients.primary as [string, string]}
            style={styles.gradientButton}
          >
            <Text style={styles.bookButtonText}>Solicitar Orçamento</Text>
            <Ionicons name="arrow-forward" size={20} color="#FFF" />
          </LinearGradient>
        </TouchableOpacity>
      </View>
    </View>
  );
}

const styles = StyleSheet.create({
  container: { flex: 1, backgroundColor: Colors.light.background },
  loader: { flex: 1, justifyContent: 'center', alignItems: 'center' },
  header: {
    position: 'absolute',
    top: 0,
    left: 0,
    right: 0,
    height: HEADER_HEIGHT,
    overflow: 'hidden',
  },
  image: { width: '100%', height: '100%' },
  scrollContent: { flexGrow: 1 },
  spacer: { height: HEADER_HEIGHT - 40 },
  mainContent: {
    borderTopLeftRadius: 32,
    borderTopRightRadius: 32,
    paddingHorizontal: 20,
    paddingTop: 30,
    marginTop: -20,
    minHeight: 500,
  },
  summaryCard: {
    padding: 24,
    borderRadius: 24,
    marginTop: -80,
    backgroundColor: '#FFF',
    borderWidth: 1,
    borderColor: '#F0F0F0',
    elevation: 0,
    shadowOpacity: 0,
  },
  categoryBadge: {
    paddingHorizontal: 12,
    paddingVertical: 4,
    borderRadius: 8,
    backgroundColor: Colors.light.primary + '15',
    alignSelf: 'flex-start',
    marginBottom: 12,
  },
  categoryText: { color: Colors.light.primary, fontSize: 12, fontWeight: '700', textTransform: 'uppercase' },
  title: { fontSize: 26, fontWeight: '800', color: Colors.light.text, letterSpacing: -0.5 },
  ratingRow: { flexDirection: 'row', alignItems: 'center', marginTop: 12, marginBottom: 20 },
  ratingBadge: { flexDirection: 'row', alignItems: 'center', paddingHorizontal: 8, paddingVertical: 4, borderRadius: 6 },
  ratingText: { fontSize: 13, fontWeight: '600', marginLeft: 4, color: Colors.light.warning },
  dot: { width: 4, height: 4, borderRadius: 2, backgroundColor: '#DDD', marginHorizontal: 10 },
  providerName: { fontSize: 14, color: Colors.light.textMuted, fontWeight: '500' },
  priceRow: { 
    flexDirection: 'row', 
    justifyContent: 'space-between', 
    alignItems: 'center', 
    paddingTop: 20,
    borderTopWidth: 1,
    borderTopColor: 'rgba(0,0,0,0.05)',
  },
  priceLabel: { fontSize: 13, color: Colors.light.textMuted, marginBottom: 2 },
  priceValue: { fontSize: 24, fontWeight: '900', color: Colors.light.primary },
  tagBadge: { flexDirection: 'row', alignItems: 'center', backgroundColor: Colors.light.primary + '10', paddingHorizontal: 10, paddingVertical: 6, borderRadius: 20 },
  tagText: { fontSize: 11, fontWeight: '700', color: Colors.light.primary, marginLeft: 4 },
  section: { marginTop: 32 },
  sectionTitle: { fontSize: 18, fontWeight: '800', color: Colors.light.text, marginBottom: 12 },
  sectionSubtitle: { fontSize: 14, color: Colors.light.textMuted, marginBottom: 16 },
  description: { fontSize: 16, color: '#555', lineHeight: 26, fontWeight: '400' },
  addonCard: {
    flexDirection: 'row',
    alignItems: 'center',
    padding: 16,
    borderRadius: 16,
    backgroundColor: '#FFF',
    borderWidth: 1.5,
    borderColor: '#F0F0F0',
    marginBottom: 12,
  },
  addonInfo: { flex: 1 },
  addonName: { fontSize: 15, fontWeight: '700', color: Colors.light.text, marginBottom: 4 },
  addonPrice: { fontSize: 14, fontWeight: '600', color: Colors.light.primary },
  checkbox: { 
    width: 24, 
    height: 24, 
    borderRadius: 12, 
    borderWidth: 2, 
    borderColor: '#DDD',
    justifyContent: 'center',
    alignItems: 'center',
  },
  footer: {
    position: 'absolute',
    bottom: 60, // Sits exactly on top of bottom nav
    left: 0,
    right: 0,
    padding: 24,
    paddingBottom: 75, // Reduced height by 30%
    flexDirection: 'row',
    alignItems: 'center',
    borderTopWidth: 1,
    borderTopColor: 'rgba(0,0,0,0.05)',
    backgroundColor: '#FFF',
    shadowOpacity: 0,
    elevation: 0,
  },
  bookButton: { flex: 1 },
  gradientButton: {
    height: 56,
    borderRadius: 18,
    flexDirection: 'row',
    justifyContent: 'center',
    alignItems: 'center',
    gap: 8,
  },
  bookButtonText: { color: '#FFF', fontSize: 16, fontWeight: '800' }
});
