import React, { useRef, useState } from 'react';
import {
  View,
  Text,
  StyleSheet,
  FlatList,
  RefreshControl,
  TouchableOpacity,
  Animated,
  Share,
  Alert,
  Modal,
  TextInput,
  ScrollView,
  ActivityIndicator,
} from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { COLORS, FONT_SIZE, SPACING, RADIUS, TEXT, SHADOWS } from '../../theme';
import { useTheme } from '../../theme';
import { Spinner, EmptyState } from '../../components/ui';
import { leadsAPI } from '../../services/api';
import { useTranslation } from '../../i18n';
import { Lead } from '../../types';

type LeadStatus = 'new' | 'contacted' | 'qualified' | 'closed' | 'lost';

const STATUS_COLORS: Record<LeadStatus, string> = {
  new: COLORS.info,
  contacted: COLORS.warning,
  qualified: COLORS.purple,
  closed: COLORS.success,
  lost: COLORS.error,
};

function buildCSV(leads: Lead[]): string {
  const header = 'Name,Email,Phone,Company,Chatbot,Status,Date';
  const rows = leads.map(l => [
    l.name ?? '',
    l.email ?? '',
    l.phone ?? '',
    l.company ?? '',
    l.chatbot_name ?? '',
    (l as any).status ?? '',
    l.created_at ? new Date(l.created_at).toLocaleDateString() : '',
  ].map(v => `"${v.replace(/"/g, '""')}"`).join(','));
  return [header, ...rows].join('\n');
}

export function LeadsScreen() {
  const { theme } = useTheme();
  const { t } = useTranslation();
  const qc = useQueryClient();
  const [selectedLead, setSelectedLead] = useState<Lead | null>(null);

  const STATUS_OPTIONS: { key: LeadStatus; label: string; color: string }[] = [
    { key: 'new', label: t.leads.status_new, color: COLORS.info },
    { key: 'contacted', label: t.leads.status_contacted, color: COLORS.warning },
    { key: 'qualified', label: t.leads.status_qualified, color: COLORS.purple },
    { key: 'closed', label: t.leads.status_closed, color: COLORS.success },
    { key: 'lost', label: t.leads.status_lost, color: COLORS.error },
  ];

  const { data, isLoading, refetch } = useQuery({
    queryKey: ['leads'],
    queryFn: () => leadsAPI.list({ limit: 200 }),
  });

  const leads: Lead[] = data?.leads ?? data?.items ?? data ?? [];

  const updateMutation = useMutation({
    mutationFn: ({ id, data }: { id: string; data: Record<string, any> }) =>
      leadsAPI.update(id, data),
    onSuccess: () => {
      qc.invalidateQueries({ queryKey: ['leads'] });
      setSelectedLead(null);
    },
  });

  const handleExport = async () => {
    if (leads.length === 0) {
      Alert.alert(t.leads.title, t.leads.no_export);
      return;
    }
    const csv = buildCSV(leads);
    await Share.share({ message: csv, title: 'Leads export' });
  };

  const renderItem = ({ item }: { item: Lead }) => (
    <LeadCard item={item} theme={theme} onPress={() => setSelectedLead(item)} />
  );

  return (
    <SafeAreaView style={[styles.safe, { backgroundColor: theme.bg }]} edges={['bottom']}>
      <View style={[styles.header, { borderBottomColor: theme.border }]}>
        <View>
          <Text style={[styles.headerTitle, { color: theme.text }]}>{t.leads.title}</Text>
          <Text style={[styles.headerSub, { color: theme.textSecondary }]}>
            {t.leads.subtitle(leads.length)}
          </Text>
        </View>
        <TouchableOpacity
          style={[styles.exportBtn, { backgroundColor: COLORS.primaryUltraLight }]}
          onPress={handleExport}>
          <Text style={[styles.exportBtnText, { color: COLORS.primaryDark }]}>{t.leads.export}</Text>
        </TouchableOpacity>
      </View>

      {isLoading ? (
        <Spinner centered label={t.common.loading} />
      ) : (
        <FlatList
          data={leads}
          keyExtractor={item => item.id}
          renderItem={renderItem}
          contentContainerStyle={styles.list}
          showsVerticalScrollIndicator={false}
          refreshControl={
            <RefreshControl refreshing={isLoading} onRefresh={refetch} tintColor={COLORS.primary} />
          }
          ListEmptyComponent={
            <EmptyState
              icon={<Text style={{ fontSize: 52 }}>👥</Text>}
              title={t.leads.empty_title}
              description={t.leads.empty_desc}
            />
          }
        />
      )}

      {/* Lead detail / edit modal */}
      {selectedLead && (
        <LeadDetailModal
          lead={selectedLead}
          theme={theme}
          saving={updateMutation.isPending}
          statusOptions={STATUS_OPTIONS}
          onClose={() => setSelectedLead(null)}
          onSave={(status, notes) =>
            updateMutation.mutate({ id: selectedLead.id, data: { status, notes } })
          }
        />
      )}
    </SafeAreaView>
  );
}

function LeadDetailModal({
  lead,
  theme,
  saving,
  statusOptions,
  onClose,
  onSave,
}: {
  lead: Lead;
  theme: any;
  saving: boolean;
  statusOptions: { key: LeadStatus; label: string; color: string }[];
  onClose: () => void;
  onSave: (status: string, notes: string) => void;
}) {
  const { t } = useTranslation();
  const [status, setStatus] = useState<LeadStatus>((lead as any).status ?? 'new');
  const [notes, setNotes] = useState<string>((lead as any).notes ?? '');

  return (
    <Modal visible animationType="slide" presentationStyle="pageSheet" onRequestClose={onClose}>
      <SafeAreaView style={[modalStyles.safe, { backgroundColor: theme.bg }]}>
        <View style={[modalStyles.header, { borderBottomColor: theme.border }]}>
          <TouchableOpacity onPress={onClose}>
            <Text style={{ color: COLORS.primary, fontSize: FONT_SIZE.md }}>{t.leads.cancel}</Text>
          </TouchableOpacity>
          <Text style={[modalStyles.title, { color: theme.text }]}>{t.leads.detail_title}</Text>
          <TouchableOpacity onPress={() => onSave(status, notes)} disabled={saving}>
            {saving
              ? <ActivityIndicator size="small" color={COLORS.primary} />
              : <Text style={{ color: COLORS.primary, fontSize: FONT_SIZE.md, fontWeight: '700' }}>{t.leads.save}</Text>}
          </TouchableOpacity>
        </View>

        <ScrollView contentContainerStyle={modalStyles.scroll}>
          {/* Info */}
          <View style={[modalStyles.section, { backgroundColor: theme.surface, borderColor: theme.border }]}>
            <Text style={[modalStyles.sectionTitle, { color: theme.text }]}>{t.leads.contact_info}</Text>
            {lead.name ? <InfoRow label={t.leads.field_name} value={lead.name} theme={theme} /> : null}
            {lead.email ? <InfoRow label={t.leads.field_email} value={lead.email} theme={theme} /> : null}
            {lead.phone ? <InfoRow label={t.leads.field_phone} value={lead.phone} theme={theme} /> : null}
            {lead.company ? <InfoRow label={t.leads.field_company} value={lead.company} theme={theme} /> : null}
            {lead.chatbot_name ? <InfoRow label={t.leads.field_chatbot} value={lead.chatbot_name} theme={theme} /> : null}
            {lead.created_at ? (
              <InfoRow label={t.leads.field_date} value={new Date(lead.created_at).toLocaleDateString()} theme={theme} />
            ) : null}
          </View>

          {/* Status */}
          <View style={[modalStyles.section, { backgroundColor: theme.surface, borderColor: theme.border }]}>
            <Text style={[modalStyles.sectionTitle, { color: theme.text }]}>{t.leads.status_section}</Text>
            <View style={modalStyles.statusGrid}>
              {statusOptions.map(opt => (
                <TouchableOpacity
                  key={opt.key}
                  style={[
                    modalStyles.statusPill,
                    { borderColor: status === opt.key ? opt.color : theme.border },
                    status === opt.key && { backgroundColor: opt.color + '18' },
                  ]}
                  onPress={() => setStatus(opt.key)}>
                  <Text style={[modalStyles.statusLabel, { color: status === opt.key ? opt.color : theme.textSecondary }]}>
                    {opt.label}
                  </Text>
                </TouchableOpacity>
              ))}
            </View>
          </View>

          {/* Notes */}
          <View style={[modalStyles.section, { backgroundColor: theme.surface, borderColor: theme.border }]}>
            <Text style={[modalStyles.sectionTitle, { color: theme.text }]}>{t.leads.notes_section}</Text>
            <TextInput
              style={[modalStyles.notesInput, { backgroundColor: theme.inputBg, borderColor: theme.border, color: theme.text }]}
              value={notes}
              onChangeText={setNotes}
              placeholder={t.leads.notes_placeholder}
              placeholderTextColor={theme.placeholder}
              multiline
              numberOfLines={5}
              textAlignVertical="top"
            />
          </View>
        </ScrollView>
      </SafeAreaView>
    </Modal>
  );
}

function InfoRow({ label, value, theme }: { label: string; value: string; theme: any }) {
  return (
    <View style={infoStyles.row}>
      <Text style={[infoStyles.label, { color: theme.textMuted }]}>{label}</Text>
      <Text style={[infoStyles.value, { color: theme.text }]} selectable>{value}</Text>
    </View>
  );
}

function LeadCard({ item, theme, onPress }: { item: Lead; theme: any; onPress: () => void }) {
  const { t } = useTranslation();
  const scale = useRef(new Animated.Value(1)).current;
  const onPressIn = () => Animated.spring(scale, { toValue: 0.98, useNativeDriver: true, speed: 60 }).start();
  const onPressOut = () => Animated.spring(scale, { toValue: 1, useNativeDriver: true, speed: 30, bounciness: 4 }).start();

  const initials = (item.name ?? item.email ?? '?')[0].toUpperCase();
  const colors = ['#6366f1', '#0ea5e9', '#10b981', '#f59e0b', '#ef4444'];
  const colorIdx = initials.charCodeAt(0) % colors.length;
  const avatarColor = colors[colorIdx];
  const itemStatus = (item as any).status as LeadStatus | undefined;
  const statusLabels: Record<LeadStatus, string> = {
    new: t.leads.status_new,
    contacted: t.leads.status_contacted,
    qualified: t.leads.status_qualified,
    closed: t.leads.status_closed,
    lost: t.leads.status_lost,
  };
  const statusColor = itemStatus ? STATUS_COLORS[itemStatus] : undefined;
  const statusLabel = itemStatus ? statusLabels[itemStatus] : undefined;

  return (
    <TouchableOpacity onPress={onPress} onPressIn={onPressIn} onPressOut={onPressOut} activeOpacity={1}>
      <Animated.View
        style={[
          styles.card,
          { backgroundColor: theme.surface, borderColor: theme.border, transform: [{ scale }] },
          SHADOWS.sm,
        ]}>
        <View style={styles.cardTop}>
          <View style={[styles.avatar, { backgroundColor: avatarColor }]}>
            <Text style={styles.avatarText}>{initials}</Text>
          </View>

          <View style={styles.info}>
            {item.name ? (
              <Text style={[styles.name, { color: theme.text }]}>{item.name}</Text>
            ) : null}
            {item.email ? (
              <Text style={[styles.email, { color: theme.textSecondary }]} selectable>{item.email}</Text>
            ) : null}
            {item.company ? (
              <Text style={[styles.company, { color: theme.textMuted }]}>{item.company}</Text>
            ) : null}
          </View>

          <View style={styles.rightCol}>
            {item.created_at ? (
              <Text style={[styles.date, { color: theme.textMuted }]}>
                {new Date(item.created_at).toLocaleDateString([], { month: 'short', day: 'numeric' })}
              </Text>
            ) : null}
            {statusColor && statusLabel && (
              <View style={[styles.statusBadge, { backgroundColor: statusColor + '22' }]}>
                <Text style={[styles.statusText, { color: statusColor }]}>{statusLabel}</Text>
              </View>
            )}
          </View>
        </View>

        {(item.phone || item.chatbot_name) && (
          <View style={styles.chips}>
            {item.phone ? (
              <MetaChip icon="📞" value={item.phone} theme={theme} />
            ) : null}
            {item.chatbot_name ? (
              <MetaChip icon="🤖" value={item.chatbot_name} theme={theme} />
            ) : null}
          </View>
        )}
      </Animated.View>
    </TouchableOpacity>
  );
}

function MetaChip({ icon, value, theme }: { icon: string; value: string; theme: any }) {
  return (
    <View style={[chipStyles.chip, { backgroundColor: theme.bgSecondary, borderColor: theme.border }]}>
      <Text style={chipStyles.icon}>{icon}</Text>
      <Text style={[chipStyles.value, { color: theme.textSecondary }]}>{value}</Text>
    </View>
  );
}

const chipStyles = StyleSheet.create({
  chip: {
    flexDirection: 'row',
    alignItems: 'center',
    borderRadius: RADIUS.full,
    borderWidth: 1,
    paddingVertical: 4,
    paddingHorizontal: SPACING.sm,
    gap: 4,
  },
  icon: { fontSize: 12 },
  value: { fontSize: FONT_SIZE.xs },
});

const infoStyles = StyleSheet.create({
  row: { flexDirection: 'row', paddingVertical: SPACING.xs, gap: SPACING.md },
  label: { width: 70, fontSize: FONT_SIZE.sm },
  value: { flex: 1, fontSize: FONT_SIZE.sm, fontWeight: '500' },
});

const modalStyles = StyleSheet.create({
  safe: { flex: 1 },
  header: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    padding: SPACING.lg,
    borderBottomWidth: 1,
  },
  title: { fontSize: FONT_SIZE.md, fontWeight: '700' },
  scroll: { padding: SPACING.lg, gap: SPACING.md, paddingBottom: SPACING.xxxl },
  section: {
    borderRadius: RADIUS.xl,
    borderWidth: 1,
    padding: SPACING.lg,
    gap: SPACING.sm,
  },
  sectionTitle: { fontSize: FONT_SIZE.md, fontWeight: '700', marginBottom: SPACING.xs },
  statusGrid: { flexDirection: 'row', flexWrap: 'wrap', gap: SPACING.sm },
  statusPill: {
    borderWidth: 1.5,
    borderRadius: RADIUS.full,
    paddingVertical: SPACING.xs,
    paddingHorizontal: SPACING.md,
  },
  statusLabel: { fontSize: FONT_SIZE.sm, fontWeight: '600' },
  notesInput: {
    borderWidth: 1.5,
    borderRadius: RADIUS.md,
    padding: SPACING.md,
    fontSize: FONT_SIZE.md,
    minHeight: 110,
  },
});

const styles = StyleSheet.create({
  safe: { flex: 1 },

  header: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    paddingHorizontal: SPACING.lg,
    paddingVertical: SPACING.md,
    borderBottomWidth: 1,
  },
  headerTitle: { ...TEXT.h3 },
  headerSub: { ...TEXT.small, marginTop: 2 },
  exportBtn: {
    borderRadius: RADIUS.full,
    paddingVertical: 7,
    paddingHorizontal: SPACING.md,
  },
  exportBtnText: { fontSize: FONT_SIZE.sm, fontWeight: '700' },

  list: { padding: SPACING.lg, gap: SPACING.md, flexGrow: 1, paddingBottom: SPACING.xxxl },

  card: {
    borderRadius: RADIUS.xl,
    borderWidth: 1,
    padding: SPACING.lg,
    gap: SPACING.md,
  },
  cardTop: { flexDirection: 'row', alignItems: 'flex-start', gap: SPACING.md },
  avatar: {
    width: 46,
    height: 46,
    borderRadius: RADIUS.full,
    alignItems: 'center',
    justifyContent: 'center',
    flexShrink: 0,
  },
  avatarText: { color: COLORS.white, fontSize: FONT_SIZE.md, fontWeight: '800' },
  info: { flex: 1 },
  name: { ...TEXT.bodyM },
  email: { ...TEXT.small, marginTop: 2 },
  company: { fontSize: FONT_SIZE.xs, marginTop: 2 },
  rightCol: { alignItems: 'flex-end', gap: 4 },
  date: { fontSize: FONT_SIZE.xs },
  statusBadge: { borderRadius: RADIUS.full, paddingVertical: 2, paddingHorizontal: SPACING.sm },
  statusText: { fontSize: FONT_SIZE.xs, fontWeight: '700' },
  chips: { flexDirection: 'row', gap: SPACING.sm, flexWrap: 'wrap' },
});
