import { useState } from 'react';
import { View, Text, FlatList, TextInput, TouchableOpacity, ActivityIndicator, RefreshControl, ScrollView } from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import { useQuery } from '@tanstack/react-query';
import { useFocusEffect } from 'expo-router';
import { useCallback } from 'react';
import { router } from 'expo-router';
import { api } from '../../../services/api';

const PRIORITY_COLOR: Record<string, string> = { HIGH: '#DC2626', NORMAL: '#0891B2', LOW: '#6B7280' };
const PRIORITY_BG: Record<string, string>    = { HIGH: '#FEE2E2', NORMAL: '#ECFEFF', LOW: '#F1F5F9' };
const STATUS_COLOR: Record<string, string>   = { OPEN: '#0891B2', IN_PROGRESS: '#D97706', RESOLVED: '#16A34A', CLOSED: '#6B7280' };
const STATUS_BG: Record<string, string>      = { OPEN: '#ECFEFF', IN_PROGRESS: '#FFFBEB', RESOLVED: '#F0FDF4', CLOSED: '#F1F5F9' };
const TYPE_COLOR: Record<string, string>     = { INSTALLATION: '#0891B2', SUPPORT: '#7C3AED', BILLING: '#D97706' };
const TYPE_BG: Record<string, string>        = { INSTALLATION: '#ECFEFF', SUPPORT: '#F5F3FF', BILLING: '#FFFBEB' };

const STATUS_FILTERS = ['All', 'OPEN', 'IN_PROGRESS', 'RESOLVED', 'CLOSED'];

export default function TasksScreen() {
  const [search, setSearch] = useState('');
  const [statusFilter, setStatusFilter] = useState('All');

  const { data, isLoading, refetch, isRefetching } = useQuery({
    queryKey: ['tasks'],
    queryFn: () => api.get('/api/v1/tickets?limit=100').then(r => r.data?.data ?? r.data ?? []),
  });

  // Refetch list every time this screen comes into focus (fixes stale list after navigating back)
  useFocusEffect(useCallback(() => { refetch(); }, []));

  const tasks = (data ?? []).filter((t: any) => {
    const matchSearch = `${t.subject} ${t.client?.firstName ?? ''} ${t.client?.lastName ?? ''}`.toLowerCase().includes(search.toLowerCase());
    const matchStatus = statusFilter === 'All' || t.status === statusFilter;
    return matchSearch && matchStatus;
  });

  return (
    <SafeAreaView style={{ flex: 1, backgroundColor: '#0891B2' }} edges={['top']}>
      <View style={{ flex: 1, backgroundColor: '#F8FAFC' }}>
        <View style={{ backgroundColor: '#0891B2', paddingHorizontal: 20, paddingTop: 16, paddingBottom: 16, flexDirection: 'row', justifyContent: 'space-between', alignItems: 'flex-end' }}>
          <View>
            <Text style={{ color: '#FFF', fontSize: 28, fontWeight: '800' }}>Tickets</Text>
            <Text style={{ color: '#A5F3FC', fontSize: 14, marginTop: 2 }}>{tasks.length} showing</Text>
          </View>
          <TouchableOpacity
            style={{ backgroundColor: 'rgba(255,255,255,0.2)', borderRadius: 12, paddingHorizontal: 16, paddingVertical: 10 }}
            onPress={() => router.push('/(app)/tasks/new')}
            activeOpacity={0.7}
          >
            <Text style={{ color: '#FFF', fontWeight: '700', fontSize: 15 }}>+ Ticket</Text>
          </TouchableOpacity>
        </View>

        <View style={{ backgroundColor: '#FFF', paddingHorizontal: 16, paddingTop: 12, paddingBottom: 8, borderBottomWidth: 1, borderBottomColor: '#F1F5F9' }}>
          <View style={{ backgroundColor: '#F8FAFC', borderWidth: 1.5, borderColor: '#E2E8F0', borderRadius: 12, flexDirection: 'row', alignItems: 'center', paddingHorizontal: 14 }}>
            <TextInput
              style={{ flex: 1, paddingVertical: 13, fontSize: 16, color: '#0F172A' }}
              placeholder="Search tasks..."
              placeholderTextColor="#94A3B8"
              value={search}
              onChangeText={setSearch}
            />
            {search.length > 0 && (
              <TouchableOpacity onPress={() => setSearch('')} hitSlop={{ top: 10, bottom: 10, left: 10, right: 10 }}>
                <View style={{ width: 20, height: 20, borderRadius: 10, backgroundColor: '#CBD5E1', alignItems: 'center', justifyContent: 'center' }}>
                  <Text style={{ color: '#FFF', fontSize: 13, fontWeight: '800', lineHeight: 16 }}>×</Text>
                </View>
              </TouchableOpacity>
            )}
          </View>

          <ScrollView horizontal showsHorizontalScrollIndicator={false} style={{ marginTop: 10, marginBottom: 4 }}>
            {STATUS_FILTERS.map(f => {
              const isActive = statusFilter === f;
              const color = f === 'All' ? '#0891B2' : STATUS_COLOR[f] ?? '#6B7280';
              return (
                <TouchableOpacity
                  key={f}
                  onPress={() => setStatusFilter(f)}
                  style={{ borderRadius: 20, paddingHorizontal: 16, paddingVertical: 8, marginRight: 8, backgroundColor: isActive ? color : '#F1F5F9' }}
                  activeOpacity={0.7}
                >
                  <Text style={{ fontSize: 14, fontWeight: '700', color: isActive ? '#FFF' : '#64748B' }}>
                    {f === 'All' ? 'All' : f.replace('_', ' ')}
                  </Text>
                </TouchableOpacity>
              );
            })}
          </ScrollView>
        </View>

        {isLoading ? (
          <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
            <ActivityIndicator color="#0891B2" size="large" />
          </View>
        ) : (
          <FlatList
            data={tasks}
            keyExtractor={(item) => item.id}
            refreshControl={<RefreshControl refreshing={isRefetching} onRefresh={refetch} tintColor="#0891B2" />}
            contentContainerStyle={{ padding: 16, paddingBottom: 32 }}
            renderItem={({ item }) => {
              const typeColor = TYPE_COLOR[item.type] ?? '#6B7280';
              const typeBg    = TYPE_BG[item.type]    ?? '#F1F5F9';
              return (
                <TouchableOpacity
                  style={{ backgroundColor: '#FFF', borderRadius: 16, padding: 18, marginBottom: 12, borderWidth: 1, borderColor: '#F1F5F9', borderLeftWidth: 4, borderLeftColor: typeColor }}
                  onPress={() => router.push(`/(app)/tasks/${item.id}`)}
                  activeOpacity={0.7}
                >
                  <View style={{ flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center', marginBottom: 8 }}>
                    <View style={{ flexDirection: 'row', alignItems: 'center', gap: 6 }}>
                      <View style={{ borderRadius: 20, paddingHorizontal: 10, paddingVertical: 4, backgroundColor: typeBg }}>
                        <Text style={{ fontSize: 12, fontWeight: '700', color: typeColor }}>{item.type}</Text>
                      </View>
                      {item.priority === 'HIGH' && (
                        <View style={{ borderRadius: 20, paddingHorizontal: 10, paddingVertical: 4, backgroundColor: PRIORITY_BG.HIGH }}>
                          <Text style={{ fontSize: 12, fontWeight: '700', color: PRIORITY_COLOR.HIGH }}>HIGH</Text>
                        </View>
                      )}
                    </View>
                    <View style={{ borderRadius: 20, paddingHorizontal: 10, paddingVertical: 4, backgroundColor: STATUS_BG[item.status] ?? '#F1F5F9' }}>
                      <Text style={{ fontSize: 12, fontWeight: '700', color: STATUS_COLOR[item.status] ?? '#6B7280' }}>{item.status?.replace('_', ' ')}</Text>
                    </View>
                  </View>
                  <Text style={{ fontSize: 16, fontWeight: '700', color: '#0F172A', marginBottom: 6 }} numberOfLines={2}>{item.subject}</Text>
                  <Text style={{ fontSize: 14, color: '#64748B' }}>
                    {item.client?.firstName} {item.client?.lastName}
                    {item.assignedTo ? ` · ${item.assignedTo.firstName} ${item.assignedTo.lastName}` : ' · Unassigned'}
                  </Text>
                  {item._count?.messages > 0 && (
                    <Text style={{ fontSize: 13, color: '#94A3B8', marginTop: 4 }}>{item._count.messages} message{item._count.messages !== 1 ? 's' : ''}</Text>
                  )}
                </TouchableOpacity>
              );
            }}
            ListEmptyComponent={
              <View style={{ alignItems: 'center', paddingVertical: 60 }}>
                <Text style={{ fontSize: 17, color: '#94A3B8' }}>No tasks found</Text>
              </View>
            }
          />
        )}
      </View>
    </SafeAreaView>
  );
}
