import React, { useEffect, useState } from 'react';
import { 
  View, 
  Text, 
  StyleSheet, 
  ScrollView, 
  ActivityIndicator, 
  useColorScheme, 
  TextInput,
  KeyboardAvoidingView,
  Platform,
  TouchableOpacity
} from 'react-native';
import { useLocalSearchParams, useRouter, Stack } from 'expo-router';
import { Colors } from '@/constants/theme';
import api from '@/services/api';
import { Ionicons } from '@expo/vector-icons';
import Animated, { FadeInDown, FadeIn } from 'react-native-reanimated';
import GlassCard from '@/components/common/GlassCard';
import AnimatedButton from '@/components/common/AnimatedButton';
import { useAuthStore } from '@/store/authStore';

const StatusBadge = ({ status, theme }: { status: string; theme: any }) => {
  const getStatusInfo = (s: string) => {
    switch (s) {
      case '1': return { label: 'Aberto', color: theme.primary };
      case '2': return { label: 'Atribuído', color: '#FF9500' };
      case '3': return { label: 'Em Progresso', color: '#5856D6' };
      case '4': return { label: 'Fechado', color: theme.success };
      default: return { label: s || 'Aberto', color: theme.primary };
    }
  };
  const info = getStatusInfo(status);
  return (
    <View style={[styles.badge, { backgroundColor: `${info.color}15` }]}>
      <Text style={[styles.badgeText, { color: info.color }]}>{info.label}</Text>
    </View>
  );
};

const PriorityBadge = ({ priority, theme }: { priority: string; theme: any }) => {
  const getPriorityInfo = (p: string) => {
    switch (p) {
      case '1': return { label: 'Baixa', color: theme.success };
      case '2': return { label: 'Média', color: '#FF9500' };
      case '3': return { label: 'Alta', color: theme.error };
      default: return { label: p || 'Média', color: '#FF9500' };
    }
  };
  const info = getPriorityInfo(priority);
  return (
    <View style={[styles.badge, { backgroundColor: `${info.color}10` }]}>
      <Text style={[styles.badgeText, { color: info.color, fontSize: 10 }]}>{info.label}</Text>
    </View>
  );
};

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

  const [ticket, setTicket] = useState<any>(data ? JSON.parse(data as string) : null);
  const [history, setHistory] = useState<any[]>([]);
  const [loading, setLoading] = useState(!data);
  const [comment, setComment] = useState('');
  const [sending, setSending] = useState(false);

  const fetchHistory = async () => {
    try {
      const response = await api.post('ticket/history', { ticketId: id });
      setHistory(response.data.data.tickethistory || []);
    } catch (error) {
      console.error('Error fetching ticket history:', error);
    }
  };

  useEffect(() => {
    if (id) fetchHistory();
  }, [id]);

  const handleSendComment = async () => {
    if (!comment.trim() || sending) return;
    setSending(true);
    try {
      await api.post('ticket/storehistory', {
        ticket_id: id,
        description: comment.trim(),
        user_id: user_id
      });
      setComment('');
      fetchHistory(); // Refresh history
    } catch (error) {
      console.error('Error sending comment:', error);
    } finally {
      setSending(false);
    }
  };

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

  return (
    <KeyboardAvoidingView 
      style={{ flex: 1, backgroundColor: theme.background }}
      behavior={Platform.OS === 'ios' ? 'padding' : undefined}
      keyboardVerticalOffset={Platform.OS === 'ios' ? 100 : 0}
    >
      <Stack.Screen options={{ title: 'Detalhes do Ticket' }} />
      <ScrollView contentContainerStyle={styles.scrollContent} showsVerticalScrollIndicator={false}>
        {/* Header/Info */}
        <Animated.View entering={FadeInDown.duration(400)}>
          <GlassCard style={styles.headerCard}>
            <View style={styles.topRow}>
              <View style={{ flex: 1 }}>
                <Text style={[styles.subject, { color: theme.text }]}>{ticket?.subject}</Text>
                <Text style={[styles.ticketId, { color: theme.textMuted }]}>ID: {ticket?.ticket_id}</Text>
              </View>
              <StatusBadge status={ticket?.status} theme={theme} />
            </View>
            
            <View style={styles.metaRow}>
              <View style={styles.metaItem}>
                <Ionicons name="calendar-outline" size={14} color={theme.textMuted} />
                <Text style={[styles.metaText, { color: theme.textMuted }]}>
                  {ticket?.created_at ? new Date(ticket.created_at).toLocaleDateString() : '—'}
                </Text>
              </View>
              <View style={[styles.metaItem, { marginLeft: 16 }]}>
                <Text style={[styles.metaLabel, { color: theme.textMuted }]}>Prioridade: </Text>
                <PriorityBadge priority={ticket?.priority} theme={theme} />
              </View>
            </View>

            <View style={[styles.divider, { backgroundColor: theme.border }]} />
            
            <Text style={[styles.descriptionTitle, { color: theme.textMuted }]}>Descrição</Text>
            <Text style={[styles.description, { color: theme.text }]}>{ticket?.description}</Text>
          </GlassCard>
        </Animated.View>

        {/* Conversation/History */}
        <Text style={[styles.sectionTitle, { color: theme.text }]}>Conversa</Text>
        
        {history.length === 0 ? (
          <View style={styles.emptyHistory}>
            <Text style={[styles.emptyText, { color: theme.textMuted }]}>Ainda não há comentários.</Text>
          </View>
        ) : (
          history.map((item, index) => (
            <Animated.View key={index} entering={FadeInDown.duration(400).delay(index * 50)}>
              <View style={[
                styles.messageContainer, 
                item.user_id === user_id ? styles.messageRight : styles.messageLeft
              ]}>
                <View style={[
                  styles.messageBubble, 
                  { backgroundColor: item.user_id === user_id ? theme.primary : theme.surface },
                  item.user_id !== user_id && styles.messageBubbleLeft
                ]}>
                  <Text style={[
                    styles.messageText, 
                    { color: item.user_id === user_id ? '#FFF' : theme.text }
                  ]}>
                    {item.description}
                  </Text>
                  <Text style={[
                      styles.messageTime, 
                      { color: item.user_id === user_id ? 'rgba(255,255,255,0.7)' : theme.textMuted }
                  ]}>
                    {item.created_at ? new Date(item.created_at).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }) : ''}
                  </Text>
                </View>
              </View>
            </Animated.View>
          ))
        )}
      </ScrollView>

      {/* Input Area */}
      {ticket?.status !== '4' && (
        <View style={[styles.inputContainer, { backgroundColor: theme.surface, borderTopColor: theme.border }]}>
          <TextInput
            style={[styles.input, { color: theme.text, backgroundColor: theme.background }]}
            placeholder="Escreva sua resposta..."
            placeholderTextColor={theme.textMuted}
            value={comment}
            onChangeText={setComment}
            multiline
            maxLength={500}
          />
          <TouchableOpacity 
            style={[styles.sendButton, { backgroundColor: theme.primary }]} 
            onPress={handleSendComment}
            disabled={sending || !comment.trim()}
          >
            {sending ? (
              <ActivityIndicator size="small" color="#FFF" />
            ) : (
              <Ionicons name="send" size={20} color="#FFF" />
            )}
          </TouchableOpacity>
        </View>
      )}
    </KeyboardAvoidingView>
  );
}

const styles = StyleSheet.create({
  center: { flex: 1, justifyContent: 'center', alignItems: 'center' },
  scrollContent: { padding: 20, paddingBottom: 40 },
  headerCard: {
    padding: 20,
    borderRadius: 24,
    marginBottom: 24,
  },
  topRow: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'flex-start',
    marginBottom: 12,
  },
  subject: { fontSize: 20, fontWeight: '800', letterSpacing: -0.5, marginBottom: 4 },
  ticketId: { fontSize: 13, fontWeight: '600' },
  badge: {
    paddingHorizontal: 10,
    paddingVertical: 5,
    borderRadius: 8,
    alignItems: 'center',
    justifyContent: 'center',
  },
  badgeText: { fontSize: 12, fontWeight: '700' },
  metaRow: {
    flexDirection: 'row',
    alignItems: 'center',
    marginBottom: 20,
  },
  metaItem: { flexDirection: 'row', alignItems: 'center' },
  metaText: { fontSize: 13, marginLeft: 4, fontWeight: '500' },
  metaLabel: { fontSize: 13, fontWeight: '500' },
  divider: { height: 1, width: '100%', marginBottom: 16 },
  descriptionTitle: { fontSize: 12, fontWeight: '700', textTransform: 'uppercase', marginBottom: 8, letterSpacing: 0.5 },
  description: { fontSize: 15, lineHeight: 22, fontWeight: '400' },
  sectionTitle: { fontSize: 18, fontWeight: '700', marginBottom: 16, paddingLeft: 4 },
  emptyHistory: { padding: 40, alignItems: 'center' },
  emptyText: { fontSize: 14, fontStyle: 'italic' },
  messageContainer: {
    flexDirection: 'row',
    marginBottom: 12,
    width: '100%',
  },
  messageLeft: { justifyContent: 'flex-start' },
  messageRight: { justifyContent: 'flex-end' },
  messageBubble: {
    maxWidth: '80%',
    padding: 12,
    paddingHorizontal: 16,
    borderRadius: 20,
    borderBottomRightRadius: 4,
  },
  messageBubbleLeft: {
    borderBottomRightRadius: 20,
    borderBottomLeftRadius: 4,
  },
  messageText: { fontSize: 15, lineHeight: 20 },
  messageTime: { fontSize: 10, alignSelf: 'flex-end', marginTop: 4 },
  inputContainer: {
    flexDirection: 'row',
    alignItems: 'flex-end',
    padding: 12,
    paddingBottom: Platform.OS === 'ios' ? 24 : 12,
    borderTopWidth: 1,
  },
  input: {
    flex: 1,
    borderRadius: 20,
    paddingHorizontal: 16,
    paddingTop: 10,
    paddingBottom: 10,
    maxHeight: 100,
    fontSize: 15,
    marginRight: 10,
    borderWidth: 1,
    borderColor: 'rgba(0,0,0,0.05)',
  },
  sendButton: {
    width: 44,
    height: 44,
    borderRadius: 22,
    justifyContent: 'center',
    alignItems: 'center',
  }
});
