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,
  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 className="flex-1 bg-black">
      <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
      className="overflow-hidden"
      style={{ height, backgroundColor: drama.palette[0] }}
    >
      <View
        className="absolute left-[-120px] top-[14%] h-[520px] w-[520px] rounded-full opacity-50"
        style={{
          backgroundColor: drama.palette[1],
          transform: [{ rotate: "-18deg" }],
        }}
      />
      <View
        className="absolute top-[18%] w-[76%] self-center rounded-[28px] border bg-white/10 p-6"
        style={{ aspectRatio: 0.72, borderColor: drama.palette[2] }}
      >
        <Text
          className="text-center text-[42px] font-extrabold leading-[48px]"
          style={{ color: drama.palette[2] }}
        >
          {drama.title}
        </Text>
        <Text className="mt-3.5 text-[13px] font-bold text-white/70">
          {drama.episode}
        </Text>
      </View>

      <SafeAreaView className="flex-1">
        <View className="flex-row items-center justify-between px-[18px] pt-1.5">
          <Text className="text-xl font-black text-white">InfiPlot</Text>
          <View className="flex-row items-center gap-1.5 rounded-full bg-black/30 px-3 py-[7px]">
            <View
              className="h-[7px] w-[7px] rounded-full"
              style={{ backgroundColor: active ? "#ff2d55" : "#777" }}
            />
            <Text className="text-xs font-extrabold text-white">刷剧</Text>
          </View>
        </View>

        <View
          className="absolute right-3.5 items-center gap-[18px]"
          style={{ 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
          className="mt-auto gap-2.5 pl-[18px] pr-[82px]"
          style={{ paddingBottom: bottomInset + BottomTabInset + 20 }}
        >
          <Text className="text-[15px] font-black text-white">
            @{drama.creator}
          </Text>
          <Text className="text-[30px] font-black leading-9 text-white">
            {drama.title}
          </Text>
          <Text className="text-[15px] font-semibold leading-[22px] text-white/90">
            {drama.hook}
          </Text>
          <View className="flex-row flex-wrap gap-2">
            {drama.tags.map((tag) => (
              <Text key={tag} className="text-[13px] font-extrabold text-white">
                #{tag}
              </Text>
            ))}
          </View>
          <View className="mt-1 flex-row items-center gap-3">
            <Pressable
              className="h-[42px] flex-row items-center justify-center gap-1.5 rounded-full bg-white px-[18px]"
              style={({ pressed }) => ({ opacity: pressed ? 0.75 : undefined })}
            >
              <SymbolView
                name={{
                  ios: "play.fill",
                  android: "play_arrow",
                  web: "play_arrow",
                }}
                size={16}
                tintColor="#101010"
              />
              <Text className="text-sm font-black text-[#101010]">继续看</Text>
            </Pressable>
            <Text className="shrink text-xs font-bold text-white/80">
              {drama.episode}
            </Text>
          </View>
        </View>
      </SafeAreaView>
    </View>
  );
}

function ActionButton({ name, label }: { name: SymbolName; label: string }) {
  return (
    <Pressable
      className="items-center gap-1.5"
      style={({ pressed }) => ({ opacity: pressed ? 0.75 : undefined })}
    >
      <View className="h-12 w-12 items-center justify-center rounded-full bg-white/15">
        <SymbolView name={name} size={24} tintColor="#fff" />
      </View>
      <Text className="text-[11px] font-extrabold text-white">{label}</Text>
    </Pressable>
  );
}
