import React from 'react';
import {
  View,
  Text,
  StyleSheet,
  ScrollView,
  TouchableOpacity,
} from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import { useQuery } from '@tanstack/react-query';
import { NativeStackScreenProps } from '@react-navigation/native-stack';
import { MarketplaceStackParamList } from '../../navigation/types';
import { COLORS, FONT_SIZE, SPACING, RADIUS } from '../../theme';
import { useTheme } from '../../theme';
import { Card, Badge, Spinner, Button } from '../../components/ui';
import { marketplaceAPI } from '../../services/api';

type Props = NativeStackScreenProps<MarketplaceStackParamList, 'MarketplaceDetail'>;

export function ChatbotDetailScreen({ route, navigation }: Props) {
  const { chatbotId } = route.params;
  const { theme } = useTheme();

  const { data: bot, isLoading } = useQuery({
    queryKey: ['marketplace-bot', chatbotId],
    queryFn: () => marketplaceAPI.get(chatbotId),
  });

  if (isLoading) return <Spinner centered />;
  if (!bot) return null;

  return (
    <SafeAreaView style={[styles.safe, { backgroundColor: theme.bg }]} edges={['bottom']}>
      <ScrollView contentContainerStyle={styles.scroll} showsVerticalScrollIndicator={false}>

        {/* Hero card */}
        <Card style={styles.hero}>
          <View style={[styles.heroAvatar, { backgroundColor: bot.primary_color || COLORS.primary }]}>
            <Text style={styles.heroAvatarText}>{bot.name[0]?.toUpperCase()}</Text>
          </View>
          <Text style={[styles.heroName, { color: theme.text }]}>{bot.name}</Text>
          {bot.company_name ? (
            <Text style={[styles.heroCompany, { color: theme.textSecondary }]}>by {bot.company_name}</Text>
          ) : null}

          <View style={styles.heroStats}>
            <StatItem icon="★" value={bot.average_rating?.toFixed(1) ?? '–'} label="Rating" />
            <StatItem icon="💬" value={String(bot.conversation_count ?? 0)} label="Chats" />
            {bot.category ? <StatItem icon="📌" value={bot.category} label="Category" /> : null}
          </View>

          <Button
            title="Start Chatting"
            onPress={() => navigation.navigate('PublicChat', { chatbotId: bot.id, chatbotName: bot.name })}
            fullWidth
            size="lg"
            style={styles.chatBtn}
          />
        </Card>

        {/* Description */}
        {bot.description ? (
          <Card style={styles.section}>
            <Text style={[styles.sectionTitle, { color: theme.text }]}>About</Text>
            <Text style={[styles.sectionText, { color: theme.textSecondary }]}>{bot.description}</Text>
          </Card>
        ) : null}

        {/* Details */}
        <Card style={styles.section}>
          <Text style={[styles.sectionTitle, { color: theme.text }]}>Details</Text>
          {bot.industry ? <DetailRow label="Industry" value={bot.industry} theme={theme} /> : null}
          {bot.category ? <DetailRow label="Category" value={bot.category} theme={theme} /> : null}
          {(bot.languages ?? []).length > 0 ? (
            <View style={styles.detailRow}>
              <Text style={[styles.detailLabel, { color: theme.textSecondary }]}>Languages</Text>
              <View style={styles.languagesRow}>
                {bot.languages.map((lang: string) => (
                  <Badge key={lang} label={lang} variant="info" />
                ))}
              </View>
            </View>
          ) : null}
        </Card>
      </ScrollView>
    </SafeAreaView>
  );
}

function StatItem({ icon, value, label }: { icon: string; value: string; label: string }) {
  const { theme } = useTheme();
  return (
    <View style={statStyles.item}>
      <Text style={statStyles.icon}>{icon}</Text>
      <Text style={[statStyles.value, { color: theme.text }]}>{value}</Text>
      <Text style={[statStyles.label, { color: theme.textMuted }]}>{label}</Text>
    </View>
  );
}

function DetailRow({ label, value, theme }: { label: string; value: string; theme: any }) {
  return (
    <View style={styles.detailRow}>
      <Text style={[styles.detailLabel, { color: theme.textSecondary }]}>{label}</Text>
      <Text style={[styles.detailValue, { color: theme.text }]}>{value}</Text>
    </View>
  );
}

const statStyles = StyleSheet.create({
  item: { alignItems: 'center', flex: 1, gap: 2 },
  icon: { fontSize: 20 },
  value: { fontSize: FONT_SIZE.md, fontWeight: '700' },
  label: { fontSize: FONT_SIZE.xs },
});

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

  hero: { alignItems: 'center', gap: SPACING.sm },
  heroAvatar: { width: 72, height: 72, borderRadius: RADIUS.xl, alignItems: 'center', justifyContent: 'center' },
  heroAvatarText: { color: '#fff', fontSize: 32, fontWeight: '700' },
  heroName: { fontSize: FONT_SIZE.xxl, fontWeight: '700', textAlign: 'center' },
  heroCompany: { fontSize: FONT_SIZE.sm },
  heroStats: { flexDirection: 'row', width: '100%', paddingVertical: SPACING.md },
  chatBtn: { marginTop: SPACING.sm },

  section: { gap: SPACING.md },
  sectionTitle: { fontSize: FONT_SIZE.lg, fontWeight: '600' },
  sectionText: { fontSize: FONT_SIZE.md, lineHeight: 22 },

  detailRow: { flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center', paddingVertical: SPACING.xs },
  detailLabel: { fontSize: FONT_SIZE.sm },
  detailValue: { fontSize: FONT_SIZE.sm, fontWeight: '500' },
  languagesRow: { flexDirection: 'row', gap: SPACING.xs, flexWrap: 'wrap' },
});
