import React, { useEffect, useState } from 'react';
import { View, Text, StyleSheet, ScrollView, ActivityIndicator, Alert, TouchableOpacity, Dimensions, StatusBar, Image, Platform, RefreshControl } from 'react-native';
import { useLocalSearchParams, useRouter, useFocusEffect } from 'expo-router';
import { Colors } from '@/constants/theme';
import api from '@/services/api';
import { useColorScheme } from 'react-native';
import Animated, { FadeInDown, useAnimatedScrollHandler, useSharedValue, useAnimatedStyle, interpolate, Extrapolate } from 'react-native-reanimated';
import { Ionicons } from '@expo/vector-icons';
import { LinearGradient } from 'expo-linear-gradient';

const { width } = Dimensions.get('window');
const HEADER_HEIGHT = 180;

export default function BookingDetailsScreen() {
  const { id } = useLocalSearchParams();
  const router = useRouter();
  const colorScheme = useColorScheme() ?? 'light';
  const theme = Colors[colorScheme as 'light' | 'dark'];

  const [bookingData, setBookingData] = useState<any>(null);
  const [loading, setLoading] = useState(true);
  const [refreshing, setRefreshing] = useState(false);
  const [actionLoading, setActionLoading] = useState(false);

  const scrollY = useSharedValue(0);

  const fetchDetails = async (isRefresh = false) => {
    if (!isRefresh) setLoading(true);
    try {
      const response = await api.post('/user/bookingdetails', { id });
      setBookingData(response.data);
    } catch (error) {
      console.error('Error fetching booking details:', error);
    } finally {
      setLoading(false);
      setRefreshing(false);
    }
  };

  const onRefresh = () => {
    setRefreshing(true);
    fetchDetails(true);
  };

  useFocusEffect(
    React.useCallback(() => {
      if (id) fetchDetails(true);
    }, [id])
  );

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

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

  const appBarTitleStyle = useAnimatedStyle(() => {
    const opacity = interpolate(scrollY.value, [HEADER_HEIGHT - 100, HEADER_HEIGHT - 60], [0, 1], Extrapolate.CLAMP);
    return { opacity };
  });

  const handleAcceptQuote = async () => {
    setActionLoading(true);
    try {
      await api.post('/acceptquote', { id });
      Alert.alert('Sucesso', 'Orçamento aceite com sucesso.');
      fetchDetails();
    } catch (error) {
      Alert.alert('Erro', 'Não foi possível aceitar o orçamento.');
    } finally {
      setActionLoading(false);
    }
  };

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

  const { booking, status, provider, provider_details, service } = bookingData;
  const statusCode = parseInt(status?.booking_status_code ?? booking.booking_status);
  const isAlreadyPaid = (parseInt(status?.payment_status_code ?? booking.payment_status ?? 0)) === 2 || statusCode === 6;
  const isPendingConfirmation = statusCode === 13;

  return (
    <View style={[styles.container, { backgroundColor: theme.background }]}>
      <StatusBar barStyle="light-content" translucent backgroundColor="transparent" />
      
      {/* App Bar Overlay */}
      <View style={styles.appBarOverlay}>
        <View style={{ flex: 1 }} />
        
        {/* Elite Chat Header Button */}
        {provider && (
          <TouchableOpacity 
            onPress={() => router.push({ 
              pathname: '/(drawer)/chat/[id]', 
              params: { 
                id: provider.id, 
                name: provider_details?.first_name || provider.name, 
                avatar: 'https://ui-avatars.com/api/?name=' + (provider_details?.first_name || provider.name) + '&background=random' 
              } 
            } as any)}
            style={[styles.headerChatBtn, { backgroundColor: theme.primary }]}
          >
            <Ionicons name="chatbubble-ellipses" size={18} color="#FFF" />
          </TouchableOpacity>
        )}
      </View>

      <Animated.ScrollView 
        onScroll={onScroll} 
        scrollEventThrottle={16} 
        contentContainerStyle={styles.scrollContent} 
        showsVerticalScrollIndicator={false}
        refreshControl={
          <RefreshControl refreshing={refreshing} onRefresh={onRefresh} tintColor={theme.primary} />
        }
      >
        
        {/* Visual Hero - 180px */}
        <Animated.View style={[styles.heroContainer, headerStyle]}>
          <Image 
            source={{ uri: service?.image_url || 'https://images.unsplash.com/photo-1621905251189-08b45d6a269e?q=80&w=2069&auto=format&fit=crop' }} 
            style={styles.heroImage} 
          />
          <LinearGradient
            colors={['rgba(0,0,0,0.1)', 'rgba(0,0,0,0.7)']}
            style={styles.heroGradient}
          />
          <View style={styles.heroContent}>
             <View style={styles.heroRow}>
                <View style={{ flex: 1 }}>
                   <Text style={styles.serviceNameHero} numberOfLines={1}>{service?.source_name}</Text>
                   
                   <View style={styles.heroMetaRow}>
                      <View style={[styles.statusTag, { backgroundColor: isAlreadyPaid ? '#4caf50' : theme.primary }]}>
                         <Text style={styles.statusTagText}>{status?.booking_status}</Text>
                      </View>
                      {provider && (
                         <>
                            <View style={styles.heroSeparator} />
                            <Text style={styles.heroTechnicianText}>
                               {provider_details?.first_name || provider.name}
                            </Text>
                         </>
                      )}
                   </View>
                </View>
                <View style={styles.heroIdCol}>
                   <Text style={styles.heroIdLabel}>ID SERVIÇO</Text>
                   <Text style={styles.heroIdValue}>#{booking.id}</Text>
                </View>
             </View>
          </View>
        </Animated.View>

        <View style={styles.body}>
          
          {/* Tonal Summary Section (Centered & Equalized) */}
          <Animated.View entering={FadeInDown.duration(600)} style={[styles.tonalSummary, { backgroundColor: theme.primary + '08' }]}>
             <View style={styles.summaryBox}>
                <Text style={[styles.summaryLabel, { color: theme.primary }]}>VALOR</Text>
                <Text style={[styles.summaryValue, { color: theme.text }]}>
                   {booking.total_amount}
                </Text>
             </View>
             <View style={styles.vDivider} />
             <View style={styles.summaryBox}>
                <Text style={[styles.summaryLabel, { color: theme.primary }]}>DATA PREVISTA</Text>
                <Text style={[styles.summaryValue, { color: theme.text }]}>
                   {bookingData.formatted_booking_date}
                </Text>
             </View>
          </Animated.View>

          <View style={styles.contentSections}>
             {booking.notes && (
               <View style={styles.descriptionArea}>
                  <Text style={[styles.labelSmall, { color: theme.textMuted, marginBottom: 8 }]}>OBSERVAÇÕES DO CLIENTE</Text>
                  <Text style={[styles.bodyText, { color: theme.text }]}>{booking.notes}</Text>
               </View>
             )}

             {bookingData.images && bookingData.images.length > 0 && (
                <View style={{ marginTop: booking.notes ? 25 : 5 }}>
                   <Text style={[styles.labelSmall, { color: theme.textMuted, marginBottom: 12 }]}>IMAGENS SUBMETIDAS</Text>
                   <ScrollView horizontal showsHorizontalScrollIndicator={false} contentContainerStyle={{ gap: 12 }}>
                      {bookingData.images.map((img: any, index: number) => (
                         <Image 
                           key={index}
                           source={{ uri: img.full_url }} 
                           style={{ width: 140, height: 140, borderRadius: 12, backgroundColor: theme.primary + '10' }} 
                         />
                      ))}
                   </ScrollView>
                </View>
             )}
          </View>

           {/* Integrated Actions - Radical Minimalism (No Cards) */}
           <View style={{ marginTop: 10, paddingBottom: 40 }}>
              {statusCode === 10 && (
                <View style={[styles.actionRow, { paddingHorizontal: 25 }]}>
                  <TouchableOpacity 
                    style={[styles.pillBtn, { backgroundColor: theme.primary }]} 
                    onPress={handleAcceptQuote}
                    disabled={actionLoading}
                  >
                    {actionLoading ? <ActivityIndicator color="#FFF" /> : <Text style={styles.pillBtnText}>Aceitar Orçamento</Text>}
                  </TouchableOpacity>
                  <TouchableOpacity style={styles.ghostBtn}>
                     <Text style={[styles.ghostBtnText, { color: theme.textMuted }]}>Outras Propostas</Text>
                  </TouchableOpacity>
                </View>
              )}

              {statusCode === 5 && !isAlreadyPaid && !isPendingConfirmation && (
                <View style={{ paddingHorizontal: 25 }}>
                   <TouchableOpacity 
                     style={[styles.pillBtn, { backgroundColor: theme.primary }]} 
                     onPress={() => router.push({
                       pathname: `/(drawer)/(tabs)/booking/payment/${id}` as any,
                       params: { amount: booking.total_amount, currency: bookingData.currency }
                     })}
                   >
                     <Ionicons name="card-outline" size={20} color="#FFF" style={{marginRight: 10}} />
                     <Text style={styles.pillBtnText}>Pagar Agora</Text>
                   </TouchableOpacity>
                </View>
              )}

              {(isPendingConfirmation || isAlreadyPaid) && (
                <View style={[styles.bannerRow, { paddingHorizontal: 25, marginTop: 10 }]}>
                  <View style={[styles.bannerIconBox, { backgroundColor: isAlreadyPaid ? '#E8F5E9' : theme.primary + '10' }]}>
                     <Ionicons name={isAlreadyPaid ? "checkmark-done" : "time-outline"} size={20} color={isAlreadyPaid ? "#2E7D32" : theme.primary} />
                  </View>
                  <View>
                     <Text style={[styles.bannerTitle, { color: theme.text }]}>
                        {isAlreadyPaid ? "Pagamento Confirmado" : "Aguardando Validação"}
                     </Text>
                     <Text style={[styles.bannerSub, { color: theme.textMuted }]}>
                        {isAlreadyPaid ? "O seu serviço está pronto para avançar." : "Estamos a verificar o seu comprovativo."}
                     </Text>
                  </View>
                </View>
              )}
           </View>
        </View>
      </Animated.ScrollView>
    </View>
  );
}

const styles = StyleSheet.create({
  container: { flex: 1 },
  loaderContainer: { flex: 1, justifyContent: 'center', alignItems: 'center' },
  scrollContent: { paddingBottom: 60 },

  // App Bar
  appBarOverlay: {
    position: 'absolute',
    top: 10,
    left: 0,
    right: 0,
    height: 120,
    zIndex: 200,
    flexDirection: 'row',
    alignItems: 'center',
    paddingTop: 10,
    paddingHorizontal: 20,
    justifyContent: 'flex-end',
  },
  headerChatBtn: {
    width: 44,
    height: 44,
    borderRadius: 22,
    justifyContent: 'center',
    alignItems: 'center',
    shadowColor: '#000',
    shadowOffset: { width: 0, height: 4 },
    shadowOpacity: 0.2,
    shadowRadius: 6,
    elevation: 6,
  },
  iconCircle: {
    width: 36,
    height: 36,
    borderRadius: 18,
    backgroundColor: 'rgba(0,0,0,0.3)',
    justifyContent: 'center',
    alignItems: 'center',
    display: 'none', // Removed back button
  },
  appBarTitle: {
    display: 'none', // Removed second title
  },

  // Hero - Minimalist
  heroContainer: {
    height: HEADER_HEIGHT,
    width: '100%',
    overflow: 'hidden',
  },
  heroImage: {
    ...StyleSheet.absoluteFillObject,
  },
  heroGradient: {
    ...StyleSheet.absoluteFillObject,
  },
  heroContent: {
    position: 'absolute',
    bottom: 25,
    left: 25,
    right: 25,
  },
  heroRow: {
    flexDirection: 'row',
    alignItems: 'flex-end',
    justifyContent: 'space-between',
  },
  heroIdCol: {
    alignItems: 'flex-end',
  },
  heroIdLabel: {
    color: '#FFF',
    fontSize: 8,
    fontWeight: '900',
    opacity: 0.6,
    letterSpacing: 1,
  },
  heroIdValue: {
    color: '#FFF',
    fontSize: 16,
    fontWeight: '800',
  },
  serviceNameHero: {
    color: '#FFF',
    fontSize: 24,
    fontWeight: '900',
    marginBottom: 4,
    letterSpacing: -0.5,
  },
  statusTag: {
    paddingHorizontal: 10,
    paddingVertical: 3,
    borderRadius: 4,
    alignSelf: 'flex-start',
  },
  statusTagText: {
    color: '#FFF',
    fontSize: 9,
    fontWeight: '900',
    textTransform: 'uppercase',
  },

  // Body
  body: {
    marginTop: 0,
  },
  tonalSummary: {
    flexDirection: 'row',
    paddingVertical: 30,
    paddingHorizontal: 25,
    alignItems: 'center',
    justifyContent: 'center',
  },
  summaryBox: {
    flex: 1,
    alignItems: 'center',
  },
  vDivider: {
    width: 1,
    height: 30,
    backgroundColor: 'rgba(0,0,0,0.06)',
    marginHorizontal: 10,
  },
  summaryLabel: {
    fontSize: 9,
    fontWeight: '900',
    letterSpacing: 2,
    marginBottom: 8,
    textTransform: 'uppercase',
  },
  summaryValue: {
    fontSize: 18, // Reduced and equalized
    fontWeight: '900',
    letterSpacing: -0.5,
  },
  summaryCurrency: {
    fontSize: 12,
    opacity: 0.5,
  },

  // Content
  contentSections: {
    padding: 25,
    paddingTop: 10,
  },
  sectionRow: {
    flexDirection: 'row',
    alignItems: 'center',
    marginBottom: 35,
  },
  sectionIconBox: {
    width: 40,
    height: 40,
    borderRadius: 12,
    justifyContent: 'center',
    alignItems: 'center',
    marginRight: 16,
  },
  sectionText: {
    flex: 1,
  },
  labelSmall: {
    fontSize: 10,
    fontWeight: '900',
    letterSpacing: 1,
    marginBottom: 4,
    textTransform: 'uppercase',
  },
  valueMedium: {
    fontSize: 16,
    fontWeight: '700',
  },
  descriptionArea: {
    marginTop: 5,
  },
  bodyText: {
    fontSize: 15,
    lineHeight: 24,
    fontWeight: '500',
  },

  heroMetaRow: {
    flexDirection: 'row',
    alignItems: 'center',
    marginTop: 6,
  },
  heroSeparator: {
    width: 3,
    height: 3,
    borderRadius: 2,
    backgroundColor: 'rgba(255,255,255,0.4)',
    marginHorizontal: 10,
  },
  heroTechnicianText: {
    color: '#FFF',
    fontSize: 11,
    fontWeight: '700',
    letterSpacing: 0.5,
    opacity: 0.8,
  },

  actionRow: {
    gap: 12,
  },
  pillBtn: {
    height: 56,
    borderRadius: 28,
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'center',
  },
  pillBtnText: {
    color: '#FFF',
    fontSize: 16,
    fontWeight: '900',
  },
  ghostBtn: {
    height: 44,
    alignItems: 'center',
    justifyContent: 'center',
  },
  ghostBtnText: {
    fontSize: 14,
    fontWeight: '800',
  },
  bannerRow: {
    flexDirection: 'row',
    alignItems: 'center',
    gap: 16,
  },
  bannerIconBox: {
    width: 44,
    height: 44,
    borderRadius: 22,
    justifyContent: 'center',
    alignItems: 'center',
  },
  bannerTitle: {
    fontSize: 15,
    fontWeight: '900',
  },
  bannerSub: {
    fontSize: 12,
    fontWeight: '500',
    marginTop: 2,
  }
});
