import { View, Text, FlatList, ActivityIndicator, TouchableOpacity, RefreshControl } from 'react-native';
import { useQuery } from '@tanstack/react-query';
import { useRouter } from 'expo-router';
import { api } from '../../../services/api';

const STATUS_COLOR: Record<string, string> = {
  open: 'bg-yellow-100 text-yellow-700',
  in_progress: 'bg-blue-100 text-blue-700',
  resolved: 'bg-green-100 text-green-700',
  closed: 'bg-gray-100 text-gray-500',
};

export default function TicketsScreen() {
  const router = useRouter();
  const { data, isLoading, refetch, isRefetching } = useQuery({
    queryKey: ['tickets'],
    queryFn: () => api.get('/api/v1/tickets').then(r => r.data?.data ?? r.data?.results ?? r.data),
  });

  const tickets = Array.isArray(data) ? data : [];

  return (
    <View className="flex-1 bg-gray-50 pt-14">
      <Text className="text-2xl font-bold text-gray-900 px-4 mb-4">Tickets</Text>
      {isLoading ? <ActivityIndicator color="#2563EB" className="mt-10" /> : (
        <FlatList
          data={tickets}
          keyExtractor={(item) => item.id}
          refreshControl={<RefreshControl refreshing={isRefetching} onRefresh={refetch} />}
          contentContainerStyle={{ paddingHorizontal: 16, paddingBottom: 24 }}
          renderItem={({ item }) => (
            <TouchableOpacity
              className="bg-white rounded-xl p-4 mb-2 border border-gray-100"
              onPress={() => router.push(`/(app)/tickets/${item.id}`)}
            >
              <View className="flex-row justify-between items-start">
                <Text className="flex-1 font-medium text-gray-900 mr-2">{item.subject}</Text>
                <View className={`px-2 py-0.5 rounded-full ${STATUS_COLOR[item.status] ?? 'bg-gray-100 text-gray-500'}`}>
                  <Text className="text-xs font-medium">{item.status}</Text>
                </View>
              </View>
              <Text className="text-gray-400 text-xs mt-1">{item.clientName} · {item.priority}</Text>
            </TouchableOpacity>
          )}
          ListEmptyComponent={<Text className="text-gray-400 text-center mt-10">No tickets</Text>}
        />
      )}
    </View>
  );
}
