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

const PRIORITIES = ['NORMAL', 'HIGH'];
const PRIORITY_COLOR: Record<string, string> = { HIGH: '#DC2626', NORMAL: '#0891B2' };
const PRIORITY_BG: Record<string, string>    = { HIGH: '#FEE2E2', NORMAL: '#ECFEFF' };

const TYPES = [
  { value: 'SUPPORT',      label: 'Support' },
  { value: 'INSTALLATION', label: 'Installation' },
  { value: 'BILLING',      label: 'Billing' },
];

export default function NewTaskScreen() {
  const qc = useQueryClient();
  const [subject, setSubject] = useState('');
  const [description, setDescription] = useState('');
  const [priority, setPriority] = useState('NORMAL');
  const [type, setType] = useState('SUPPORT');
  const [search, setSearch] = useState('');
  const [debouncedSearch, setDebouncedSearch] = useState('');
  const [client, setClient] = useState<any>(null);
  const [loading, setLoading] = useState(false);

  const { data: searchResults, isFetching: searching } = useQuery({
    queryKey: ['client-search', debouncedSearch],
    queryFn: () => api.get(`/api/v1/clients?search=${debouncedSearch}&limit=8`).then(r => r.data?.data ?? r.data ?? []),
    enabled: debouncedSearch.trim().length >= 2,
  });

  const handleSearchChange = (v: string) => {
    setSearch(v);
    setTimeout(() => setDebouncedSearch(v), 400);
  };

  const submit = async () => {
    if (!subject.trim()) return Alert.alert('Required', 'Please enter a subject.');
    if (!client) return Alert.alert('Required', 'Please select a client.');
    setLoading(true);
    try {
      await api.post('/api/v1/tickets', {
        subject: subject.trim(),
        description: description.trim() || undefined,
        priority, type, clientId: client.id,
      });
      qc.invalidateQueries({ queryKey: ['tasks'] });
      qc.invalidateQueries({ queryKey: ['dashboard'] });
      Alert.alert('Task Created', subject, [{ text: 'OK', onPress: () => router.back() }]);
    } catch (e: any) {
      Alert.alert('Error', e?.response?.data?.message ?? 'Could not create task.');
    } finally { setLoading(false); }
  };

  return (
    <SafeAreaView style={{ flex: 1, backgroundColor: '#0891B2' }} edges={['top']}>
      <View style={{ flex: 1, backgroundColor: '#F8FAFC' }}>
        <View style={{ backgroundColor: '#0891B2', paddingHorizontal: 20, paddingTop: 12, paddingBottom: 20 }}>
          <TouchableOpacity onPress={() => router.back()} style={{ marginBottom: 12 }} activeOpacity={0.7}>
            <Text style={{ color: '#A5F3FC', fontSize: 17, fontWeight: '600' }}>← Back</Text>
          </TouchableOpacity>
          <Text style={{ color: '#FFF', fontSize: 28, fontWeight: '800' }}>New Ticket</Text>
        </View>

        <ScrollView style={{ flex: 1 }} contentContainerStyle={{ padding: 16, paddingBottom: 40 }} keyboardShouldPersistTaps="handled">
          {/* Client Search */}
          <Text style={{ fontSize: 16, fontWeight: '700', color: '#0F172A', marginBottom: 10 }}>
            Client <Text style={{ color: '#DC2626' }}>*</Text>
          </Text>
          {client ? (
            <View style={{ flexDirection: 'row', alignItems: 'center', backgroundColor: '#ECFEFF', borderRadius: 14, padding: 18, marginBottom: 20, borderWidth: 1, borderColor: '#A5F3FC' }}>
              <View style={{ flex: 1 }}>
                <Text style={{ fontSize: 17, fontWeight: '700', color: '#0E7490' }}>{client.firstName} {client.lastName}</Text>
                <Text style={{ fontSize: 15, color: '#0891B2', marginTop: 2 }}>{client.accountNumber}</Text>
              </View>
              <TouchableOpacity onPress={() => { setClient(null); setSearch(''); setDebouncedSearch(''); }} hitSlop={{ top: 10, bottom: 10, left: 10, right: 10 }}>
                <Text style={{ fontSize: 15, fontWeight: '700', color: '#0891B2' }}>Change</Text>
              </TouchableOpacity>
            </View>
          ) : (
            <View style={{ marginBottom: 20 }}>
              <View style={{ backgroundColor: '#FFF', borderWidth: 1.5, borderColor: '#E2E8F0', borderRadius: 14, flexDirection: 'row', alignItems: 'center', paddingHorizontal: 16, marginBottom: 8 }}>
                <TextInput
                  style={{ flex: 1, paddingVertical: 14, fontSize: 16, color: '#0F172A' }}
                  placeholder="Search by name or account #"
                  placeholderTextColor="#94A3B8"
                  value={search}
                  onChangeText={handleSearchChange}
                  autoCapitalize="none"
                />
                {search.length > 0 && (
                  <TouchableOpacity onPress={() => { setSearch(''); setDebouncedSearch(''); }} hitSlop={{ top: 10, bottom: 10, left: 10, right: 10 }}>
                    <View style={{ width: 22, height: 22, borderRadius: 11, backgroundColor: '#CBD5E1', alignItems: 'center', justifyContent: 'center' }}>
                      <Text style={{ color: '#FFF', fontSize: 13, fontWeight: '800', lineHeight: 16 }}>×</Text>
                    </View>
                  </TouchableOpacity>
                )}
                {searching && <ActivityIndicator size="small" color="#0891B2" style={{ marginLeft: 8 }} />}
              </View>
              {debouncedSearch.trim().length >= 2 && (
                <View style={{ backgroundColor: '#FFF', borderRadius: 14, borderWidth: 1, borderColor: '#E2E8F0', overflow: 'hidden' }}>
                  {(searchResults ?? []).length === 0 && !searching ? (
                    <Text style={{ paddingHorizontal: 16, paddingVertical: 14, fontSize: 15, color: '#94A3B8' }}>No clients found</Text>
                  ) : (
                    (searchResults ?? []).map((c: any, i: number, arr: any[]) => (
                      <TouchableOpacity
                        key={c.id}
                        style={{ paddingHorizontal: 16, paddingVertical: 14, borderBottomWidth: i < arr.length - 1 ? 1 : 0, borderBottomColor: '#F1F5F9' }}
                        onPress={() => { setClient(c); setSearch(''); setDebouncedSearch(''); }}
                        activeOpacity={0.7}
                      >
                        <Text style={{ fontSize: 16, fontWeight: '600', color: '#0F172A' }}>{c.firstName} {c.lastName}</Text>
                        <Text style={{ fontSize: 14, color: '#64748B', marginTop: 2 }}>{c.accountNumber}</Text>
                      </TouchableOpacity>
                    ))
                  )}
                </View>
              )}
            </View>
          )}

          {/* Subject */}
          <Text style={{ fontSize: 16, fontWeight: '700', color: '#0F172A', marginBottom: 10 }}>
            Subject <Text style={{ color: '#DC2626' }}>*</Text>
          </Text>
          <TextInput
            style={{ backgroundColor: '#FFF', borderWidth: 1.5, borderColor: '#E2E8F0', borderRadius: 14, paddingHorizontal: 18, paddingVertical: 14, fontSize: 16, color: '#0F172A', marginBottom: 20 }}
            placeholder="e.g. New installation - Barangay 5"
            placeholderTextColor="#94A3B8"
            value={subject}
            onChangeText={setSubject}
          />

          {/* Type */}
          <Text style={{ fontSize: 16, fontWeight: '700', color: '#0F172A', marginBottom: 10 }}>Type</Text>
          <View style={{ flexDirection: 'row', flexWrap: 'wrap', marginBottom: 20 }}>
            {TYPES.map(t => (
              <TouchableOpacity
                key={t.value}
                onPress={() => setType(t.value)}
                style={{ borderRadius: 20, paddingHorizontal: 16, paddingVertical: 10, marginRight: 8, marginBottom: 8, backgroundColor: type === t.value ? '#0891B2' : '#FFF', borderWidth: 1.5, borderColor: type === t.value ? '#0891B2' : '#E2E8F0' }}
                activeOpacity={0.7}
              >
                <Text style={{ fontSize: 14, fontWeight: '600', color: type === t.value ? '#FFF' : '#64748B' }}>{t.label}</Text>
              </TouchableOpacity>
            ))}
          </View>

          {/* Priority */}
          <Text style={{ fontSize: 16, fontWeight: '700', color: '#0F172A', marginBottom: 10 }}>Priority</Text>
          <View style={{ flexDirection: 'row', marginBottom: 20 }}>
            {PRIORITIES.map(p => {
              const isSelected = priority === p;
              const isHigh = p === 'HIGH';
              const selectedBg = isHigh ? '#DC2626' : '#0891B2';
              const unselectedBg = isHigh ? '#FEF2F2' : '#F0F9FF';
              const selectedText = '#FFF';
              const unselectedText = isHigh ? '#DC2626' : '#0891B2';
              const desc = isHigh ? 'Urgent, escalate' : 'Standard queue';
              return (
                <TouchableOpacity
                  key={p}
                  onPress={() => setPriority(p)}
                  style={{ flex: 1, borderRadius: 14, paddingVertical: 16, alignItems: 'center', marginHorizontal: 4, backgroundColor: isSelected ? selectedBg : unselectedBg, borderWidth: 1.5, borderColor: isSelected ? selectedBg : '#E2E8F0' }}
                  activeOpacity={0.7}
                >
                  <Text style={{ fontSize: 16, fontWeight: isHigh ? '800' : '700', color: isSelected ? selectedText : unselectedText }}>{p}</Text>
                  <Text style={{ fontSize: 13, fontWeight: '500', color: isSelected ? 'rgba(255,255,255,0.8)' : '#94A3B8', marginTop: 3 }}>{desc}</Text>
                </TouchableOpacity>
              );
            })}
          </View>

          {/* Description */}
          <Text style={{ fontSize: 16, fontWeight: '700', color: '#0F172A', marginBottom: 10 }}>
            Description <Text style={{ fontWeight: '400', color: '#94A3B8' }}>(optional)</Text>
          </Text>
          <TextInput
            style={{ backgroundColor: '#FFF', borderWidth: 1.5, borderColor: '#E2E8F0', borderRadius: 14, paddingHorizontal: 18, paddingVertical: 14, fontSize: 16, color: '#0F172A', marginBottom: 24, minHeight: 100, textAlignVertical: 'top' }}
            placeholder="Describe the issue in detail..."
            placeholderTextColor="#94A3B8"
            value={description}
            onChangeText={setDescription}
            multiline
          />

          <TouchableOpacity
            style={{ backgroundColor: client && subject.trim() ? '#0891B2' : '#CBD5E1', borderRadius: 14, paddingVertical: 18, alignItems: 'center' }}
            onPress={submit}
            disabled={loading || !client || !subject.trim()}
            activeOpacity={0.8}
          >
            {loading ? <ActivityIndicator color="#FFF" /> : <Text style={{ color: '#FFF', fontSize: 17, fontWeight: '700' }}>Create Ticket</Text>}
          </TouchableOpacity>
        </ScrollView>
      </View>
    </SafeAreaView>
  );
}
