import React, { useState } from 'react';
import {
  View,
  Text,
  StyleSheet,
  ScrollView,
  TouchableOpacity,
  Clipboard,
  Platform,
} from 'react-native';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { COLORS, FONT_SIZE, SPACING, RADIUS } from '../../../theme';
import { useTheme } from '../../../theme';
import { Card, Button, Input } from '../../../components/ui';
import { useToast } from '../../../contexts/ToastContext';
import { chatbotsAPI, channelsAPI } from '../../../services/api';
import { ChannelConnection } from '../../../types';

interface Props {
  chatbotId: string;
  chatbotName: string;
}

export function DeployTab({ chatbotId, chatbotName }: Props) {
  const { theme } = useTheme();
  const toast = useToast();
  const qc = useQueryClient();
  const [telegramToken, setTelegramToken] = useState('');
  const [connectingTelegram, setConnectingTelegram] = useState(false);
  const [showTelegramForm, setShowTelegramForm] = useState(false);

  const { data: embedData } = useQuery({
    queryKey: ['embed', chatbotId],
    queryFn: () => chatbotsAPI.getEmbed(chatbotId),
  });

  const { data: channels } = useQuery({
    queryKey: ['channels', chatbotId],
    queryFn: () => channelsAPI.list(chatbotId),
  });

  const disconnectMutation = useMutation({
    mutationFn: channelsAPI.disconnect,
    onSuccess: () => {
      qc.invalidateQueries({ queryKey: ['channels', chatbotId] });
      toast.success('Channel disconnected');
    },
  });

  const handleCopy = (text: string, label: string) => {
    Clipboard.setString(text);
    toast.success(`${label} copied!`);
  };

  const handleConnectTelegram = async () => {
    if (!telegramToken.trim()) {
      toast.error('Enter your Telegram bot token');
      return;
    }
    setConnectingTelegram(true);
    try {
      await channelsAPI.connectTelegram(chatbotId, telegramToken.trim());
      qc.invalidateQueries({ queryKey: ['channels', chatbotId] });
      setTelegramToken('');
      setShowTelegramForm(false);
      toast.success('Telegram bot connected!');
    } catch (err: any) {
      toast.error(err?.response?.data?.detail ?? 'Failed to connect Telegram');
    } finally {
      setConnectingTelegram(false);
    }
  };

  const telegramConnection = (channels as ChannelConnection[] ?? []).find(c => c.channel === 'telegram');
  const whatsappConnection = (channels as ChannelConnection[] ?? []).find(c => c.channel === 'whatsapp');

  return (
    <ScrollView
      style={[styles.scroll, { backgroundColor: theme.bg }]}
      contentContainerStyle={styles.content}
      showsVerticalScrollIndicator={false}>

      {/* Web Embed */}
      <Card style={styles.section}>
        <Text style={[styles.sectionTitle, { color: theme.text }]}>🌐 Web Embed</Text>
        <Text style={[styles.sectionDesc, { color: theme.textSecondary }]}>
          Paste this script on your website to add the chat widget.
        </Text>
        {embedData?.embed_script ? (
          <View style={[styles.codeBlock, { backgroundColor: theme.surfaceHover, borderColor: theme.border }]}>
            <Text style={[styles.codeText, { color: theme.textSecondary }]} numberOfLines={4}>
              {embedData.embed_script}
            </Text>
            <TouchableOpacity
              style={styles.copyBtn}
              onPress={() => handleCopy(embedData.embed_script, 'Embed script')}>
              <Text style={[styles.copyBtnText, { color: COLORS.primary }]}>Copy</Text>
            </TouchableOpacity>
          </View>
        ) : null}
        {embedData?.chat_url ? (
          <View style={styles.urlRow}>
            <Text style={[styles.urlLabel, { color: theme.textSecondary }]}>Direct link:</Text>
            <Text style={[styles.urlText, { color: COLORS.primary }]} numberOfLines={1} selectable>
              {embedData.chat_url}
            </Text>
            <TouchableOpacity onPress={() => handleCopy(embedData.chat_url, 'Chat URL')}>
              <Text style={[styles.copyBtnText, { color: COLORS.primary }]}>Copy</Text>
            </TouchableOpacity>
          </View>
        ) : null}
      </Card>

      {/* Telegram */}
      <Card style={styles.section}>
        <View style={styles.channelHeader}>
          <Text style={styles.channelIcon}>✈️</Text>
          <View style={styles.channelTitleCol}>
            <Text style={[styles.sectionTitle, { color: theme.text }]}>Telegram</Text>
            <Text style={[styles.sectionDesc, { color: theme.textSecondary }]}>
              Connect a Telegram bot to use your chatbot
            </Text>
          </View>
        </View>
        {telegramConnection ? (
          <View style={styles.connectedRow}>
            <View style={styles.connectedInfo}>
              <View style={styles.connectedDot} />
              <Text style={[styles.connectedText, { color: theme.text }]}>
                @{telegramConnection.bot_username ?? 'Connected'}
              </Text>
            </View>
            <Button
              title="Disconnect"
              variant="danger"
              size="sm"
              onPress={() => disconnectMutation.mutate(telegramConnection.id)}
            />
          </View>
        ) : (
          <>
            {showTelegramForm ? (
              <View style={styles.connectForm}>
                <Input
                  label="Bot Token"
                  value={telegramToken}
                  onChangeText={setTelegramToken}
                  placeholder="1234567890:ABC..."
                  autoCapitalize="none"
                />
                <View style={styles.formActions}>
                  <Button title="Cancel" variant="ghost" size="sm" onPress={() => setShowTelegramForm(false)} />
                  <Button title="Connect" size="sm" onPress={handleConnectTelegram} loading={connectingTelegram} />
                </View>
              </View>
            ) : (
              <Button title="Connect Telegram Bot" variant="outline" onPress={() => setShowTelegramForm(true)} />
            )}
          </>
        )}
      </Card>

      {/* WhatsApp */}
      <Card style={styles.section}>
        <View style={styles.channelHeader}>
          <Text style={styles.channelIcon}>💬</Text>
          <View style={styles.channelTitleCol}>
            <Text style={[styles.sectionTitle, { color: theme.text }]}>WhatsApp</Text>
            <Text style={[styles.sectionDesc, { color: theme.textSecondary }]}>
              Connect via Meta Cloud API (Business+ plan)
            </Text>
          </View>
        </View>
        {whatsappConnection ? (
          <View style={styles.connectedRow}>
            <View style={styles.connectedInfo}>
              <View style={styles.connectedDot} />
              <Text style={[styles.connectedText, { color: theme.text }]}>
                Keyword: {whatsappConnection.wa_keyword}
              </Text>
            </View>
            <Button
              title="Disconnect"
              variant="danger"
              size="sm"
              onPress={() => disconnectMutation.mutate(whatsappConnection.id)}
            />
          </View>
        ) : (
          <Text style={[styles.upgradeNote, { color: theme.textMuted }]}>
            Requires Business plan or higher
          </Text>
        )}
      </Card>
    </ScrollView>
  );
}

const styles = StyleSheet.create({
  scroll: { flex: 1 },
  content: { padding: SPACING.lg, gap: SPACING.lg },
  section: { gap: SPACING.md },
  sectionTitle: { fontSize: FONT_SIZE.lg, fontWeight: '600' },
  sectionDesc: { fontSize: FONT_SIZE.sm, lineHeight: 20 },

  codeBlock: {
    borderRadius: RADIUS.md,
    padding: SPACING.md,
    borderWidth: 1,
    gap: SPACING.sm,
  },
  codeText: { fontSize: 11, fontFamily: Platform.OS === 'ios' ? 'Menlo' : 'monospace' },
  copyBtn: { alignSelf: 'flex-end' },
  copyBtnText: { fontSize: FONT_SIZE.sm, fontWeight: '600' },

  urlRow: { flexDirection: 'row', alignItems: 'center', gap: SPACING.sm, flexWrap: 'wrap' },
  urlLabel: { fontSize: FONT_SIZE.sm },
  urlText: { flex: 1, fontSize: FONT_SIZE.sm },

  channelHeader: { flexDirection: 'row', gap: SPACING.md, alignItems: 'flex-start' },
  channelIcon: { fontSize: 28 },
  channelTitleCol: { flex: 1, gap: 2 },

  connectedRow: { flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center' },
  connectedInfo: { flexDirection: 'row', alignItems: 'center', gap: SPACING.sm },
  connectedDot: { width: 8, height: 8, borderRadius: 4, backgroundColor: COLORS.success },
  connectedText: { fontSize: FONT_SIZE.sm, fontWeight: '500' },

  connectForm: { gap: SPACING.sm },
  formActions: { flexDirection: 'row', gap: SPACING.sm, justifyContent: 'flex-end' },

  upgradeNote: { fontSize: FONT_SIZE.sm, fontStyle: 'italic' },
});

