import React, { useState, useEffect } from 'react';
import {
  View,
  Text,
  StyleSheet,
  ScrollView,
  TouchableOpacity,
  Switch,
  Alert,
  TextInput,
  ActivityIndicator,
  Modal,
  FlatList,
} from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { NativeStackScreenProps } from '@react-navigation/native-stack';
import { DashboardStackParamList } from '../../navigation/types';
import { COLORS, FONT_SIZE, SPACING, RADIUS } from '../../theme';
import { useTheme } from '../../theme';
import { Button, Input, Card, Spinner } from '../../components/ui';
import { useToast } from '../../contexts/ToastContext';
import { chatbotsAPI, modelsAPI, documentsAPI, urlSourcesAPI, channelsAPI } from '../../services/api';
import { Chatbot, Document, URLSource, AIModel, ChannelConnection } from '../../types';
import { DocumentsTab } from './tabs/DocumentsTab';
import { DeployTab } from './tabs/DeployTab';
import { TestingTab } from './tabs/TestingTab';
import { ChatInterface } from '../../components/ChatInterface';
import { CHATBOT_TEMPLATES, ChatbotTemplate } from '../../data/templates';

type Props = NativeStackScreenProps<DashboardStackParamList, 'ChatbotBuilder'>;

type Tab = 'settings' | 'documents' | 'preview' | 'testing' | 'deploy';

const TABS: { key: Tab; label: string }[] = [
  { key: 'settings', label: 'Settings' },
  { key: 'documents', label: 'Docs' },
  { key: 'preview', label: 'Preview' },
  { key: 'testing', label: 'Testing' },
  { key: 'deploy', label: 'Deploy' },
];

const CATEGORIES = ['Customer Support', 'Sales', 'HR', 'Education', 'Healthcare', 'Finance', 'Legal', 'Other'];
const INDUSTRIES = ['Technology', 'Retail', 'Healthcare', 'Finance', 'Education', 'Manufacturing', 'Other'];
const TEMPERATURES = [0, 0.3, 0.5, 0.7, 1.0];

export function ChatbotBuilderScreen({ route, navigation }: Props) {
  const { chatbotId } = route.params ?? {};
  const isEditing = Boolean(chatbotId);
  const { theme } = useTheme();
  const toast = useToast();
  const qc = useQueryClient();

  const [activeTab, setActiveTab] = useState<Tab>('settings');
  const [showTemplates, setShowTemplates] = useState(!isEditing);

  // Form state
  const [name, setName] = useState('');
  const [description, setDescription] = useState('');
  const [systemPrompt, setSystemPrompt] = useState('');
  const [selectedModel, setSelectedModel] = useState('');
  const [temperature, setTemperature] = useState(0.7);
  const [maxTokens, setMaxTokens] = useState(1024);
  const [primaryColor, setPrimaryColor] = useState('#6366f1');
  const [welcomeMessage, setWelcomeMessage] = useState('Hello! How can I help you today?');
  const [category, setCategory] = useState('');
  const [industry, setIndustry] = useState('');
  const [showBranding, setShowBranding] = useState(true);
  const [leadCaptureEnabled, setLeadCaptureEnabled] = useState(false);
  const [handoffEnabled, setHandoffEnabled] = useState(false);
  const [handoffEmail, setHandoffEmail] = useState('');
  const [errors, setErrors] = useState<Record<string, string>>({});

  // Load existing chatbot
  const { data: chatbot, isLoading: loadingBot } = useQuery({
    queryKey: ['chatbot', chatbotId],
    queryFn: () => chatbotsAPI.get(chatbotId!),
    enabled: isEditing,
  });

  // Load available models
  const { data: modelsData } = useQuery({
    queryKey: ['models'],
    queryFn: modelsAPI.available,
  });

  useEffect(() => {
    if (chatbot) {
      setName(chatbot.name ?? '');
      setDescription(chatbot.description ?? '');
      setSystemPrompt(chatbot.system_prompt ?? '');
      setSelectedModel(chatbot.model ?? '');
      setTemperature(chatbot.temperature ?? 0.7);
      setMaxTokens(chatbot.max_tokens ?? 1024);
      setPrimaryColor(chatbot.primary_color ?? '#6366f1');
      setWelcomeMessage(chatbot.welcome_message ?? '');
      setCategory(chatbot.category ?? '');
      setIndustry(chatbot.industry ?? '');
      setShowBranding(chatbot.show_branding ?? true);
      setLeadCaptureEnabled(chatbot.lead_capture_enabled ?? false);
      setHandoffEnabled(chatbot.handoff_enabled ?? false);
      setHandoffEmail(chatbot.handoff_email ?? '');
    } else if (!isEditing && modelsData?.default_model) {
      setSelectedModel(modelsData.default_model);
    }
  }, [chatbot, modelsData, isEditing]);

  const saveMutation = useMutation({
    mutationFn: (payload: Partial<Chatbot>) =>
      isEditing
        ? chatbotsAPI.update(chatbotId!, payload)
        : chatbotsAPI.create(payload),
    onSuccess: (data) => {
      qc.invalidateQueries({ queryKey: ['chatbots'] });
      qc.invalidateQueries({ queryKey: ['chatbot', chatbotId] });
      toast.success(isEditing ? 'Chatbot updated!' : 'Chatbot created!');
      if (!isEditing) {
        navigation.replace('ChatbotBuilder', { chatbotId: data.id });
      }
    },
    onError: (err: any) => toast.error(err?.response?.data?.detail ?? 'Save failed'),
  });

  const validate = () => {
    const e: Record<string, string> = {};
    if (!name.trim()) e.name = 'Name is required';
    setErrors(e);
    return Object.keys(e).length === 0;
  };

  const applyTemplate = (tpl: ChatbotTemplate) => {
    setSystemPrompt(tpl.system_prompt);
    setWelcomeMessage(tpl.welcome_message);
    setCategory(tpl.category);
    setLeadCaptureEnabled(tpl.lead_capture_enabled);
    setShowTemplates(false);
  };

  const handleSave = () => {
    if (!validate()) return;
    saveMutation.mutate({
      name: name.trim(),
      description: description.trim(),
      system_prompt: systemPrompt.trim(),
      model: selectedModel,
      temperature,
      max_tokens: maxTokens,
      primary_color: primaryColor,
      welcome_message: welcomeMessage.trim(),
      category,
      industry,
      show_branding: showBranding,
      lead_capture_enabled: leadCaptureEnabled,
      handoff_enabled: handoffEnabled,
      handoff_email: handoffEmail.trim(),
    });
  };

  if (isEditing && loadingBot) {
    return <Spinner centered label="Loading chatbot..." />;
  }

  const PRESET_COLORS = ['#6366f1', '#8b5cf6', '#ec4899', '#ef4444', '#f59e0b', '#10b981', '#3b82f6', '#14b8a6'];

  return (
    <SafeAreaView style={[styles.safe, { backgroundColor: theme.bg }]} edges={['bottom']}>
      {/* Template picker modal (only for new chatbots) */}
      <Modal
        visible={showTemplates}
        animationType="slide"
        presentationStyle="pageSheet"
        onRequestClose={() => setShowTemplates(false)}>
        <SafeAreaView style={[tplStyles.safe, { backgroundColor: theme.bg }]}>
          <View style={[tplStyles.header, { borderBottomColor: theme.border }]}>
            <Text style={[tplStyles.title, { color: theme.text }]}>Choose a template</Text>
            <TouchableOpacity onPress={() => setShowTemplates(false)}>
              <Text style={[tplStyles.skip, { color: COLORS.primary }]}>Start blank →</Text>
            </TouchableOpacity>
          </View>
          <FlatList
            data={CHATBOT_TEMPLATES}
            keyExtractor={item => item.id}
            contentContainerStyle={tplStyles.list}
            renderItem={({ item }) => (
              <TouchableOpacity
                style={[tplStyles.card, { backgroundColor: theme.surface, borderColor: theme.border }]}
                onPress={() => applyTemplate(item)}>
                <Text style={tplStyles.icon}>{item.icon}</Text>
                <View style={tplStyles.cardInfo}>
                  <Text style={[tplStyles.cardName, { color: theme.text }]}>{item.name}</Text>
                  <Text style={[tplStyles.cardDesc, { color: theme.textSecondary }]}>{item.description}</Text>
                </View>
                <Text style={[tplStyles.chevron, { color: theme.textMuted }]}>›</Text>
              </TouchableOpacity>
            )}
          />
        </SafeAreaView>
      </Modal>

      {/* Tab bar */}
      <View style={[styles.tabBar, { backgroundColor: theme.surface, borderBottomColor: theme.border }]}>
        {TABS.map(tab => (
          <TouchableOpacity
            key={tab.key}
            style={[styles.tab, activeTab === tab.key && styles.tabActive]}
            onPress={() => setActiveTab(tab.key)}>
            <Text style={[
              styles.tabText,
              { color: activeTab === tab.key ? COLORS.primary : theme.textSecondary },
              activeTab === tab.key && styles.tabTextActive,
            ]}>
              {tab.label}
            </Text>
          </TouchableOpacity>
        ))}
      </View>

      {/* Settings Tab */}
      {activeTab === 'settings' && (
        <ScrollView
          style={styles.scroll}
          contentContainerStyle={styles.scrollContent}
          keyboardShouldPersistTaps="handled"
          showsVerticalScrollIndicator={false}>

          <SectionHeader title="Basic Info" />
          <Input
            label="Chatbot Name *"
            value={name}
            onChangeText={setName}
            placeholder="My Support Bot"
            error={errors.name}
          />
          <Input
            label="Description"
            value={description}
            onChangeText={setDescription}
            placeholder="What does this chatbot do?"
            multiline
            numberOfLines={3}
          />

          <SectionHeader title="Behavior" />
          <View style={styles.field}>
            <Text style={[styles.label, { color: theme.text }]}>System Prompt</Text>
            <TextInput
              style={[styles.textarea, { backgroundColor: theme.inputBg, borderColor: theme.border, color: theme.text }]}
              value={systemPrompt}
              onChangeText={setSystemPrompt}
              placeholder="You are a helpful assistant..."
              placeholderTextColor={theme.placeholder}
              multiline
              numberOfLines={5}
              textAlignVertical="top"
            />
          </View>

          <SectionHeader title="AI Model" />
          <ScrollView horizontal showsHorizontalScrollIndicator={false} style={styles.modelsScroll}>
            <View style={styles.modelsRow}>
              {(modelsData?.models ?? []).map((m: AIModel) => (
                <TouchableOpacity
                  key={m.id}
                  style={[
                    styles.modelPill,
                    { borderColor: selectedModel === m.id ? COLORS.primary : theme.border },
                    selectedModel === m.id && { backgroundColor: COLORS.primaryUltraLight },
                    !m.available && styles.modelDisabled,
                  ]}
                  onPress={() => m.available && setSelectedModel(m.id)}
                  disabled={!m.available}>
                  <Text style={[
                    styles.modelPillText,
                    { color: selectedModel === m.id ? COLORS.primaryDark : theme.text },
                    !m.available && { color: theme.textMuted },
                  ]}>
                    {m.name}
                  </Text>
                  {m.upgrade_required ? (
                    <Text style={styles.modelUpgrade}>{m.upgrade_required}</Text>
                  ) : null}
                </TouchableOpacity>
              ))}
            </View>
          </ScrollView>

          <SectionHeader title="Temperature" />
          <View style={styles.tempRow}>
            {TEMPERATURES.map(t => (
              <TouchableOpacity
                key={t}
                style={[
                  styles.tempPill,
                  { borderColor: temperature === t ? COLORS.primary : theme.border },
                  temperature === t && { backgroundColor: COLORS.primaryUltraLight },
                ]}
                onPress={() => setTemperature(t)}>
                <Text style={[styles.tempText, { color: temperature === t ? COLORS.primaryDark : theme.text }]}>
                  {t}
                </Text>
              </TouchableOpacity>
            ))}
          </View>
          <Text style={[styles.hint, { color: theme.textMuted }]}>
            0 = focused, 1 = creative
          </Text>

          <SectionHeader title="Appearance" />
          <Text style={[styles.label, { color: theme.text }]}>Primary Color</Text>
          <View style={styles.colorRow}>
            {PRESET_COLORS.map(c => (
              <TouchableOpacity
                key={c}
                style={[styles.colorSwatch, { backgroundColor: c }, primaryColor === c && styles.colorSwatchSelected]}
                onPress={() => setPrimaryColor(c)}
              />
            ))}
          </View>

          <Input
            label="Welcome Message"
            value={welcomeMessage}
            onChangeText={setWelcomeMessage}
            placeholder="Hello! How can I help you today?"
          />

          <SectionHeader title="Classification" />
          <View style={styles.row}>
            <View style={{ flex: 1 }}>
              <Text style={[styles.label, { color: theme.text }]}>Category</Text>
              <ScrollView horizontal showsHorizontalScrollIndicator={false}>
                <View style={styles.pillRow}>
                  {CATEGORIES.map(c => (
                    <TouchableOpacity
                      key={c}
                      style={[styles.pill, { borderColor: category === c ? COLORS.primary : theme.border }, category === c && { backgroundColor: COLORS.primaryUltraLight }]}
                      onPress={() => setCategory(c === category ? '' : c)}>
                      <Text style={[styles.pillText, { color: category === c ? COLORS.primaryDark : theme.text }]}>
                        {c}
                      </Text>
                    </TouchableOpacity>
                  ))}
                </View>
              </ScrollView>
            </View>
          </View>

          <SectionHeader title="Advanced" />
          <ToggleRow
            label="Show Branding"
            description="Display 'Powered by Contexta' in the chat widget"
            value={showBranding}
            onValueChange={setShowBranding}
          />
          <ToggleRow
            label="Lead Capture"
            description="Collect visitor contact info during chats"
            value={leadCaptureEnabled}
            onValueChange={setLeadCaptureEnabled}
          />
          <ToggleRow
            label="Human Handoff"
            description="Escalate conversations to a human agent"
            value={handoffEnabled}
            onValueChange={setHandoffEnabled}
          />
          {handoffEnabled && (
            <Input
              label="Handoff Email"
              value={handoffEmail}
              onChangeText={setHandoffEmail}
              placeholder="agent@yourcompany.com"
              keyboardType="email-address"
              autoCapitalize="none"
            />
          )}

          <Button
            title={saveMutation.isPending ? 'Saving...' : (isEditing ? 'Save Changes' : 'Create Chatbot')}
            onPress={handleSave}
            loading={saveMutation.isPending}
            fullWidth
            size="lg"
            style={styles.saveBtn}
          />
        </ScrollView>
      )}

      {/* Documents Tab */}
      {activeTab === 'documents' && chatbotId && (
        <DocumentsTab chatbotId={chatbotId} />
      )}
      {activeTab === 'documents' && !chatbotId && (
        <View style={styles.noIdState}>
          <Text style={[styles.noIdText, { color: theme.textSecondary }]}>
            Save the chatbot first to add documents.
          </Text>
        </View>
      )}

      {/* Testing Tab */}
      {activeTab === 'testing' && chatbotId && (
        <TestingTab chatbotId={chatbotId} />
      )}
      {activeTab === 'testing' && !chatbotId && (
        <View style={styles.noIdState}>
          <Text style={[styles.noIdText, { color: theme.textSecondary }]}>
            Save the chatbot first to run tests.
          </Text>
        </View>
      )}

      {/* Preview Tab */}
      {activeTab === 'preview' && chatbotId && (
        <ChatInterface
          chatbotId={chatbotId}
          welcomeMessage={welcomeMessage}
          primaryColor={primaryColor}
        />
      )}
      {activeTab === 'preview' && !chatbotId && (
        <View style={styles.noIdState}>
          <Text style={[styles.noIdText, { color: theme.textSecondary }]}>
            Save the chatbot first to preview it.
          </Text>
        </View>
      )}

      {/* Deploy Tab */}
      {activeTab === 'deploy' && chatbotId && (
        <DeployTab chatbotId={chatbotId} chatbotName={name} />
      )}
      {activeTab === 'deploy' && !chatbotId && (
        <View style={styles.noIdState}>
          <Text style={[styles.noIdText, { color: theme.textSecondary }]}>
            Save the chatbot first to view deploy options.
          </Text>
        </View>
      )}
    </SafeAreaView>
  );
}

function SectionHeader({ title }: { title: string }) {
  const { theme } = useTheme();
  return (
    <Text style={[sectionStyles.header, { color: theme.textMuted }]}>{title.toUpperCase()}</Text>
  );
}

function ToggleRow({
  label,
  description,
  value,
  onValueChange,
}: {
  label: string;
  description: string;
  value: boolean;
  onValueChange: (v: boolean) => void;
}) {
  const { theme } = useTheme();
  return (
    <View style={toggleStyles.row}>
      <View style={toggleStyles.labelCol}>
        <Text style={[toggleStyles.label, { color: theme.text }]}>{label}</Text>
        <Text style={[toggleStyles.desc, { color: theme.textMuted }]}>{description}</Text>
      </View>
      <Switch
        value={value}
        onValueChange={onValueChange}
        trackColor={{ true: COLORS.primary, false: '#ccc' }}
        thumbColor="#fff"
      />
    </View>
  );
}

const sectionStyles = StyleSheet.create({
  header: {
    fontSize: FONT_SIZE.xs,
    fontWeight: '700',
    letterSpacing: 0.8,
    marginTop: SPACING.xl,
    marginBottom: SPACING.sm,
  },
});

const toggleStyles = StyleSheet.create({
  row: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    paddingVertical: SPACING.sm,
    gap: SPACING.md,
  },
  labelCol: { flex: 1 },
  label: { fontSize: FONT_SIZE.md, fontWeight: '500' },
  desc: { fontSize: FONT_SIZE.xs, marginTop: 2 },
});

const styles = StyleSheet.create({
  safe: { flex: 1 },
  tabBar: {
    flexDirection: 'row',
    borderBottomWidth: 1,
    paddingHorizontal: SPACING.sm,
  },
  tab: {
    flex: 1,
    paddingVertical: SPACING.md,
    alignItems: 'center',
    borderBottomWidth: 2,
    borderBottomColor: 'transparent',
  },
  tabActive: { borderBottomColor: COLORS.primary },
  tabText: { fontSize: FONT_SIZE.sm, fontWeight: '500' },
  tabTextActive: { fontWeight: '700' },

  scroll: { flex: 1 },
  scrollContent: { padding: SPACING.lg, paddingBottom: SPACING.xxxl },

  field: { marginBottom: SPACING.md },
  label: { fontSize: FONT_SIZE.sm, fontWeight: '500', marginBottom: SPACING.xs },
  textarea: {
    borderWidth: 1.5,
    borderRadius: RADIUS.md,
    padding: SPACING.md,
    fontSize: FONT_SIZE.md,
    minHeight: 110,
  },
  hint: { fontSize: FONT_SIZE.xs, marginTop: -SPACING.xs, marginBottom: SPACING.sm },

  modelsScroll: { marginBottom: SPACING.md },
  modelsRow: { flexDirection: 'row', gap: SPACING.sm, paddingBottom: SPACING.xs },
  modelPill: {
    borderWidth: 1.5,
    borderRadius: RADIUS.full,
    paddingVertical: SPACING.xs,
    paddingHorizontal: SPACING.md,
    gap: 2,
  },
  modelPillText: { fontSize: FONT_SIZE.sm, fontWeight: '500' },
  modelDisabled: { opacity: 0.4 },
  modelUpgrade: { fontSize: 9, color: COLORS.warning, fontWeight: '600' },

  tempRow: { flexDirection: 'row', gap: SPACING.sm, flexWrap: 'wrap', marginBottom: SPACING.xs },
  tempPill: {
    borderWidth: 1.5,
    borderRadius: RADIUS.full,
    paddingVertical: SPACING.xs,
    paddingHorizontal: SPACING.lg,
  },
  tempText: { fontSize: FONT_SIZE.sm, fontWeight: '600' },

  colorRow: { flexDirection: 'row', gap: SPACING.sm, marginBottom: SPACING.lg },
  colorSwatch: { width: 32, height: 32, borderRadius: RADIUS.full },
  colorSwatchSelected: { borderWidth: 3, borderColor: '#fff', shadowColor: '#000', shadowOffset: { width: 0, height: 2 }, shadowOpacity: 0.3, shadowRadius: 4, elevation: 4 },

  pillRow: { flexDirection: 'row', gap: SPACING.sm },
  pill: {
    borderWidth: 1.5,
    borderRadius: RADIUS.full,
    paddingVertical: 4,
    paddingHorizontal: SPACING.md,
  },
  pillText: { fontSize: FONT_SIZE.xs, fontWeight: '500' },

  row: { marginBottom: SPACING.md },

  saveBtn: { marginTop: SPACING.xxxl },

  noIdState: { flex: 1, justifyContent: 'center', alignItems: 'center', padding: SPACING.xxxl },
  noIdText: { fontSize: FONT_SIZE.md, textAlign: 'center' },
});

const tplStyles = StyleSheet.create({
  safe: { flex: 1 },
  header: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    padding: SPACING.lg,
    borderBottomWidth: 1,
  },
  title: { fontSize: FONT_SIZE.lg, fontWeight: '700' },
  skip: { fontSize: FONT_SIZE.sm, fontWeight: '600' },
  list: { padding: SPACING.lg, gap: SPACING.sm },
  card: {
    flexDirection: 'row',
    alignItems: 'center',
    gap: SPACING.md,
    padding: SPACING.lg,
    borderRadius: RADIUS.xl,
    borderWidth: 1,
  },
  icon: { fontSize: 32 },
  cardInfo: { flex: 1 },
  cardName: { fontSize: FONT_SIZE.md, fontWeight: '700' },
  cardDesc: { fontSize: FONT_SIZE.sm, marginTop: 2, lineHeight: 18 },
  chevron: { fontSize: 22, fontWeight: '300' },
});
