// Article Detail View

import React, { useEffect, useState } from 'react';
import {
  View,
  ScrollView,
  StyleSheet,
  Share,
  Linking,
  Image,
  Pressable,
} from 'react-native';
import { useSafeAreaInsets } from 'react-native-safe-area-context';
import { SymbolView } from 'expo-symbols';
import { useLocalSearchParams } from 'expo-router';
import RenderHtml from 'react-native-render-html';

import { ThemedText } from '@/components/themed-text';
import { ThemedView } from '@/components/themed-view';
import { useTheme } from '@/hooks/use-theme';
import { useBookmarkStore } from '@/stores/bookmark-store';
import { FeedItem } from '@/types/feed';
import { getFeedItems, getAllFeedItems } from '@/services/database';
import { Colors, Spacing, MaxContentWidth, BottomTabInset } from '@/constants/theme';

export default function ArticleDetailScreen() {
  const { id } = useLocalSearchParams<{ id: string }>();
  const insets = useSafeAreaInsets();
  const theme = useTheme();
  const { isBookmarked, toggleBookmark } = useBookmarkStore();
  
  const [article, setArticle] = useState<FeedItem | null>(null);
  const [loading, setLoading] = useState(true);
  
  const bookmarked = id ? isBookmarked(id) : false;

  useEffect(() => {
    async function loadArticle() {
      if (!id) return;
      
      try {
        setLoading(true);
        const items = await getFeedItems(undefined, 500);
        const found = items.find(item => item.id === id);
        setArticle(found || null);
      } catch (error) {
        console.error('Failed to load article:', error);
      } finally {
        setLoading(false);
      }
    }
    
    loadArticle();
  }, [id]);

  const handleShare = async () => {
    if (!article?.link) return;
    
    try {
      await Share.share({
        message: `${article.title}\n\n${article.link}`,
        title: article.title,
        url: article.link,
      });
    } catch (error) {
      console.error('Share error:', error);
    }
  };

  const handleOpenInBrowser = () => {
    if (article?.link) {
      Linking.openURL(article.link);
    }
  };

  const formatDate = (date?: Date) => {
    if (!date) return '';
    return new Date(date).toLocaleDateString('en-US', {
      year: 'numeric',
      month: 'long',
      day: 'numeric',
    });
  };

  const extractImagesFromHtml = (html: string): string[] => {
    const imgRegex = /<img[^>]+src=["']([^"']+)["'][^>]*>/gi;
    const images: string[] = [];
    let match;
    while ((match = imgRegex.exec(html)) !== null) {
      if (match[1] && !images.includes(match[1])) {
        images.push(match[1]);
      }
    }
    return images;
  };

  const getGalleryImages = (): string[] => {
    const images: string[] = [];
    if (article?.content) {
      images.push(...extractImagesFromHtml(article.content));
    }
    if (article?.description) {
      images.push(...extractImagesFromHtml(article.description));
    }
    return [...new Set(images)];
  };

  const galleryImages = getGalleryImages();

  const renderContent = (content?: string) => {
    if (!content) return null;
    
    const isHtml = /<[a-z][\s\S]*>/i.test(content);
    
    if (isHtml) {
      return (
        <RenderHtml
          contentWidth={350}
          source={{ html: content }}
          baseStyle={styles.content}
        />
      );
    }
    
    return (
      <ThemedText style={styles.content}>
        {content}
      </ThemedText>
    );
  };

  if (loading) {
    return (
      <ThemedView style={styles.container}>
        <ThemedView style={styles.loadingContainer}>
          <ThemedText>Loading...</ThemedText>
        </ThemedView>
      </ThemedView>
    );
  }

  if (!article) {
    return (
      <ThemedView style={styles.container}>
        <ThemedView style={styles.errorContainer}>
          <ThemedText>Article not found</ThemedText>
        </ThemedView>
      </ThemedView>
    );
  }

  return (
    <ThemedView style={styles.container}>
      <ScrollView
        style={styles.scrollView}
        contentContainerStyle={[
          styles.contentContainer,
          { paddingBottom: insets.bottom + BottomTabInset + Spacing.four },
        ]}>
        <ThemedView style={styles.header}>
          <ThemedText type="title" style={styles.title}>
            {article.title}
          </ThemedText>
          
          {article.author && (
            <ThemedText type="small" themeColor="textSecondary" style={styles.author}>
              By {article.author}
            </ThemedText>
          )}
          
          {article.published && (
            <ThemedText type="small" themeColor="textSecondary">
              {formatDate(article.published)}
            </ThemedText>
          )}
        </ThemedView>

        <ThemedView style={styles.actions}>
          <Pressable
            style={[styles.actionButton, { backgroundColor: theme.backgroundElement }]}
            onPress={() => id && toggleBookmark(id)}>
            <SymbolView
              tintColor={bookmarked ? '#007AFF' : theme.text}
              name={bookmarked ? 'bookmark_fill' as any : 'bookmark' as any}
              size={20}
            />
          </Pressable>
          
          <Pressable
            style={[styles.actionButton, { backgroundColor: theme.backgroundElement }]}
            onPress={handleShare}>
            <SymbolView
              tintColor={theme.text}
              name={{ ios: 'square.and.arrow.up', android: 'share', web: 'share' }}
              size={20}
            />
          </Pressable>
          
          <Pressable
            style={[styles.actionButton, { backgroundColor: theme.backgroundElement }]}
            onPress={handleOpenInBrowser}>
            <SymbolView
              tintColor={theme.text}
              name={{ ios: 'safari', android: 'public', web: 'globe' }}
              size={20}
            />
          </Pressable>
        </ThemedView>

        {galleryImages.length > 0 && (
          <ThemedView style={styles.gallery}>
            <ScrollView
              horizontal
              showsHorizontalScrollIndicator={false}
              contentContainerStyle={styles.galleryContent}
            >
              {galleryImages.map((imgUrl, index) => (
                <Pressable key={index} onPress={() => Linking.openURL(imgUrl)}>
                  <Image
                    source={{ uri: imgUrl }}
                    style={styles.galleryImage}
                    resizeMode="cover"
                  />
                </Pressable>
              ))}
            </ScrollView>
          </ThemedView>
        )}

        {article.description && (
          <ThemedView style={styles.section}>
            <ThemedText type="default" style={styles.description}>
              {article.description}
            </ThemedText>
          </ThemedView>
        )}

        {article.content && (
          <ThemedView style={styles.section}>
            {renderContent(article.content)}
          </ThemedView>
        )}

        {article.link && (
          <Pressable
            style={[styles.readMoreButton, { backgroundColor: theme.text }]}
            onPress={handleOpenInBrowser}>
            <ThemedText style={[styles.readMoreText, { color: theme.background }]}>
              Read Full Article
            </ThemedText>
          </Pressable>
        )}
      </ScrollView>
    </ThemedView>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  scrollView: {
    flex: 1,
  },
  contentContainer: {
    maxWidth: MaxContentWidth,
    marginHorizontal: 'auto',
    flexGrow: 1,
  },
  loadingContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
  errorContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
  header: {
    padding: Spacing.four,
    gap: Spacing.two,
  },
  title: {
    fontSize: 24,
    fontWeight: '700',
    lineHeight: 32,
  },
  author: {
    marginTop: Spacing.two,
  },
  actions: {
    flexDirection: 'row',
    paddingHorizontal: Spacing.four,
    paddingVertical: Spacing.two,
    gap: Spacing.two,
  },
  actionButton: {
    width: 44,
    height: 44,
    borderRadius: 22,
    justifyContent: 'center',
    alignItems: 'center',
  },
  gallery: {
    paddingVertical: Spacing.two,
  },
  galleryContent: {
    paddingHorizontal: Spacing.four,
    gap: Spacing.two,
  },
  galleryImage: {
    width: 200,
    height: 150,
    borderRadius: Spacing.two,
  },
  section: {
    padding: Spacing.four,
    paddingTop: 0,
  },
  description: {
    fontSize: 16,
    lineHeight: 24,
    color: '#333',
  },
  content: {
    fontSize: 16,
    lineHeight: 26,
  },
  readMoreButton: {
    margin: Spacing.four,
    padding: Spacing.three,
    borderRadius: Spacing.three,
    alignItems: 'center',
  },
  readMoreText: {
    fontSize: 16,
    fontWeight: '600',
  },
});