import React, { useCallback, useRef, useState, useEffect } from 'react';
import {
  View,
  Text,
  StyleSheet,
  FlatList,
  TouchableOpacity,
  Alert,
  RefreshControl,
  Animated,
} from 'react-native';
import AsyncStorage from '@react-native-async-storage/async-storage';
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, TEXT, SHADOWS } from '../../theme';
import { useTheme } from '../../theme';
import { PlanBadge, Spinner, EmptyState, Button } from '../../components/ui';
import { useToast } from '../../contexts/ToastContext';
import { chatbotsAPI } from '../../services/api';
import { useAuthStore } from '../../stores/authStore';
import { useTranslation } from '../../i18n';
import { Chatbot } from '../../types';

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

function OnboardingChecklist({
  chatbots,
  userId,
  onNavigateCreate,
}: {
  chatbots: Chatbot[];
  userId: string;
  onNavigateCreate: () => void;
}) {
  const { theme } = useTheme();
  const { t } = useTranslation();
  const storageKey = `onboarding_v1_${userId}`;
  const [dismissed, setDismissed] = useState(false);
  const [loaded, setLoaded] = useState(false);

  useEffect(() => {
    AsyncStorage.getItem(storageKey).then(val => {
      if (val === 'dismissed') setDismissed(true);
      setLoaded(true);
    });
  }, [storageKey]);

  const dismiss = async () => {
    setDismissed(true);
    await AsyncStorage.setItem(storageKey, 'dismissed');
  };

  if (!loaded || dismissed) return null;

  const steps = [
    {
      id: 'create',
      label: t.onboarding.step_create,
      done: chatbots.length > 0,
      action: onNavigateCreate,
    },
    {
      id: 'docs',
      label: t.onboarding.step_docs,
      done: chatbots.some(c => (c.document_count ?? 0) > 0),
      action: chatbots[0]
        ? () => {}
        : onNavigateCreate,
    },
    {
      id: 'publish',
      label: t.onboarding.step_publish,
      done: chatbots.some(c => c.is_published),
      action: undefined,
    },
  ];

  const completedCount = steps.filter(s => s.done).length;
  const allDone = completedCount === steps.length;

  if (allDone) {
    dismiss();
    return null;
  }

  const progress = (completedCount / steps.length) * 100;

  return (
    <View style={[onboardStyles.card, { backgroundColor: theme.surface, borderColor: theme.border }]}>
      <View style={onboardStyles.cardHeader}>
        <Text style={[onboardStyles.title, { color: theme.text }]}>
          🚀 {t.onboarding.title}
        </Text>
        <View style={[onboardStyles.progressLabel, { backgroundColor: COLORS.primaryUltraLight }]}>
          <Text style={[onboardStyles.progressLabelText, { color: COLORS.primaryDark }]}>
            {completedCount}/{steps.length}
          </Text>
        </View>
        <TouchableOpacity onPress={dismiss} hitSlop={{ top: 8, bottom: 8, left: 8, right: 8 }}>
          <Text style={[onboardStyles.dismiss, { color: theme.textMuted }]}>✕</Text>
        </TouchableOpacity>
      </View>

      <View style={[onboardStyles.bar, { backgroundColor: theme.bgSecondary }]}>
        <View style={[onboardStyles.barFill, { width: `${progress}%` as any }]} />
      </View>

      {steps.map((step, i) => (
        <View key={step.id} style={onboardStyles.step}>
          <View style={[
            onboardStyles.stepDot,
            { borderColor: step.done ? COLORS.success : theme.border },
            step.done && { backgroundColor: COLORS.success },
          ]}>
            {step.done && <Text style={onboardStyles.checkmark}>✓</Text>}
            {!step.done && (
              <Text style={[onboardStyles.stepNum, { color: theme.textMuted }]}>{i + 1}</Text>
            )}
          </View>
          <Text style={[
            onboardStyles.stepLabel,
            { color: step.done ? theme.textMuted : theme.text },
            step.done && onboardStyles.stepLabelDone,
          ]}>{step.label}</Text>
        </View>
      ))}
    </View>
  );
}

export function DashboardScreen({ navigation }: Props) {
  const { theme, isDark } = useTheme();
  const { t } = useTranslation();
  const toast = useToast();
  const user = useAuthStore(s => s.user);
  const qc = useQueryClient();

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

  const publishMutation = useMutation({
    mutationFn: ({ id, published }: { id: string; published: boolean }) =>
      published ? chatbotsAPI.unpublish(id) : chatbotsAPI.publish(id),
    onSuccess: () => qc.invalidateQueries({ queryKey: ['chatbots'] }),
    onError: (err: any) => toast.error(err?.response?.data?.detail ?? 'Action failed'),
  });

  const deleteMutation = useMutation({
    mutationFn: chatbotsAPI.delete,
    onSuccess: () => { qc.invalidateQueries({ queryKey: ['chatbots'] }); toast.success(t.dashboard.delete_title); },
    onError: (err: any) => toast.error(err?.response?.data?.detail ?? t.common.error),
  });

  const handleDelete = useCallback((bot: Chatbot) => {
    Alert.alert(
      t.dashboard.delete_title,
      t.dashboard.delete_confirm(bot.name),
      [
        { text: t.common.cancel, style: 'cancel' },
        { text: t.common.delete, style: 'destructive', onPress: () => deleteMutation.mutate(bot.id) },
      ],
    );
  }, [deleteMutation]);

  const renderItem = ({ item, index }: { item: Chatbot; index: number }) => (
    <ChatbotCard
      bot={item}
      index={index}
      onEdit={() => navigation.navigate('ChatbotBuilder', { chatbotId: item.id })}
      onPreview={() => navigation.navigate('ChatPreview', { chatbotId: item.id, chatbotName: item.name })}
      onTogglePublish={() => publishMutation.mutate({ id: item.id, published: item.is_published })}
      onDelete={() => handleDelete(item)}
      publishLoading={publishMutation.isPending}
    />
  );

  return (
    <SafeAreaView style={[styles.safe, { backgroundColor: theme.bg }]} edges={['top', 'bottom']}>
      {/* Header */}
      <View style={[styles.header, { borderBottomColor: theme.border }]}>
        <View style={styles.headerLeft}>
          <Text style={[styles.headerTitle, { color: theme.text }]}>{t.dashboard.title}</Text>
          <View style={styles.headerMeta}>
            <Text style={[styles.headerSub, { color: theme.textSecondary }]}>{user?.company_name}</Text>
            <PlanBadge plan={user?.plan ?? 'free'} />
          </View>
        </View>
        <Button title={t.dashboard.new} size="sm" onPress={() => navigation.navigate('ChatbotBuilder', {})} />
      </View>

      {isLoading ? (
        <Spinner centered label={t.common.loading} />
      ) : (
        <FlatList
          data={chatbots ?? []}
          keyExtractor={item => item.id}
          renderItem={renderItem}
          contentContainerStyle={styles.list}
          showsVerticalScrollIndicator={false}
          ListHeaderComponent={
            user ? (
              <OnboardingChecklist
                chatbots={chatbots ?? []}
                userId={user.id}
                onNavigateCreate={() => navigation.navigate('ChatbotBuilder', {})}
              />
            ) : null
          }
          refreshControl={
            <RefreshControl refreshing={isLoading} onRefresh={refetch} tintColor={COLORS.primary} />
          }
          ListEmptyComponent={
            <EmptyState
              icon={<Text style={{ fontSize: 52 }}>🤖</Text>}
              title={t.dashboard.empty_title}
              description={t.dashboard.empty_desc}
              action={{ label: t.dashboard.create_first, onPress: () => navigation.navigate('ChatbotBuilder', {}) }}
            />
          }
        />
      )}
    </SafeAreaView>
  );
}

function ChatbotCard({
  bot, index, onEdit, onPreview, onTogglePublish, onDelete, publishLoading,
}: {
  bot: Chatbot;
  index: number;
  onEdit: () => void;
  onPreview: () => void;
  onTogglePublish: () => void;
  onDelete: () => void;
  publishLoading: boolean;
}) {
  const { theme } = useTheme();
  const { t } = useTranslation();
  const scale = useRef(new Animated.Value(1)).current;
  const accentColor = bot.primary_color || COLORS.primary;

  return (
    <Animated.View style={[styles.card, { backgroundColor: theme.surface, borderColor: theme.border, transform: [{ scale }] }, SHADOWS.sm]}>
      {/* Accent strip */}
      <View style={[styles.accentStrip, { backgroundColor: accentColor }]} />

      <View style={styles.cardBody}>
        {/* Top row */}
        <View style={styles.cardTop}>
          <View style={[styles.botAvatar, { backgroundColor: accentColor + '22' }]}>
            <Text style={[styles.botAvatarText, { color: accentColor }]}>
              {bot.name[0]?.toUpperCase()}
            </Text>
          </View>
          <View style={styles.botInfo}>
            <Text style={[styles.botName, { color: theme.text }]} numberOfLines={1}>{bot.name}</Text>
            {bot.description ? (
              <Text style={[styles.botDesc, { color: theme.textSecondary }]} numberOfLines={1}>
                {bot.description}
              </Text>
            ) : null}
          </View>
          <View style={[styles.statusDot, { backgroundColor: bot.is_published ? COLORS.success : theme.border }]} />
        </View>

        {/* Stats row */}
        <View style={styles.statsRow}>
          <Stat icon="📄" value={bot.document_count ?? 0} label={t.dashboard.docs} theme={theme} />
          <Stat icon="💬" value={bot.conversation_count ?? 0} label={t.dashboard.chats} theme={theme} />
          {bot.model ? (
            <View style={[styles.modelPill, { backgroundColor: theme.bgSecondary }]}>
              <Text style={[styles.modelText, { color: theme.textMuted }]} numberOfLines={1}>
                {bot.model.split('/').pop() ?? bot.model}
              </Text>
            </View>
          ) : null}
        </View>

        {/* Actions */}
        <View style={styles.actions}>
          <Button title={t.dashboard.edit} variant="outline" size="sm" onPress={onEdit} style={styles.actionBtn} />
          <Button title={t.dashboard.preview} variant="secondary" size="sm" onPress={onPreview} style={styles.actionBtn} />
          <Button
            title={bot.is_published ? t.dashboard.unpublish : t.dashboard.publish}
            variant={bot.is_published ? 'ghost' : 'primary'}
            size="sm"
            loading={publishLoading}
            onPress={onTogglePublish}
            style={styles.actionBtn}
          />
          <TouchableOpacity
            onPress={onDelete}
            style={styles.deleteBtn}
            hitSlop={{ top: 8, bottom: 8, left: 8, right: 8 }}>
            <Text style={styles.deleteIcon}>🗑</Text>
          </TouchableOpacity>
        </View>
      </View>
    </Animated.View>
  );
}

function Stat({ icon, value, label, theme }: { icon: string; value: number; label: string; theme: any }) {
  return (
    <View style={[statStyles.chip, { backgroundColor: theme.bgSecondary }]}>
      <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>
  );
}

const statStyles = StyleSheet.create({
  chip: { flexDirection: 'row', alignItems: 'center', borderRadius: RADIUS.sm, paddingVertical: 5, paddingHorizontal: SPACING.sm, gap: 3 },
  icon: { fontSize: 12 },
  value: { ...TEXT.smallM },
  label: { ...TEXT.caption },
});

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

  header: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    paddingHorizontal: SPACING.lg,
    paddingVertical: SPACING.md,
    borderBottomWidth: 1,
  },
  headerLeft: { flex: 1, marginRight: SPACING.md },
  headerTitle: { ...TEXT.h3 },
  headerMeta: { flexDirection: 'row', alignItems: 'center', gap: SPACING.sm, marginTop: 3 },
  headerSub: { ...TEXT.small },

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

  card: {
    borderRadius: RADIUS.xl,
    borderWidth: 1,
    overflow: 'hidden',
    flexDirection: 'row',
  },
  accentStrip: { width: 4 },
  cardBody: { flex: 1, padding: SPACING.lg, gap: SPACING.md },

  cardTop: { flexDirection: 'row', alignItems: 'center', gap: SPACING.md },
  botAvatar: { width: 42, height: 42, borderRadius: RADIUS.md, alignItems: 'center', justifyContent: 'center' },
  botAvatarText: { fontSize: FONT_SIZE.lg, fontWeight: '700' },
  botInfo: { flex: 1 },
  botName: { ...TEXT.h4 },
  botDesc: { ...TEXT.small, marginTop: 2 },
  statusDot: { width: 9, height: 9, borderRadius: RADIUS.full },

  statsRow: { flexDirection: 'row', gap: SPACING.sm, flexWrap: 'wrap', alignItems: 'center' },
  modelPill: { borderRadius: RADIUS.sm, paddingVertical: 5, paddingHorizontal: SPACING.sm },
  modelText: { fontSize: FONT_SIZE.xs },

  actions: { flexDirection: 'row', gap: SPACING.sm, alignItems: 'center', flexWrap: 'wrap' },
  actionBtn: {},
  deleteBtn: { marginLeft: 'auto', padding: SPACING.xs },
  deleteIcon: { fontSize: 17 },
});

const onboardStyles = StyleSheet.create({
  card: {
    borderRadius: RADIUS.xl,
    borderWidth: 1,
    padding: SPACING.lg,
    marginBottom: SPACING.md,
    gap: SPACING.md,
  },
  cardHeader: { flexDirection: 'row', alignItems: 'center', gap: SPACING.sm },
  title: { flex: 1, fontSize: FONT_SIZE.md, fontWeight: '700' },
  progressLabel: {
    borderRadius: RADIUS.full,
    paddingVertical: 2,
    paddingHorizontal: SPACING.sm,
  },
  progressLabelText: { fontSize: FONT_SIZE.xs, fontWeight: '700' },
  dismiss: { fontSize: FONT_SIZE.md, paddingHorizontal: SPACING.xs },
  bar: { height: 6, borderRadius: RADIUS.full, overflow: 'hidden' },
  barFill: {
    height: '100%',
    borderRadius: RADIUS.full,
    backgroundColor: COLORS.primary,
  },
  step: { flexDirection: 'row', alignItems: 'center', gap: SPACING.sm },
  stepDot: {
    width: 22,
    height: 22,
    borderRadius: RADIUS.full,
    borderWidth: 1.5,
    alignItems: 'center',
    justifyContent: 'center',
    flexShrink: 0,
  },
  checkmark: { color: COLORS.white, fontSize: 12, fontWeight: '800' },
  stepNum: { fontSize: FONT_SIZE.xs, fontWeight: '700' },
  stepLabel: { flex: 1, fontSize: FONT_SIZE.sm, fontWeight: '500' },
  stepLabelDone: { textDecorationLine: 'line-through' },
});
