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

const STATUS_CONFIG: Record<string, { label: string; color: string; bg: string }> = {
  NEW:        { label: 'New',        color: '#0891B2', bg: '#ECFEFF' },
  CONTACTED:  { label: 'Contacted',  color: '#D97706', bg: '#FEF3C7' },
  INTERESTED: { label: 'Interested', color: '#7C3AED', bg: '#F5F3FF' },
  CONVERTED:  { label: 'Converted',  color: '#166534', bg: '#DCFCE7' },
  LOST:       { label: 'Lost',       color: '#6B7280', bg: '#F1F5F9' },
};

export default function LeadsScreen() {
  const { user } = useAuthStore();
  const qc = useQueryClient();
  const [search, setSearch] = useState('');
  const [showAdd, setShowAdd] = useState(false);
  const [newName, setNewName]       = useState('');
  const [newPhone, setNewPhone]     = useState('');
  const [newAddress, setNewAddress] = useState('');
  const [newNotes, setNewNotes]     = useState('');
  const [saving, setSaving]         = useState(false);

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

  const leads: any[] = (data ?? []).filter((l: any) =>
    `${l.firstName} ${l.lastName} ${l.phone}`.toLowerCase().includes(search.toLowerCase())
  );

  const addLead = async () => {
    const parts = newName.trim().split(' ');
    const firstName = parts[0] ?? '';
    const lastName  = parts.slice(1).join(' ') || '—';
    if (!firstName) { Alert.alert('Required', 'Enter the lead\'s name.'); return; }
    if (!newPhone.trim()) { Alert.alert('Required', 'Enter a contact number.'); return; }
    setSaving(true);
    try {
      await api.post('/api/v1/leads', {
        firstName, lastName,
        phone: newPhone.trim(),
        ...(newAddress.trim() ? { address: newAddress.trim() } : {}),
        ...(newNotes.trim()   ? { notes: newNotes.trim() }   : {}),
      });
      setShowAdd(false);
      setNewName(''); setNewPhone(''); setNewAddress(''); setNewNotes('');
      qc.invalidateQueries({ queryKey: ['leads'] });
      refetch();
    } catch (e: any) {
      Alert.alert('Error', e?.response?.data?.message ?? 'Could not save lead.');
    } finally {
      setSaving(false);
    }
  };

  const renderLead = ({ item: l }: { item: any }) => {
    const cfg = STATUS_CONFIG[l.status] ?? STATUS_CONFIG.NEW;
    return (
      <TouchableOpacity
        onPress={() => router.push(`/(app)/leads/${l.id}`)}
        activeOpacity={0.7}
        style={{ backgroundColor: '#fff', borderRadius: 14, padding: 16, marginBottom: 10, borderWidth: 1, borderColor: '#F1F5F9', flexDirection: 'row', alignItems: 'center' }}
      >
        {/* Avatar circle */}
        <View style={{ width: 44, height: 44, borderRadius: 22, backgroundColor: '#ECFEFF', alignItems: 'center', justifyContent: 'center', marginRight: 14 }}>
          <Text style={{ fontSize: 18, fontWeight: '800', color: '#0891B2' }}>
            {l.firstName?.[0]?.toUpperCase() ?? '?'}
          </Text>
        </View>
        <View style={{ flex: 1 }}>
          <Text style={{ fontSize: 16, fontWeight: '700', color: '#0F172A' }}>
            {l.firstName} {l.lastName !== '—' ? l.lastName : ''}
          </Text>
          <Text style={{ fontSize: 14, color: '#64748B', marginTop: 2 }}>{l.phone}</Text>
          {l.notes ? <Text style={{ fontSize: 13, color: '#94A3B8', marginTop: 2 }} numberOfLines={1}>{l.notes}</Text> : null}
        </View>
        <View style={{ backgroundColor: cfg.bg, borderRadius: 20, paddingHorizontal: 10, paddingVertical: 4 }}>
          <Text style={{ fontSize: 12, fontWeight: '700', color: cfg.color }}>{cfg.label}</Text>
        </View>
      </TouchableOpacity>
    );
  };

  return (
    <SafeAreaView style={{ flex: 1, backgroundColor: '#F8FAFC' }}>
      {/* Header */}
      <View style={{ backgroundColor: '#0891B2', paddingHorizontal: 20, paddingTop: 16, paddingBottom: 20, flexDirection: 'row', alignItems: 'flex-end', justifyContent: 'space-between' }}>
        <View>
          <Text style={{ color: '#FFF', fontSize: 28, fontWeight: '800' }}>Leads</Text>
          <Text style={{ color: '#A5F3FC', fontSize: 15, marginTop: 2 }}>{leads.length} prospect{leads.length !== 1 ? 's' : ''}</Text>
        </View>
        <TouchableOpacity
          onPress={() => setShowAdd(true)}
          style={{ backgroundColor: '#fff', borderRadius: 20, paddingHorizontal: 14, paddingVertical: 8, flexDirection: 'row', alignItems: 'center', gap: 6 }}
        >
          <Text style={{ fontSize: 18, color: '#0891B2', fontWeight: '800', lineHeight: 20 }}>+</Text>
          <Text style={{ fontSize: 14, fontWeight: '700', color: '#0891B2' }}>Add Lead</Text>
        </TouchableOpacity>
      </View>

      {/* Search */}
      <View style={{ backgroundColor: '#fff', paddingHorizontal: 16, paddingVertical: 12, 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 by name or phone"
            placeholderTextColor="#94A3B8"
            value={search} onChangeText={setSearch}
          />
          {search.length > 0 && (
            <TouchableOpacity onPress={() => setSearch('')}>
              <View style={{ width: 20, height: 20, borderRadius: 10, backgroundColor: '#CBD5E1', alignItems: 'center', justifyContent: 'center' }}>
                <Text style={{ color: '#fff', fontSize: 12, fontWeight: '800' }}>×</Text>
              </View>
            </TouchableOpacity>
          )}
        </View>
      </View>

      {isLoading ? (
        <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
          <ActivityIndicator color="#0891B2" size="large" />
        </View>
      ) : (
        <FlatList
          data={leads}
          keyExtractor={i => i.id}
          renderItem={renderLead}
          contentContainerStyle={{ padding: 16, paddingBottom: 40 }}
          refreshControl={<RefreshControl refreshing={isRefetching} onRefresh={refetch} tintColor="#0891B2" />}
          ListEmptyComponent={
            <View style={{ alignItems: 'center', paddingTop: 60 }}>
              <Text style={{ fontSize: 40, marginBottom: 12 }}>👥</Text>
              <Text style={{ fontSize: 17, fontWeight: '700', color: '#475569' }}>No leads yet</Text>
              <Text style={{ fontSize: 14, color: '#94A3B8', marginTop: 4 }}>Tap + Add Lead to record a prospect</Text>
            </View>
          }
        />
      )}

      {/* Add Lead Modal */}
      <Modal visible={showAdd} transparent animationType="slide" onRequestClose={() => setShowAdd(false)}>
        <View style={{ flex: 1, backgroundColor: 'rgba(0,0,0,0.45)', justifyContent: 'flex-end' }}>
          <TouchableOpacity style={{ flex: 1 }} onPress={() => setShowAdd(false)} />
          <View style={{ backgroundColor: '#fff', borderTopLeftRadius: 24, borderTopRightRadius: 24, padding: 24, paddingBottom: 40 }}>
            <View style={{ width: 40, height: 4, backgroundColor: '#E2E8F0', borderRadius: 2, alignSelf: 'center', marginBottom: 20 }} />
            <Text style={{ fontSize: 20, fontWeight: '800', color: '#1E293B', marginBottom: 20 }}>New Lead</Text>

            <Text style={{ fontSize: 13, fontWeight: '600', color: '#64748B', marginBottom: 6 }}>Full Name <Text style={{ color: '#DC2626' }}>*</Text></Text>
            <TextInput
              value={newName} onChangeText={setNewName}
              placeholder="Juan Dela Cruz"
              autoCapitalize="words"
              style={{ borderWidth: 1.5, borderColor: '#E2E8F0', borderRadius: 12, paddingHorizontal: 14, paddingVertical: 13, fontSize: 16, color: '#1E293B', marginBottom: 14 }}
            />

            <Text style={{ fontSize: 13, fontWeight: '600', color: '#64748B', marginBottom: 6 }}>Contact Number <Text style={{ color: '#DC2626' }}>*</Text></Text>
            <TextInput
              value={newPhone} onChangeText={setNewPhone}
              placeholder="09XXXXXXXXX"
              keyboardType="phone-pad"
              style={{ borderWidth: 1.5, borderColor: '#E2E8F0', borderRadius: 12, paddingHorizontal: 14, paddingVertical: 13, fontSize: 16, color: '#1E293B', marginBottom: 14 }}
            />

            <Text style={{ fontSize: 13, fontWeight: '600', color: '#64748B', marginBottom: 6 }}>Address (optional)</Text>
            <TextInput
              value={newAddress} onChangeText={setNewAddress}
              placeholder="Sitio, Barangay, Municipality..."
              style={{ borderWidth: 1.5, borderColor: '#E2E8F0', borderRadius: 12, paddingHorizontal: 14, paddingVertical: 13, fontSize: 16, color: '#1E293B', marginBottom: 14 }}
            />

            <Text style={{ fontSize: 13, fontWeight: '600', color: '#64748B', marginBottom: 6 }}>Notes (optional)</Text>
            <TextInput
              value={newNotes} onChangeText={setNewNotes}
              placeholder="Location, interest, remarks..."
              multiline
              style={{ borderWidth: 1, borderColor: '#E2E8F0', borderRadius: 12, paddingHorizontal: 14, paddingVertical: 12, fontSize: 15, color: '#1E293B', marginBottom: 20, minHeight: 72, textAlignVertical: 'top' }}
            />

            <TouchableOpacity
              onPress={addLead} disabled={saving}
              style={{ backgroundColor: saving ? '#94A3B8' : '#0891B2', borderRadius: 14, paddingVertical: 17, alignItems: 'center' }}
            >
              {saving ? <ActivityIndicator color="#fff" /> : <Text style={{ fontSize: 16, fontWeight: '700', color: '#fff' }}>Save Lead</Text>}
            </TouchableOpacity>
          </View>
        </View>
      </Modal>
    </SafeAreaView>
  );
}
