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

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

export default function StaffBookingDetailScreen() {
  const { id } = useLocalSearchParams<{ id: string }>();
  const navigation = useNavigation();
  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 fetchDetail = async (isRefresh = false) => {
    if (!isRefresh) setLoading(true);
    try {
      const res = await api.post('/user/bookingdetails', { id });
      setBookingData(res.data);
    } catch (err) {
      console.error('[StaffBookingDetail] error:', err);
    } finally {
      setLoading(false);
      setRefreshing(false);
    }
  };

  useFocusEffect(useCallback(() => {
    navigation.getParent()?.setOptions?.({ headerTitle: 'Detalhes do Serviço' });
    fetchDetail();
  }, [id]));

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

  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 changeStatus = (type: number, label: string) => {
    let message = `Deseja ${label.toLowerCase()} deste serviço?`;
    if (type === 5) message = 'Confirma a conclusão do trabalho?';
    if (type === 2) message = 'Deseja aceitar este serviço?';
    if (type === 3) message = 'Deseja cancelar este serviço?';

    Alert.alert(label, message, [
      { text: 'Não', style: 'cancel' },
      {
        text: 'Sim, Confirmar',
        onPress: async () => {
          try {
            setActionLoading(true);
            await api.post('/updatebookingstatus', { id: id, status: type });
            fetchDetail(true);
          } catch (err: any) {
            console.error('[StaffBookingDetail] Error updating status:', err.response?.data || err.message);
            Alert.alert('Erro', 'Não foi possível actualizar o estado do serviço.');
          } finally {
            setActionLoading(false);
          }
        }
      }
    ]);
  };

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

  if (!bookingData) {
    return (
      <View style={[styles.loader, { backgroundColor: theme.background }]}>
        <Ionicons name="alert-circle-outline" size={48} color={theme.border} />
        <Text style={[styles.emptyText, { color: theme.textMuted }]}>Serviço não encontrado.</Text>
      </View>
    );
  }

  const { booking, service, status } = bookingData;
  const imageUrl = service?.image_url || 'https://images.unsplash.com/photo-1621905251189-08b45d6a269e?q=80&w=2069&auto=format&fit=crop';
  
  const statusCode = Number(booking.booking_status);
  const isCompleted = statusCode === 5 || statusCode === 6;

  return (
    <View style={{ flex: 1, backgroundColor: theme.primary + '08' }}>
      <StatusBar barStyle="light-content" translucent backgroundColor="transparent" />

      {/* App Bar Overlay - Chat Button */}
      <View style={styles.appBarOverlay}>
        <TouchableOpacity 
          onPress={() => router.push(`/(drawer)/chat/${booking.user_id}` 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 - Exact Parity */}
        <Animated.View style={[styles.heroContainer, headerStyle]}>
          <RNImage source={{ uri: imageUrl }} style={styles.heroImage} resizeMode="cover" />
          <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 ?? booking.source_name}</Text>
                <View style={styles.heroMetaRow}>
                  <View style={[styles.statusTag, { backgroundColor: theme.primary }]}>
                    <Text style={styles.statusTagText}>{status?.booking_status ?? 'Pendente'}</Text>
                  </View>
                </View>
              </View>
              <View style={styles.heroIdCol}>
                <Text style={styles.heroIdLabel}>ID SERVIÇO</Text>
                <Text style={styles.heroIdValue}>#{booking.order_id ?? booking.id}</Text>
              </View>
            </View>
          </View>
        </Animated.View>

        <View style={styles.body}>
          <Animated.View entering={FadeInDown.duration(600)} style={styles.tonalSummaryWrapper}>
            <View style={[styles.md3Card, { backgroundColor: theme.background, borderColor: theme.primary + '20' }]}>
              <Text style={[styles.summaryLabel, { color: theme.primary }]}>VALOR</Text>
              <Text style={[styles.summaryValue, { color: theme.text }]}>
                {booking.total_amount ?? '—'}
              </Text>
            </View>
            <View style={[styles.md3Card, { backgroundColor: theme.background, borderColor: theme.primary + '20' }]}>
              <Text style={[styles.summaryLabel, { color: theme.primary }]}>DATA PREVISTA</Text>
              <Text style={[styles.summaryValue, { color: theme.text }]}>
                {bookingData.formatted_booking_date ?? booking.booking_date ?? '—'}
              </Text>
            </View>
          </Animated.View>

          <View style={styles.contentSections}>
            {/* Customer Profile Section (MD3 Tonal) */}
            <Animated.View entering={FadeInDown.duration(600).delay(200)} style={[styles.contactCard, { backgroundColor: theme.background, borderColor: theme.primary + '15' }]}>
               <View style={styles.contactHeader}>
                  <View style={[styles.contactAvatar, { backgroundColor: theme.primary + '10' }]}>
                     <Ionicons name="person" size={24} color={theme.primary} />
                  </View>
                  <View>
                     <Text style={[styles.contactName, { color: theme.text }]}>
                        {booking.user_name || [booking.first_name, booking.last_name].filter(Boolean).join(' ') || 'Cliente'}
                     </Text>
                     <Text style={[styles.contactRole, { color: '#666' }]}>Cliente Comprador</Text>
                  </View>
               </View>

               <View style={styles.contactGrid}>
                  <View style={styles.contactItem}>
                     <Text style={[styles.contactLabel, { color: '#555' }]}>EMAIL</Text>
                     <Text style={[styles.contactValue, { color: theme.text }]} numberOfLines={1}>{booking.user_email}</Text>
                  </View>
                  <View style={styles.contactItem}>
                     <Text style={[styles.contactLabel, { color: '#555' }]}>TELEFONE</Text>
                     <Text style={[styles.contactValue, { color: theme.text }]}>{booking.user_phone ?? booking.contact ?? '—'}</Text>
                  </View>
               </View>

               <View style={styles.addressBox}>
                  <Ionicons name="location-sharp" size={18} color={theme.primary} style={{ marginRight: 8, marginTop: 2 }} />
                  <View style={{ flex: 1 }}>
                     <Text style={[styles.contactLabel, { color: '#555' }]}>ENDEREÇO DO SERVIÇO</Text>
                     <Text style={[styles.addressText, { color: theme.text }]}>{booking.user_address ?? 'Não informado'}</Text>
                  </View>
               </View>
            </Animated.View>

            {/* Note Area */}
            {booking.notes && (
              <View style={styles.notesContainer}>
                <Text style={[styles.notesLabel, { color: '#555' }]}>NOTAS DO SERVIÇO</Text>
                <View style={[styles.notesBubble, { backgroundColor: theme.background, borderColor: theme.primary + '20' }]}>
                  <Text style={[styles.notesText, { color: theme.text }]}>{booking.notes}</Text>
                </View>
              </View>
            )}
          </View>

          {/* Action Footer */}
          <View style={styles.actionFooter}>
            {Number(booking.booking_status) === 1 && (
              <View style={styles.actionRow}>
                <TouchableOpacity 
                  style={[styles.pillBtn, { backgroundColor: '#48c774' }]} 
                  onPress={() => changeStatus(2, 'Aceitar Serviço')}
                  disabled={actionLoading}
                >
                  <Text style={styles.pillBtnText}>Confirmar Agora</Text>
                </TouchableOpacity>
                <TouchableOpacity 
                   style={styles.ghostBtn}
                   onPress={() => changeStatus(3, 'Cancelar Serviço')}
                >
                  <Text style={[styles.ghostBtnText, { color: '#ff6b6b' }]}>Rejeitar</Text>
                </TouchableOpacity>
              </View>
            )}

            {Number(booking.booking_status) === 2 && (
              <TouchableOpacity 
                style={[styles.pillBtn, { backgroundColor: theme.primary }]} 
                onPress={() => changeStatus(5, 'Concluir Serviço')}
                disabled={actionLoading}
              >
                <Ionicons name="checkmark-circle-outline" size={24} color="#FFF" style={{marginRight: 10}} />
                <Text style={styles.pillBtnText}>Marcar como Concluído</Text>
              </TouchableOpacity>
            )}
          </View>
        </View>
      </Animated.ScrollView>
    </View>
  );
}

const styles = StyleSheet.create({
  loader: { flex: 1, justifyContent: 'center', alignItems: 'center' },
  emptyText: { fontSize: 15 },
  scrollContent: { paddingBottom: 120 }, // Increased padding for bottom tabs
  appBarOverlay: { position: 'absolute', top: 40, right: 20, zIndex: 200 },
  headerChatBtn: {
    width: 44, height: 44, borderRadius: 22, justifyContent: 'center', alignItems: 'center',
    // No shadows - MD3 Flat
  },
  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: 9, fontWeight: '700', letterSpacing: 1 },
  heroIdValue: { color: '#FFF', fontSize: 16, fontWeight: '700' },
  serviceNameHero: { color: '#FFF', fontSize: 24, fontWeight: '800', 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: { marginTop: 0 },
  
  // MD3 Tonal Summary
  tonalSummaryWrapper: { 
    flexDirection: 'row', paddingVertical: 20, paddingHorizontal: 25, gap: 12, alignItems: 'center', justifyContent: 'center' 
  },
  md3Card: { 
    flex: 1, paddingVertical: 18, borderRadius: 24, alignItems: 'center', borderWidth: 0.5,
  },
  summaryLabel: { fontSize: 10, fontWeight: '800', letterSpacing: 1.5, marginBottom: 6, textTransform: 'uppercase' },
  summaryValue: { fontSize: 17, fontWeight: '700', letterSpacing: -0.5 },
  contentSections: { padding: 25, paddingTop: 10 },
  
  // Premium Contact Card (MD3 Flat)
  contactCard: {
    padding: 24, borderRadius: 28, borderWidth: 0.5,
    // No shadows - MD3 Flat
  },
  contactHeader: { flexDirection: 'row', alignItems: 'center', gap: 14, marginBottom: 20 },
  contactAvatar: { width: 56, height: 56, borderRadius: 28, justifyContent: 'center', alignItems: 'center' },
  contactName: { fontSize: 18, fontWeight: '800', letterSpacing: -0.5 },
  contactRole: { fontSize: 11, fontWeight: '600', textTransform: 'uppercase', letterSpacing: 0.5 },
  contactGrid: { flexDirection: 'row', gap: 20, marginBottom: 20, borderBottomWidth: 1, borderBottomColor: 'rgba(0,0,0,0.05)', paddingBottom: 15 },
  contactItem: { flex: 1 },
  contactLabel: { fontSize: 10, fontWeight: '800', letterSpacing: 1, marginBottom: 6 },
  contactValue: { fontSize: 14, fontWeight: '600' },
  addressBox: { flexDirection: 'row', alignItems: 'flex-start' },
  addressText: { fontSize: 14, fontWeight: '500', lineHeight: 22 },

  // Notes
  notesContainer: { marginTop: 24 },
  notesLabel: { fontSize: 10, fontWeight: '800', letterSpacing: 1.2, marginBottom: 10 },
  notesBubble: { padding: 18, borderRadius: 24, borderWidth: 0.5 },
  notesText: { fontSize: 14, fontStyle: 'italic', lineHeight: 24 },

  // Action Footer
  actionFooter: { marginTop: 10, paddingBottom: 20, paddingHorizontal: 25 },
  actionRow: { gap: 12 },
  pillBtn: { height: 60, borderRadius: 30, flexDirection: 'row', alignItems: 'center', justifyContent: 'center' },
  pillBtnText: { color: '#FFF', fontSize: 16, fontWeight: '800' },
  ghostBtn: { height: 44, alignItems: 'center', justifyContent: 'center' },
  ghostBtnText: { fontSize: 14, fontWeight: '800' },
  heroMetaRow: { flexDirection: 'row', alignItems: 'center', marginTop: 6 },
});
