import { useState } from 'react';
import { View, Text, ScrollView, TextInput, TouchableOpacity, ActivityIndicator, Alert } from 'react-native';
import { useLocalSearchParams, router } from 'expo-router';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { api } from '../../../services/api';

export default function TicketDetailScreen() {
  const { id } = useLocalSearchParams<{ id: string }>();
  const [reply, setReply] = useState('');
  const qc = useQueryClient();

  const { data, isLoading } = useQuery({
    queryKey: ['ticket', id],
    queryFn: () => api.get(`/api/v1/tickets/${id}`).then(r => r.data),
  });

  const addReply = useMutation({
    mutationFn: () => api.post(`/api/v1/tickets/${id}/messages`, { message: reply }),
    onSuccess: () => { setReply(''); qc.invalidateQueries({ queryKey: ['ticket', id] }); },
    onError: () => Alert.alert('Error', 'Could not send reply.'),
  });

  if (isLoading) return <View className="flex-1 items-center justify-center"><ActivityIndicator color="#2563EB" /></View>;

  return (
    <View className="flex-1 bg-gray-50">
      <View className="px-4 pt-14 pb-4 bg-primary flex-row items-center">
        <TouchableOpacity onPress={() => router.back()} className="mr-3">
          <Text className="text-white text-lg">←</Text>
        </TouchableOpacity>
        <View className="flex-1">
          <Text className="text-white font-bold" numberOfLines={1}>{data?.subject}</Text>
          <Text className="text-white/70 text-xs">{data?.status} · {data?.priority}</Text>
        </View>
      </View>
      <ScrollView className="flex-1 px-4 py-4">
        {(data?.messages ?? []).map((m: any) => (
          <View key={m.id} className={`mb-3 max-w-xs ${m.senderType === 'AGENT' ? 'self-end items-end' : 'self-start items-start'}`}>
            <View className={`rounded-2xl px-4 py-3 ${m.senderType === 'AGENT' ? 'bg-primary' : 'bg-white border border-gray-100'}`}>
              <Text className={m.senderType === 'AGENT' ? 'text-white' : 'text-gray-900'}>{m.message}</Text>
            </View>
            <Text className="text-gray-400 text-xs mt-1">{m.senderName}</Text>
          </View>
        ))}
      </ScrollView>
      <View className="flex-row px-4 py-3 bg-white border-t border-gray-100">
        <TextInput
          className="flex-1 bg-gray-100 rounded-xl px-4 py-3 mr-2"
          placeholder="Type a reply..."
          value={reply}
          onChangeText={setReply}
          multiline
        />
        <TouchableOpacity
          className="bg-primary rounded-xl px-4 items-center justify-center"
          onPress={() => reply.trim() && addReply.mutate()}
          disabled={addReply.isPending}
        >
          {addReply.isPending ? <ActivityIndicator color="white" /> : <Text className="text-white font-semibold">Send</Text>}
        </TouchableOpacity>
      </View>
    </View>
  );
}
