/**
 * Content calendar — social media scheduling and content overview.
 */

import React, { useEffect, useState, useCallback } from 'react';
import {
  View,
  Text,
  StyleSheet,
  FlatList,
  TouchableOpacity,
  RefreshControl,
} from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import { useTheme } from '../../themes/ThemeProvider';
import { getContentCalendar } from '../../services/api';

interface ContentPost {
  id: number;
  title: string;
  platform: string;
  content_type: string;
  scheduled_date: string;
  scheduled_time: string;
  status: 'draft' | 'scheduled' | 'published' | 'failed';
  preview_text: string;
}

export default function ContentCalendar({ navigation }: any) {
  const { theme } = useTheme();
  const [posts, setPosts] = useState<ContentPost[]>([]);
  const [refreshing, setRefreshing] = useState(false);

  const load = useCallback(async () => {
    const res = await getContentCalendar();
    if (res.success && res.data) setPosts(res.data as ContentPost[]);
  }, []);

  useEffect(() => {
    load();
  }, [load]);

  const onRefresh = useCallback(async () => {
    setRefreshing(true);
    await load();
    setRefreshing(false);
  }, [load]);

  const platformIcon = (platform: string): string => {
    switch (platform.toLowerCase()) {
      case 'instagram': return '📸';
      case 'facebook': return '📘';
      case 'tiktok': return '🎵';
      case 'linkedin': return '💼';
      default: return '📱';
    }
  };

  const statusColor = (status: string): string => {
    switch (status) {
      case 'published': return theme.colors.success;
      case 'scheduled': return theme.colors.info;
      case 'draft': return theme.colors.warning;
      case 'failed': return theme.colors.error;
      default: return theme.colors.textSecondary;
    }
  };

  return (
    <SafeAreaView style={[styles.safe, { backgroundColor: theme.colors.background }]} edges={['bottom']}>
      <View style={[styles.quickActions, { backgroundColor: theme.colors.card }]}>
        <TouchableOpacity
          style={[styles.qaBtn, { backgroundColor: theme.colors.primary }]}
          onPress={() => navigation.navigate('Staging')}
        >
          <Text style={styles.qaBtnText}>Virtual Staging</Text>
        </TouchableOpacity>
        <TouchableOpacity
          style={[styles.qaBtn, { backgroundColor: theme.colors.accent }]}
          onPress={() => navigation.navigate('VideoGen')}
        >
          <Text style={styles.qaBtnText}>Create Video</Text>
        </TouchableOpacity>
      </View>

      <FlatList
        data={posts}
        keyExtractor={(item) => String(item.id)}
        refreshControl={
          <RefreshControl refreshing={refreshing} onRefresh={onRefresh} tintColor={theme.colors.primary} />
        }
        renderItem={({ item }) => (
          <View style={[styles.postCard, theme.shadow.sm, { backgroundColor: theme.colors.card }]}>
            <View style={styles.postHeader}>
              <Text style={styles.platformIcon}>{platformIcon(item.platform)}</Text>
              <View style={styles.postHeaderText}>
                <Text style={[styles.postTitle, { color: theme.colors.text }]}>{item.title}</Text>
                <Text style={[styles.postMeta, { color: theme.colors.textSecondary }]}>
                  {item.platform} • {item.content_type}
                </Text>
              </View>
              <View style={[styles.statusDot, { backgroundColor: statusColor(item.status) }]} />
            </View>
            <Text style={[styles.postPreview, { color: theme.colors.textSecondary }]} numberOfLines={2}>
              {item.preview_text}
            </Text>
            <Text style={[styles.postSchedule, { color: theme.colors.textSecondary }]}>
              {item.scheduled_date} at {item.scheduled_time}
            </Text>
          </View>
        )}
        ListEmptyComponent={
          <View style={styles.empty}>
            <Text style={[styles.emptyText, { color: theme.colors.textSecondary }]}>
              No content scheduled. Create your first post!
            </Text>
          </View>
        }
      />
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  safe: { flex: 1 },
  quickActions: { flexDirection: 'row', padding: 12, gap: 10 },
  qaBtn: { flex: 1, paddingVertical: 12, borderRadius: 10, alignItems: 'center' },
  qaBtnText: { color: '#FFF', fontWeight: '700', fontSize: 14 },
  postCard: { marginHorizontal: 16, marginVertical: 6, borderRadius: 10, padding: 14 },
  postHeader: { flexDirection: 'row', alignItems: 'center', marginBottom: 8 },
  platformIcon: { fontSize: 24, marginRight: 10 },
  postHeaderText: { flex: 1 },
  postTitle: { fontSize: 15, fontWeight: '600' },
  postMeta: { fontSize: 12, marginTop: 2 },
  statusDot: { width: 10, height: 10, borderRadius: 5 },
  postPreview: { fontSize: 13, lineHeight: 18, marginBottom: 6 },
  postSchedule: { fontSize: 12 },
  empty: { padding: 40, alignItems: 'center' },
  emptyText: { fontSize: 14, textAlign: 'center' },
});
