import { mobileDramaFeed } from '@infiplot/core';
import type { MobileDrama } from '@infiplot/types';
import { SymbolView } from 'expo-symbols';
import type { ComponentProps } from 'react';
import { useMemo, useRef, useState } from 'react';
import {
  Dimensions,
  FlatList,
  Pressable,
  StyleSheet,
  Text,
  View,
  type NativeScrollEvent,
  type NativeSyntheticEvent,
} from 'react-native';
import { SafeAreaView, useSafeAreaInsets } from 'react-native-safe-area-context';

import { BottomTabInset } from '@/constants/theme';

type SymbolName = ComponentProps<typeof SymbolView>['name'];

export default function FeedScreen() {
  const { height } = Dimensions.get('window');
  const insets = useSafeAreaInsets();
  const pageHeight = height;
  const [activeIndex, setActiveIndex] = useState(0);
  const listRef = useRef<FlatList<MobileDrama>>(null);

  const snapOffsets = useMemo(
    () => mobileDramaFeed.map((_, index) => index * pageHeight),
    [pageHeight],
  );

  function handleScrollEnd(event: NativeSyntheticEvent<NativeScrollEvent>) {
    const nextIndex = Math.round(event.nativeEvent.contentOffset.y / pageHeight);
    setActiveIndex(Math.max(0, Math.min(mobileDramaFeed.length - 1, nextIndex)));
  }

  return (
    <View style={styles.root}>
      <FlatList
        ref={listRef}
        data={mobileDramaFeed}
        keyExtractor={(item) => item.id}
        pagingEnabled
        snapToOffsets={snapOffsets}
        decelerationRate="fast"
        showsVerticalScrollIndicator={false}
        onMomentumScrollEnd={handleScrollEnd}
        renderItem={({ item, index }) => (
          <DramaPage
            drama={item}
            active={index === activeIndex}
            height={pageHeight}
            bottomInset={insets.bottom}
          />
        )}
      />
    </View>
  );
}

function DramaPage({
  drama,
  active,
  height,
  bottomInset,
}: {
  drama: MobileDrama;
  active: boolean;
  height: number;
  bottomInset: number;
}) {
  return (
    <View style={[styles.page, { height, backgroundColor: drama.palette[0] }]}>
      <View style={[styles.posterGlow, { backgroundColor: drama.palette[1] }]} />
      <View style={[styles.posterOrb, { borderColor: drama.palette[2] }]}>
        <Text style={[styles.posterTitle, { color: drama.palette[2] }]}>{drama.title}</Text>
        <Text style={styles.posterSubtitle}>{drama.episode}</Text>
      </View>

      <SafeAreaView style={styles.safe}>
        <View style={styles.topBar}>
          <Text style={styles.brand}>InfiPlot</Text>
          <View style={styles.livePill}>
            <View style={[styles.liveDot, { backgroundColor: active ? '#ff2d55' : '#777' }]} />
            <Text style={styles.liveText}>刷剧</Text>
          </View>
        </View>

        <View style={[styles.sideRail, { bottom: bottomInset + BottomTabInset + 86 }]}>
          <ActionButton name={{ ios: 'heart.fill', android: 'favorite', web: 'favorite' }} label={drama.likes} />
          <ActionButton name={{ ios: 'bubble.right.fill', android: 'chat_bubble', web: 'chat_bubble' }} label={drama.comments} />
          <ActionButton name={{ ios: 'square.and.arrow.up', android: 'ios_share', web: 'ios_share' }} label="分享" />
        </View>

        <View style={[styles.infoPanel, { paddingBottom: bottomInset + BottomTabInset + 20 }]}>
          <Text style={styles.creator}>@{drama.creator}</Text>
          <Text style={styles.title}>{drama.title}</Text>
          <Text style={styles.hook}>{drama.hook}</Text>
          <View style={styles.tags}>
            {drama.tags.map((tag) => (
              <Text key={tag} style={styles.tag}>
                #{tag}
              </Text>
            ))}
          </View>
          <View style={styles.playRow}>
            <Pressable style={({ pressed }) => [styles.primaryButton, pressed && styles.pressed]}>
              <SymbolView name={{ ios: 'play.fill', android: 'play_arrow', web: 'play_arrow' }} size={16} tintColor="#101010" />
              <Text style={styles.primaryButtonText}>继续看</Text>
            </Pressable>
            <Text style={styles.episode}>{drama.episode}</Text>
          </View>
        </View>
      </SafeAreaView>
    </View>
  );
}

function ActionButton({ name, label }: { name: SymbolName; label: string }) {
  return (
    <Pressable style={({ pressed }) => [styles.actionButton, pressed && styles.pressed]}>
      <View style={styles.actionIcon}>
        <SymbolView name={name} size={24} tintColor="#fff" />
      </View>
      <Text style={styles.actionLabel}>{label}</Text>
    </Pressable>
  );
}

const styles = StyleSheet.create({
  root: {
    flex: 1,
    backgroundColor: '#000',
  },
  page: {
    overflow: 'hidden',
  },
  posterGlow: {
    position: 'absolute',
    width: 520,
    height: 520,
    borderRadius: 260,
    top: '14%',
    left: -120,
    opacity: 0.5,
    transform: [{ rotate: '-18deg' }],
  },
  posterOrb: {
    position: 'absolute',
    top: '18%',
    alignSelf: 'center',
    width: '76%',
    aspectRatio: 0.72,
    borderWidth: 1,
    borderRadius: 28,
    justifyContent: 'center',
    alignItems: 'center',
    padding: 24,
    backgroundColor: 'rgba(255,255,255,0.08)',
  },
  posterTitle: {
    fontSize: 42,
    lineHeight: 48,
    fontWeight: '800',
    textAlign: 'center',
  },
  posterSubtitle: {
    color: 'rgba(255,255,255,0.72)',
    marginTop: 14,
    fontSize: 13,
    fontWeight: '700',
  },
  safe: {
    flex: 1,
  },
  topBar: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
    paddingHorizontal: 18,
    paddingTop: 6,
  },
  brand: {
    color: '#fff',
    fontSize: 20,
    fontWeight: '900',
  },
  livePill: {
    flexDirection: 'row',
    alignItems: 'center',
    gap: 6,
    paddingHorizontal: 12,
    paddingVertical: 7,
    borderRadius: 99,
    backgroundColor: 'rgba(0,0,0,0.32)',
  },
  liveDot: {
    width: 7,
    height: 7,
    borderRadius: 7,
  },
  liveText: {
    color: '#fff',
    fontSize: 12,
    fontWeight: '800',
  },
  sideRail: {
    position: 'absolute',
    right: 14,
    gap: 18,
    alignItems: 'center',
  },
  actionButton: {
    alignItems: 'center',
    gap: 6,
  },
  actionIcon: {
    width: 48,
    height: 48,
    borderRadius: 24,
    alignItems: 'center',
    justifyContent: 'center',
    backgroundColor: 'rgba(255,255,255,0.16)',
  },
  actionLabel: {
    color: '#fff',
    fontSize: 11,
    fontWeight: '800',
  },
  infoPanel: {
    marginTop: 'auto',
    paddingLeft: 18,
    paddingRight: 82,
    gap: 10,
  },
  creator: {
    color: '#fff',
    fontSize: 15,
    fontWeight: '900',
  },
  title: {
    color: '#fff',
    fontSize: 30,
    lineHeight: 36,
    fontWeight: '900',
  },
  hook: {
    color: 'rgba(255,255,255,0.88)',
    fontSize: 15,
    lineHeight: 22,
    fontWeight: '600',
  },
  tags: {
    flexDirection: 'row',
    flexWrap: 'wrap',
    gap: 8,
  },
  tag: {
    color: '#fff',
    fontSize: 13,
    fontWeight: '800',
  },
  playRow: {
    flexDirection: 'row',
    alignItems: 'center',
    gap: 12,
    marginTop: 4,
  },
  primaryButton: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'center',
    gap: 6,
    paddingHorizontal: 18,
    height: 42,
    borderRadius: 21,
    backgroundColor: '#fff',
  },
  primaryButtonText: {
    color: '#101010',
    fontSize: 14,
    fontWeight: '900',
  },
  episode: {
    color: 'rgba(255,255,255,0.78)',
    fontSize: 12,
    fontWeight: '700',
    flexShrink: 1,
  },
  pressed: {
    opacity: 0.75,
  },
});
