import React, { useState } from 'react';
import {
  Platform,
  Pressable,
  ScrollView,
  StyleSheet,
  TextInput,
  View,
} from 'react-native';
import { useSafeAreaInsets } from 'react-native-safe-area-context';
import { SymbolView } from 'expo-symbols';

import { ThemedText } from '@/components/themed-text';
import { ThemedView } from '@/components/themed-view';
import { BottomTabInset, MaxContentWidth, Spacing } from '@/constants/theme';
import { useTheme } from '@/hooks/use-theme';
import { t } from '@/i18n';

type CategoryIcon = {
  ios: string;
  android: string;
  web: string;
};

const CATEGORY_ICONS: Record<string, CategoryIcon> = {
  tech: { ios: 'laptopcomputer', android: 'laptop', web: 'laptop' },
  news: { ios: 'doc.text', android: 'article', web: 'article' },
  sports: { ios: 'figure.run', android: 'run', web: 'run' },
  business: { ios: 'briefcase', android: 'briefcase', web: 'briefcase' },
  entertainment: { ios: 'star', android: 'star', web: 'star' },
  health: { ios: 'heart.fill', android: 'heart', web: 'heart' },
  science: { ios: 'beaker', android: 'flask', web: 'flask' },
  food: { ios: 'bowl.with.spoon', android: 'restaurant', web: 'restaurant' },
};

const CATEGORIES = [
  { id: 'tech', name: 'Technology' },
  { id: 'news', name: 'News' },
  { id: 'sports', name: 'Sports' },
  { id: 'business', name: 'Business' },
  { id: 'entertainment', name: 'Entertainment' },
  { id: 'health', name: 'Health' },
  { id: 'science', name: 'Science' },
  { id: 'food', name: 'Food' },
];

const TRENDING_FEEDS = [
  {
    id: '1',
    title: 'TechCrunch',
    description: 'Latest technology news and startups',
    category: 'tech',
    subscribers: 125000,
  },
  {
    id: '2',
    title: 'The Verge',
    description: 'Technology, science, art, and culture',
    category: 'tech',
    subscribers: 98000,
  },
  {
    id: '3',
    title: 'Hacker News',
    description: 'News about hacking and startups',
    category: 'tech',
    subscribers: 87000,
  },
  {
    id: '4',
    title: 'BBC News',
    description: 'Breaking news and features',
    category: 'news',
    subscribers: 156000,
  },
  {
    id: '5',
    title: 'ESPN',
    description: 'Sports news and highlights',
    category: 'sports',
    subscribers: 112000,
  },
];

const RECOMMENDED_PODCASTS = [
  {
    id: '1',
    title: 'The Daily',
    description: 'News explained',
    publisher: 'The New York Times',
  },
  {
    id: '2',
    title: 'Reply All',
    description: 'About the internet',
    publisher: 'Gimlet Media',
  },
  {
    id: '3',
    title: '99% Invisible',
    description: 'Design and architecture',
    publisher: 'Roman Mars',
  },
];

export default function ExploreScreen() {
  const safeAreaInsets = useSafeAreaInsets();
  const insets = {
    ...safeAreaInsets,
    bottom: safeAreaInsets.bottom + BottomTabInset + Spacing.three,
  };
  const theme = useTheme();
  const [searchQuery, setSearchQuery] = useState('');
  const [selectedCategory, setSelectedCategory] = useState<string | null>(null);

  const contentPlatformStyle = Platform.select({
    android: {
      paddingTop: insets.top,
      paddingLeft: insets.left,
      paddingRight: insets.right,
      paddingBottom: insets.bottom,
    },
    web: {
      paddingTop: Spacing.six,
      paddingBottom: Spacing.four,
    },
  });

  const filteredTrending = TRENDING_FEEDS.filter((feed) => {
    const matchesSearch =
      feed.title.toLowerCase().includes(searchQuery.toLowerCase()) ||
      feed.description.toLowerCase().includes(searchQuery.toLowerCase());
    const matchesCategory = selectedCategory ? feed.category === selectedCategory : true;
    return matchesSearch && matchesCategory;
  });

  return (
    <ScrollView
      style={[styles.scrollView, { backgroundColor: theme.background }]}
      contentInset={insets}
      contentContainerStyle={[styles.contentContainer, contentPlatformStyle]}>
      <ThemedView style={styles.container}>
        <ThemedView style={styles.header}>
          <ThemedText type="title">{t('tab.explore')}</ThemedText>
          <ThemedText themeColor="textSecondary">{t('explore.discover')}</ThemedText>
        </ThemedView>

        <ThemedView style={styles.searchContainer}>
          <SymbolView
            tintColor={theme.textSecondary}
            name={{ ios: 'magnifyingglass', android: 'search', web: 'search' }}
            size={18}
            style={styles.searchIcon}
          />
          <TextInput
            style={[styles.searchInput, { color: theme.text }]}
            placeholder={t('explore.searchPlaceholder')}
            placeholderTextColor={theme.textSecondary}
            value={searchQuery}
            onChangeText={setSearchQuery}
            clearButtonMode="while-editing"
          />
        </ThemedView>

        <ThemedView style={styles.categoriesContainer}>
          <ScrollView
            horizontal
            showsHorizontalScrollIndicator={false}
            contentContainerStyle={styles.categoriesContent}>
            <Pressable
              style={[
                styles.categoryChip,
                !selectedCategory && { backgroundColor: theme.text },
              ]}
              onPress={() => setSelectedCategory(null)}>
              <ThemedText
                style={[
                  styles.categoryChipText,
                  !selectedCategory && { color: theme.background },
                ]}>
                {t('explore.all')}
              </ThemedText>
            </Pressable>
            {CATEGORIES.map((category) => (
              <Pressable
                key={category.id}
                style={[
                  styles.categoryChip,
                  selectedCategory === category.id && { backgroundColor: theme.text },
                ]}
                onPress={() =>
                  setSelectedCategory(
                    selectedCategory === category.id ? null : category.id
                  )
                }>
                <SymbolView
                  tintColor={
                    selectedCategory === category.id ? theme.background : theme.text
                  }
                  name={(CATEGORY_ICONS[category.id] as any)}
                  size={14}
                  style={styles.categoryIcon}
                />
                <ThemedText
                  style={[
                    styles.categoryChipText,
                    selectedCategory === category.id && { color: theme.background },
                  ]}>
                  {category.name}
                </ThemedText>
              </Pressable>
            ))}
          </ScrollView>
        </ThemedView>

        <ThemedView style={styles.section}>
          <ThemedView style={styles.sectionHeader}>
            <ThemedText type="section">{t('explore.trending')}</ThemedText>
          </ThemedView>
          <ThemedView style={styles.feedsList}>
            {filteredTrending.map((feed) => (
              <Pressable
                key={feed.id}
                style={[
                  styles.feedCard,
                  { backgroundColor: theme.backgroundElement },
                ]}>
                <ThemedView style={styles.feedCardContent}>
                  <ThemedText type="defaultSemiBold" numberOfLines={1}>
                    {feed.title}
                  </ThemedText>
                  <ThemedText
                    themeColor="textSecondary"
                    numberOfLines={2}
                    style={styles.feedDescription}>
                    {feed.description}
                  </ThemedText>
                  <ThemedView style={styles.feedMeta}>
                    <ThemedText themeColor="textSecondary" type="small">
                      {(feed.subscribers / 1000).toFixed(1)}K subscribers
                    </ThemedText>
                  </ThemedView>
                </ThemedView>
                <Pressable style={[styles.addButton, { backgroundColor: theme.text }]}>
                  <SymbolView
                    tintColor={theme.background}
                    name={{ ios: 'plus', android: 'add', web: 'add' }}
                    size={16}
                  />
                </Pressable>
              </Pressable>
            ))}
            {filteredTrending.length === 0 && (
              <ThemedView style={styles.emptyState}>
                <ThemedText themeColor="textSecondary">
                  {t('explore.noFeeds')}
                </ThemedText>
              </ThemedView>
            )}
          </ThemedView>
        </ThemedView>

        <ThemedView style={styles.section}>
          <ThemedView style={styles.sectionHeader}>
            <ThemedText type="section">{t('explore.recommended')}</ThemedText>
          </ThemedView>
          <ThemedView style={styles.feedsList}>
            {RECOMMENDED_PODCASTS.map((podcast) => (
              <Pressable
                key={podcast.id}
                style={[
                  styles.feedCard,
                  { backgroundColor: theme.backgroundElement },
                ]}>
                <ThemedView style={styles.feedCardContent}>
                  <ThemedView style={styles.podcastHeader}>
                    <SymbolView
                      tintColor={theme.textSecondary}
                      name={{ ios: 'waveform', android: 'equalizer', web: 'equalizer' }}
                      size={14}
                      style={styles.podcastIcon}
                    />
                    <ThemedText type="defaultSemiBold" numberOfLines={1}>
                      {podcast.title}
                    </ThemedText>
                  </ThemedView>
                  <ThemedText
                    themeColor="textSecondary"
                    numberOfLines={2}
                    style={styles.feedDescription}>
                    {podcast.description} • {podcast.publisher}
                  </ThemedText>
                </ThemedView>
                <Pressable style={[styles.addButton, { backgroundColor: theme.text }]}>
                  <SymbolView
                    tintColor={theme.background}
                    name={{ ios: 'plus', android: 'add', web: 'add' }}
                    size={16}
                  />
                </Pressable>
              </Pressable>
            ))}
          </ThemedView>
        </ThemedView>
      </ThemedView>
    </ScrollView>
  );
}

const styles = StyleSheet.create({
  scrollView: {
    flex: 1,
  },
  contentContainer: {
    flexDirection: 'row',
    justifyContent: 'center',
  },
  container: {
    maxWidth: MaxContentWidth,
    flexGrow: 1,
  },
  header: {
    paddingHorizontal: Spacing.four,
    paddingVertical: Spacing.four,
    gap: Spacing.two,
  },
  searchContainer: {
    flexDirection: 'row',
    alignItems: 'center',
    paddingHorizontal: Spacing.four,
    paddingVertical: Spacing.two,
    marginHorizontal: Spacing.four,
    marginBottom: Spacing.two,
    borderRadius: Spacing.three,
  },
  searchIcon: {
    marginRight: Spacing.two,
  },
  searchInput: {
    flex: 1,
    fontSize: 16,
    paddingVertical: Spacing.one,
  },
  categoriesContainer: {
    marginBottom: Spacing.four,
  },
  categoriesContent: {
    paddingHorizontal: Spacing.four,
    gap: Spacing.two,
  },
  categoryChip: {
    flexDirection: 'row',
    alignItems: 'center',
    paddingHorizontal: Spacing.three,
    paddingVertical: Spacing.two,
    borderRadius: Spacing.six,
    backgroundColor: '#e5e5ea',
    minWidth: 80,
  },
  categoryChipText: {
    fontSize: 14,
    fontWeight: '500',
  },
  categoryIcon: {
    marginRight: Spacing.one,
  },
  section: {
    marginBottom: Spacing.four,
  },
  sectionHeader: {
    paddingHorizontal: Spacing.four,
    paddingVertical: Spacing.two,
  },
  feedsList: {
    gap: Spacing.two,
    paddingHorizontal: Spacing.four,
  },
  feedCard: {
    flexDirection: 'row',
    alignItems: 'center',
    padding: Spacing.three,
    borderRadius: Spacing.three,
  },
  feedCardContent: {
    flex: 1,
    gap: Spacing.one,
  },
  feedDescription: {
    fontSize: 14,
    marginTop: Spacing.one,
  },
  feedMeta: {
    marginTop: Spacing.one,
  },
  addButton: {
    width: 32,
    height: 32,
    borderRadius: 16,
    justifyContent: 'center',
    alignItems: 'center',
    marginLeft: Spacing.two,
  },
  podcastHeader: {
    flexDirection: 'row',
    alignItems: 'center',
    gap: Spacing.two,
  },
  podcastIcon: {
    flexShrink: 0,
  },
  emptyState: {
    paddingVertical: Spacing.six,
    alignItems: 'center',
  },
});
