import React, { useState } from 'react';
import {
  View,
  Text,
  StyleSheet,
  ScrollView,
  FlatList,
  TextInput,
  TouchableOpacity,
  Alert,
  RefreshControl,
  Modal,
} 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 { Button, Spinner, EmptyState } from '../../components/ui';
import { useToast } from '../../contexts/ToastContext';
import { campaignsAPI, chatbotsAPI } from '../../services/api';
import { useTranslation } from '../../i18n';
import type { Campaign, Chatbot } from '../../types';

const STATUS_COLORS: Record<string, { color: string; bg: string; emoji: string }> = {
  draft:   { color: '#6b7280', bg: '#f3f4f6', emoji: '📝' },
  sending: { color: '#2563eb', bg: '#dbeafe', emoji: '⏳' },
  sent:    { color: '#16a34a', bg: '#dcfce7', emoji: '✅' },
  failed:  { color: '#dc2626', bg: '#fee2e2', emoji: '❌' },
};

// ── New Campaign Modal ────────────────────────────────────────────────────────

function NewCampaignModal({
  visible,
  chatbots,
  onClose,
  onCreate,
  creating,
}: {
  visible: boolean;
  chatbots: Chatbot[];
  onClose: () => void;
  onCreate: (data: { chatbot_id: string; title: string; message: string }) => void;
  creating: boolean;
}) {
  const { theme } = useTheme();
  const { t } = useTranslation();
  const [chatbotIdx, setChatbotIdx] = useState(0);
  const [title, setTitle] = useState('');
  const [message, setMessage] = useState('');

  const handleCreate = () => {
    if (!title.trim() || !message.trim()) return;
    const chatbot_id = chatbots[chatbotIdx]?.id ?? '';
    if (!chatbot_id) return;
    onCreate({ chatbot_id, title: title.trim(), message: message.trim() });
    setTitle('');
    setMessage('');
    setChatbotIdx(0);
  };

  return (
    <Modal visible={visible} animationType="slide" presentationStyle="pageSheet" onRequestClose={onClose}>
      <SafeAreaView style={[styles.modalSafe, { backgroundColor: theme.bg }]}>
        <ScrollView contentContainerStyle={styles.modalScroll} keyboardShouldPersistTaps="handled">
          <View style={styles.modalHeader}>
            <Text style={[styles.modalTitle, { color: theme.text }]}>{t.campaigns.new}</Text>
            <TouchableOpacity onPress={onClose} style={[styles.closeBtn, { backgroundColor: theme.bgSecondary }]}>
              <Text style={[styles.closeBtnText, { color: theme.textSecondary }]}>✕</Text>
            </TouchableOpacity>
          </View>

          <Text style={[styles.fieldLabel, { color: theme.textSecondary }]}>{t.campaigns.select_chatbot}</Text>
          {chatbots.length === 0 ? (
            <Text style={[styles.hintText, { color: theme.textMuted }]}>
              {t.campaigns.empty_desc}
            </Text>
          ) : (
            <ScrollView horizontal showsHorizontalScrollIndicator={false} style={styles.chipRow}>
              {chatbots.map((c, idx) => (
                <TouchableOpacity
                  key={c.id}
                  onPress={() => setChatbotIdx(idx)}
                  style={[
                    styles.chip,
                    {
                      backgroundColor: idx === chatbotIdx ? COLORS.primary : theme.bgSecondary,
                      borderColor: idx === chatbotIdx ? COLORS.primary : theme.border,
                    },
                  ]}>
                  <Text style={[styles.chipText, { color: idx === chatbotIdx ? COLORS.white : theme.text }]}>
                    {c.name}
                  </Text>
                </TouchableOpacity>
              ))}
            </ScrollView>
          )}

          <Text style={[styles.fieldLabel, { color: theme.textSecondary }]}>{t.campaigns.campaign_name}</Text>
          <TextInput
            style={[styles.textInput, { backgroundColor: theme.surface, borderColor: theme.border, color: theme.text }]}
            placeholder={t.campaigns.name_placeholder}
            placeholderTextColor={theme.textMuted}
            value={title}
            onChangeText={setTitle}
          />

          <Text style={[styles.fieldLabel, { color: theme.textSecondary }]}>{t.campaigns.message_label}</Text>
          <TextInput
            style={[styles.textInput, styles.textArea, { backgroundColor: theme.surface, borderColor: theme.border, color: theme.text }]}
            placeholder={t.campaigns.message_placeholder}
            placeholderTextColor={theme.textMuted}
            value={message}
            onChangeText={setMessage}
            multiline
            numberOfLines={5}
            textAlignVertical="top"
          />
          <Text style={[styles.charCount, { color: theme.textMuted }]}>{message.length} characters</Text>

          <View style={styles.modalActions}>
            <Button title={t.campaigns.cancel} variant="outline" onPress={onClose} style={styles.modalActionBtn} />
            <Button
              title={t.campaigns.create}
              onPress={handleCreate}
              loading={creating}
              disabled={!title.trim() || !message.trim() || chatbots.length === 0}
              style={styles.modalActionBtn}
            />
          </View>
        </ScrollView>
      </SafeAreaView>
    </Modal>
  );
}

// ── Campaign Card ─────────────────────────────────────────────────────────────

function CampaignCard({
  campaign,
  chatbotName,
  onSend,
  onDelete,
  theme,
}: {
  campaign: Campaign;
  chatbotName: string;
  onSend: () => void;
  onDelete: () => void;
  theme: any;
}) {
  const { t } = useTranslation();
  const STATUS_LABELS: Record<string, string> = {
    draft: t.campaigns.status_draft,
    sending: t.campaigns.status_sending,
    sent: t.campaigns.status_sent,
    failed: t.campaigns.status_failed,
  };
  const sc = STATUS_COLORS[campaign.status] ?? STATUS_COLORS.draft;
  const statusLabel = STATUS_LABELS[campaign.status] ?? campaign.status;
  const createdAt = campaign.created_at ? new Date(campaign.created_at).toLocaleDateString() : '';
  const sentAt = campaign.sent_at ? new Date(campaign.sent_at).toLocaleDateString() : '';

  return (
    <View style={[styles.campaignCard, { backgroundColor: theme.surface, borderColor: theme.border }, SHADOWS.sm]}>
      <View style={styles.cardTopRow}>
        <Text style={[styles.campaignTitle, { color: theme.text }]} numberOfLines={1}>{campaign.title}</Text>
        <View style={[styles.statusBadge, { backgroundColor: sc.bg }]}>
          <Text style={[styles.statusText, { color: sc.color }]}>{sc.emoji} {statusLabel}</Text>
        </View>
      </View>

      <Text style={[styles.cardMeta, { color: theme.textMuted }]}>
        {chatbotName} · {createdAt}
      </Text>

      <View style={[styles.messageBox, { backgroundColor: theme.bgSecondary }]}>
        <Text style={[styles.messageText, { color: theme.textSecondary }]} numberOfLines={3}>
          {campaign.message}
        </Text>
      </View>

      <View style={styles.statsRow}>
        <Text style={[styles.statText, { color: theme.textMuted }]}>
          👥 {t.campaigns.subscribers(campaign.recipients_count)}
        </Text>
        {campaign.status === 'sent' && (
          <Text style={[styles.statText, { color: COLORS.success }]}>
            ✅ {campaign.sent_count} {t.campaigns.delivered} · {sentAt}
          </Text>
        )}
      </View>

      {campaign.status === 'draft' && (
        <View style={styles.actionRow}>
          <TouchableOpacity style={styles.sendBtn} onPress={onSend}>
            <Text style={styles.sendBtnText}>📤 {t.campaigns.send}</Text>
          </TouchableOpacity>
          <TouchableOpacity style={[styles.deleteBtn, { borderColor: COLORS.error + '40', backgroundColor: '#fee2e210' }]} onPress={onDelete}>
            <Text style={[styles.deleteBtnText, { color: COLORS.error }]}>🗑 {t.campaigns.delete}</Text>
          </TouchableOpacity>
        </View>
      )}

      {campaign.status === 'sent' && (
        <TouchableOpacity style={styles.deleteSentBtn} onPress={onDelete}>
          <Text style={[styles.deleteSentText, { color: theme.textMuted }]}>🗑 {t.campaigns.delete}</Text>
        </TouchableOpacity>
      )}
    </View>
  );
}

// ── Main Screen ───────────────────────────────────────────────────────────────

export function CampaignsScreen() {
  const { theme } = useTheme();
  const { t } = useTranslation();
  const toast = useToast();
  const qc = useQueryClient();
  const [showForm, setShowForm] = useState(false);
  const [chatbotFilter, setChatbotFilter] = useState('');

  const { data: chatbots = [] } = useQuery<Chatbot[]>({
    queryKey: ['chatbots'],
    queryFn: chatbotsAPI.list,
  });

  const { data: campaigns = [], isLoading, refetch, error } = useQuery<Campaign[]>({
    queryKey: ['campaigns', chatbotFilter],
    queryFn: () => campaignsAPI.list(chatbotFilter ? { chatbot_id: chatbotFilter } : undefined),
    retry: false,
    refetchInterval: 8000,
  });

  const createCampaign = useMutation({
    mutationFn: campaignsAPI.create,
    onSuccess: () => {
      setShowForm(false);
      qc.invalidateQueries({ queryKey: ['campaigns'] });
      toast.success(t.campaigns.create);
    },
    onError: (err: any) => toast.error(err?.response?.data?.detail ?? t.common.error),
  });

  const sendCampaign = useMutation({
    mutationFn: (id: string) => campaignsAPI.send(id),
    onSuccess: () => {
      qc.invalidateQueries({ queryKey: ['campaigns'] });
      toast.success(t.campaigns.send);
    },
    onError: (err: any) => toast.error(err?.response?.data?.detail ?? t.common.error),
  });

  const deleteCampaign = useMutation({
    mutationFn: (id: string) => campaignsAPI.delete(id),
    onSuccess: () => {
      qc.invalidateQueries({ queryKey: ['campaigns'] });
      toast.success(t.campaigns.delete);
    },
  });

  const isPlanError = (error as any)?.response?.status === 402;

  const chatbotMap = Object.fromEntries(chatbots.map(c => [c.id, c.name]));
  const sentCampaigns = campaigns.filter(c => c.status === 'sent');
  const totalDelivered = sentCampaigns.reduce((sum, c) => sum + c.sent_count, 0);

  const handleSend = (campaign: Campaign) => {
    Alert.alert(
      t.campaigns.send,
      t.campaigns.send_confirm(campaign.title, campaign.recipients_count),
      [
        { text: t.campaigns.cancel, style: 'cancel' },
        { text: t.campaigns.send_now, style: 'default', onPress: () => sendCampaign.mutate(campaign.id) },
      ],
    );
  };

  const handleDelete = (campaign: Campaign) => {
    Alert.alert(t.campaigns.delete, `"${campaign.title}"?`, [
      { text: t.campaigns.cancel, style: 'cancel' },
      { text: t.campaigns.delete, style: 'destructive', onPress: () => deleteCampaign.mutate(campaign.id) },
    ]);
  };

  if (isLoading) return <Spinner centered label={t.common.loading} />;

  if (isPlanError) {
    return (
      <SafeAreaView style={[styles.safe, { backgroundColor: theme.bg }]} edges={['bottom']}>
        <View style={styles.upgradeContainer}>
          <Text style={styles.upgradeEmoji}>🔒</Text>
          <Text style={[styles.upgradeTitle, { color: theme.text }]}>Campaigns Require Starter+</Text>
          <Text style={[styles.upgradeDesc, { color: theme.textSecondary }]}>
            Upgrade your plan to send broadcast messages to chatbot subscribers.
          </Text>
        </View>
      </SafeAreaView>
    );
  }

  return (
    <SafeAreaView style={[styles.safe, { backgroundColor: theme.bg }]} edges={['bottom']}>
      <ScrollView
        contentContainerStyle={styles.scroll}
        showsVerticalScrollIndicator={false}
        refreshControl={<RefreshControl refreshing={isLoading} onRefresh={refetch} tintColor={COLORS.primary} />}>

        {/* Header */}
        <View style={styles.headerRow}>
          <View>
            <Text style={[styles.pageTitle, { color: theme.text }]}>{t.campaigns.title}</Text>
            <Text style={[styles.pageSub, { color: theme.textSecondary }]}>
              {t.campaigns.empty_desc}
            </Text>
          </View>
          <Button title={t.campaigns.new} onPress={() => setShowForm(true)} size="sm" />
        </View>

        {/* Stats */}
        {campaigns.length > 0 && (
          <View style={styles.statsGrid}>
            {[
              { label: t.campaigns.title, value: campaigns.length, emoji: '📣' },
              { label: t.campaigns.status_sent, value: sentCampaigns.length, emoji: '✅' },
              { label: t.campaigns.delivered, value: totalDelivered, emoji: '📬' },
            ].map(s => (
              <View key={s.label} style={[styles.statCard, { backgroundColor: theme.surface, borderColor: theme.border }, SHADOWS.sm]}>
                <Text style={styles.statEmoji}>{s.emoji}</Text>
                <Text style={[styles.statValue, { color: theme.text }]}>{s.value.toLocaleString()}</Text>
                <Text style={[styles.statLabel, { color: theme.textMuted }]}>{s.label}</Text>
              </View>
            ))}
          </View>
        )}

        {/* Chatbot filter */}
        {chatbots.length > 1 && (
          <ScrollView horizontal showsHorizontalScrollIndicator={false} style={styles.filterRow}>
            {[{ id: '', name: 'All' }, ...chatbots].map(c => (
              <TouchableOpacity
                key={c.id}
                onPress={() => setChatbotFilter(c.id)}
                style={[
                  styles.filterChip,
                  {
                    backgroundColor: chatbotFilter === c.id ? COLORS.primary : theme.bgSecondary,
                    borderColor: chatbotFilter === c.id ? COLORS.primary : theme.border,
                  },
                ]}>
                <Text style={[styles.filterText, { color: chatbotFilter === c.id ? COLORS.white : theme.text }]}>
                  {c.name}
                </Text>
              </TouchableOpacity>
            ))}
          </ScrollView>
        )}

        {/* Campaign list */}
        {campaigns.length === 0 ? (
          <EmptyState
            icon={<Text style={{ fontSize: 48 }}>📣</Text>}
            title={t.campaigns.empty_title}
            description={t.campaigns.empty_desc}
          />
        ) : (
          <View style={styles.list}>
            {campaigns.map(campaign => (
              <CampaignCard
                key={campaign.id}
                campaign={campaign}
                chatbotName={chatbotMap[campaign.chatbot_id] ?? 'Unknown'}
                onSend={() => handleSend(campaign)}
                onDelete={() => handleDelete(campaign)}
                theme={theme}
              />
            ))}
          </View>
        )}
      </ScrollView>

      <NewCampaignModal
        visible={showForm}
        chatbots={chatbots}
        onClose={() => setShowForm(false)}
        onCreate={data => createCampaign.mutate(data)}
        creating={createCampaign.isPending}
      />
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  safe: { flex: 1 },
  scroll: { padding: SPACING.lg, gap: SPACING.lg, paddingBottom: SPACING.xxxl },

  headerRow: { flexDirection: 'row', alignItems: 'flex-start', justifyContent: 'space-between', gap: SPACING.md },
  pageTitle: { ...TEXT.h3 },
  pageSub: { ...TEXT.small, marginTop: 2 },

  statsGrid: { flexDirection: 'row', gap: SPACING.sm },
  statCard: {
    flex: 1,
    borderRadius: RADIUS.xl,
    borderWidth: 1,
    padding: SPACING.md,
    alignItems: 'center',
    gap: 4,
  },
  statEmoji: { fontSize: 20 },
  statValue: { fontSize: FONT_SIZE.xl, fontWeight: '800' },
  statLabel: { ...TEXT.caption },

  filterRow: { marginBottom: -SPACING.sm },
  filterChip: {
    paddingHorizontal: SPACING.md,
    paddingVertical: SPACING.xs,
    borderRadius: RADIUS.full,
    borderWidth: 1,
    marginRight: SPACING.xs,
  },
  filterText: { ...TEXT.small },

  list: { gap: SPACING.md },

  campaignCard: {
    borderRadius: RADIUS.xl,
    borderWidth: 1,
    padding: SPACING.lg,
    gap: SPACING.sm,
  },
  cardTopRow: { flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between', gap: SPACING.sm },
  campaignTitle: { ...TEXT.bodyM, flex: 1 },
  statusBadge: { borderRadius: RADIUS.full, paddingHorizontal: SPACING.sm, paddingVertical: 3 },
  statusText: { fontSize: FONT_SIZE.xs, fontWeight: '600' },
  cardMeta: { ...TEXT.caption },
  messageBox: { borderRadius: RADIUS.md, padding: SPACING.md },
  messageText: { ...TEXT.small },
  statsRow: { flexDirection: 'row', flexWrap: 'wrap', gap: SPACING.md },
  statText: { ...TEXT.caption },

  actionRow: { flexDirection: 'row', gap: SPACING.sm, marginTop: SPACING.xs },
  sendBtn: {
    flex: 1,
    backgroundColor: COLORS.success,
    borderRadius: RADIUS.md,
    paddingVertical: SPACING.sm,
    alignItems: 'center',
  },
  sendBtnText: { color: COLORS.white, fontWeight: '600', fontSize: FONT_SIZE.sm },
  deleteBtn: {
    borderWidth: 1,
    borderRadius: RADIUS.md,
    paddingVertical: SPACING.sm,
    paddingHorizontal: SPACING.md,
    alignItems: 'center',
  },
  deleteBtnText: { fontWeight: '600', fontSize: FONT_SIZE.sm },
  deleteSentBtn: { paddingVertical: SPACING.xs, alignSelf: 'flex-start' },
  deleteSentText: { ...TEXT.small },

  // Modal
  modalSafe: { flex: 1 },
  modalScroll: { padding: SPACING.xl, gap: SPACING.md, paddingBottom: SPACING.xxxl },
  modalHeader: { flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between', marginBottom: SPACING.sm },
  modalTitle: { ...TEXT.h3 },
  closeBtn: { width: 32, height: 32, borderRadius: RADIUS.full, alignItems: 'center', justifyContent: 'center' },
  closeBtnText: { fontSize: FONT_SIZE.sm, fontWeight: '600' },
  fieldLabel: { ...TEXT.smallM, marginBottom: -SPACING.xs },
  hintText: { ...TEXT.small },
  chipRow: { marginBottom: SPACING.xs },
  chip: {
    paddingHorizontal: SPACING.md,
    paddingVertical: SPACING.xs,
    borderRadius: RADIUS.full,
    borderWidth: 1,
    marginRight: SPACING.xs,
  },
  chipText: { ...TEXT.small },
  textInput: {
    borderWidth: 1,
    borderRadius: RADIUS.lg,
    paddingHorizontal: SPACING.md,
    paddingVertical: SPACING.sm,
    fontSize: FONT_SIZE.sm,
  },
  textArea: { height: 120, paddingTop: SPACING.sm },
  charCount: { ...TEXT.caption, textAlign: 'right', marginTop: -SPACING.xs },
  modalActions: { flexDirection: 'row', gap: SPACING.sm, marginTop: SPACING.sm },
  modalActionBtn: { flex: 1 },

  // Upgrade
  upgradeContainer: { flex: 1, alignItems: 'center', justifyContent: 'center', padding: SPACING.xxxl, gap: SPACING.md },
  upgradeEmoji: { fontSize: 48 },
  upgradeTitle: { ...TEXT.h3, textAlign: 'center' },
  upgradeDesc: { ...TEXT.body, textAlign: 'center' },
});
