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

export default function TicketDetailScreen() {
  const { id } = useLocalSearchParams<{ id: string }>();
  const router = useRouter();
  const [reply, setReply] = useState('');
  const { data: ticket, isLoading, refetch } = useQuery({
    queryKey: ['ticket', id],
    queryFn: () => api.get(`/api/v1/tickets/${id}`).then(r => r.data),
  });

  const sendReply = async () => {
    if (!reply.trim()) return;
    try {
      await api.post(`/api/v1/tickets/${id}/messages`, { message: reply });
      setReply('');
      refetch();
    } catch { Alert.alert('Error', 'Could not send reply.'); }
  };

  if (isLoading) return <ActivityIndicator color="#2563EB" className="flex-1 mt-20" />;

  return (
    <View className="flex-1 bg-gray-50">
      <View className="pt-14 pb-4 px-4 bg-white border-b border-gray-100">
        <TouchableOpacity onPress={() => router.back()} className="mb-2">
          <Text className="text-primary text-sm">← Tickets</Text>
        </TouchableOpacity>
        <Text className="text-lg font-bold text-gray-900">{ticket?.subject}</Text>
        <Text className="text-gray-500 text-xs">{ticket?.clientName} · {ticket?.status}</Text>
      </View>

      <ScrollView className="flex-1 px-4 py-4">
        {(ticket?.messages ?? []).map((m: any) => (
          <View key={m.id} className={`mb-3 p-3 rounded-xl max-w-xs ${m.senderType === 'staff' ? 'bg-primary self-end' : 'bg-white self-start border border-gray-100'}`}>
            <Text className={m.senderType === 'staff' ? 'text-white text-sm' : 'text-gray-900 text-sm'}>{m.message}</Text>
            <Text className={`text-xs mt-1 ${m.senderType === 'staff' ? 'text-blue-200' : 'text-gray-400'}`}>{m.senderName}</Text>
          </View>
        ))}
      </ScrollView>

      <View className="px-4 py-3 bg-white border-t border-gray-100 flex-row gap-2">
        <TextInput
          className="flex-1 border border-gray-200 rounded-xl px-3 py-2.5 text-sm bg-gray-50"
          placeholder="Type a reply..."
          value={reply}
          onChangeText={setReply}
          multiline
        />
        <TouchableOpacity className="bg-primary rounded-xl px-4 items-center justify-center" onPress={sendReply}>
          <Text className="text-white font-medium text-sm">Send</Text>
        </TouchableOpacity>
      </View>
    </View>
  );
}
