import Documents from "@/components/sections/details/documents";
import InvestmentTerms from "@/components/sections/details/investment-terms";
import MarketplaceInvestCard from "@/components/sections/details/marketplace-invest-card";
import PropertyVideo from "@/components/sections/details/property-video";
import Reviews from "@/components/sections/details/reviews";
import Pagination from "@/components/sliderUi/Pagination";
import ImageLoader from "@/components/ui/ImageLoader";
import { useGetQuery } from "@/hooks/mutate/useGetQuery";
import { useColor } from "@/hooks/useColor";
import { useShare } from "@/hooks/useShare";
import { useAuthStore } from "@/providers/AuthStoreProviders";
import { useTranslations } from "@/providers/TranslationProviders";
import { useWishlist } from "@/providers/WishlistProvider";
import { Project } from "@/types/project";
import { showToast } from "@/utils/toast";
import { router, useLocalSearchParams } from "expo-router";
import { ArrowLeftIcon, ChartLineUpIcon, CoinsIcon, HeartIcon, HourglassLowIcon, MapPinIcon, ShareNetworkIcon, UsersThreeIcon } from "phosphor-react-native";
import { FlatList, Linking, Platform, Pressable, ScrollView, Text, useWindowDimensions, View, ViewToken } from "react-native";
import Animated, { useAnimatedRef, useAnimatedScrollHandler, useSharedValue } from "react-native-reanimated";
import RenderHTML from "react-native-render-html";
import { useSafeAreaInsets } from "react-native-safe-area-context";

export default function MarketplaceDetailsScreen() {
  const insets = useSafeAreaInsets();
  const { primary, secondary } = useColor();
  const { appInfo } = useAuthStore((state) => state);
  const { tran, translateNumber } = useTranslations();
  const { project, price, seller, number_of_shares, project_id, seller_id } = useLocalSearchParams();
  const { addItem, removeItem, isInWishlist } = useWishlist();

  const { data: projectDetails } = useGetQuery<Project>({
    url: `/marketplace/${project}/${price}${seller ? `/${seller}` : ""}`,
  });

  const imageIds: number[] = projectDetails?.gallery?.map((img) => img.id) ?? [];

  const flatListRef = useAnimatedRef<FlatList>();
  const x = useSharedValue(0);
  const flatListIndex = useSharedValue(0);

  const onViewableItemsChanged = ({ viewableItems }: { viewableItems: ViewToken[] }) => {
    if (viewableItems[0]?.index !== null) {
      flatListIndex.value = viewableItems[0].index;
    }
  };

  const onScroll = useAnimatedScrollHandler({
    onScroll: (event) => {
      x.value = event.contentOffset.x;
    },
  });
  const { width: SCREEN_WIDTH } = useWindowDimensions();

  // Prepare props for InvestCard
  const detailsInfoProps = {
    title: projectDetails?.title,
    slug: projectDetails?.slug,
    project_id: Number(project_id) || projectDetails?.id,
    code: projectDetails?.code,
    thumbnail: projectDetails?.thumbnail,
    share_value: projectDetails?.share_value,
    roi: projectDetails?.roi,
    number_of_shares: Number(number_of_shares) || projectDetails?.number_of_shares,
    share_sold: projectDetails?.share_sold,
    share_type: projectDetails?.share_type,
    effective_date: projectDetails?.effective_date,
    maturity_date: projectDetails?.maturity_date ?? null,
    renewal_date: projectDetails?.renewal_date ?? null,
    total_investors: projectDetails?.total_investors,
    roi_distribution: projectDetails?.roi_distribution,
    marketplace_resale: projectDetails?.marketplace_resale,
    listing: projectDetails?.listing,
    price: Number(price),
    seller_id: seller_id ? Number(seller_id) : null,
  };

  const onShare = useShare({
    messageText: `${appInfo?.application_info?.company_info?.website}/marketplace/${projectDetails?.slug}/${price}${seller ? `/${seller}` : ""}`,
  });

  const inWishlist = isInWishlist(detailsInfoProps.project_id ?? 0);

  const handleWishlistToggle = () => {
    if (inWishlist && detailsInfoProps.project_id) {
      removeItem(detailsInfoProps.project_id);
      showToast({
        type: "success",
        text: `${tran("Removed from wishlist")}`,
      });
    } else {
      addItem({
        id: detailsInfoProps.project_id ?? 0,
        project_id: detailsInfoProps.project_id ?? 0,
        title: detailsInfoProps.title ?? "",
        slug: detailsInfoProps.slug ?? "",
        code: detailsInfoProps.code ?? "",
        thumbnail: detailsInfoProps.thumbnail ?? "",
      });
      showToast({
        type: "success",
        text: `${tran("Added to wishlist")}`,
      });
    }
  };

  const openMap = () => {
    const lat = projectDetails?.latitude;
    const lng = projectDetails?.longitude;

    if (!lat || !lng) return;

    const url = Platform.select({
      ios: `http://maps.apple.com/?ll=${lat},${lng}`,
      android: `geo:${lat},${lng}?q=${lat},${lng}`,
    });

    if (url) {
      Linking.openURL(url);
    }
  };

  return (
    <View className="flex-1 bg-white">
      <ScrollView showsVerticalScrollIndicator={false} className="flex-1">
        {/* Immersive Gallery Section */}
        <View className="relative">
          <Animated.FlatList
            ref={flatListRef}
            data={projectDetails?.gallery}
            onScroll={onScroll}
            keyExtractor={(item, idx) => `key:${idx}`}
            renderItem={({ item }) => (
              <View style={{ width: SCREEN_WIDTH }}>
                <ImageLoader src={item.url} width={SCREEN_WIDTH} height={320} className="w-full h-[320px]" />
              </View>
            )}
            scrollEventThrottle={16}
            horizontal
            pagingEnabled
            showsHorizontalScrollIndicator={false}
            onViewableItemsChanged={onViewableItemsChanged}
            viewabilityConfig={{
              minimumViewTime: 300,
              viewAreaCoveragePercentThreshold: 50,
            }}
          />

          {/* Header Overlay */}
          <View className="absolute top-0 left-0 right-0 px-4 flex-row justify-between items-center" style={{ paddingTop: insets.top + 10 }}>
            <Pressable onPress={() => router.back()} hitSlop={10} className="w-10 h-10 rounded-full bg-white/90 items-center justify-center shadow-sm">
              <View pointerEvents="none">
                <ArrowLeftIcon size={20} color="#0f172a" weight="bold" />
              </View>
            </Pressable>

            <View className="flex-row gap-2">
              <Pressable onPress={onShare} hitSlop={10} className="w-10 h-10 rounded-full bg-white/90 items-center justify-center shadow-sm">
                <View pointerEvents="none">
                  <ShareNetworkIcon size={20} color="#0f172a" weight="bold" />
                </View>
              </Pressable>
              <Pressable onPress={handleWishlistToggle} hitSlop={10} className="w-10 h-10 rounded-full bg-white/90 items-center justify-center shadow-sm">
                <View pointerEvents="none">
                  <HeartIcon size={20} color={inWishlist ? "#ef4444" : "#0f172a"} weight={inWishlist ? "fill" : "bold"} />
                </View>
              </Pressable>
            </View>
          </View>

          {/* Pagination Dots Overlay */}
          <View className="absolute bottom-6 left-0 right-0 items-center">
            <Pagination onbordingSliderData={imageIds} x={x} />
          </View>

          {/* Type Badge Overlay */}
          {projectDetails?.type?.name && (
            <View className="absolute bottom-6 left-4 bg-slate-900 px-3 py-1.5 rounded-lg shadow-lg">
              <Text className="text-white text-[10px] font-manrope-extrabold uppercase tracking-widest">{tran(projectDetails.type.name)}</Text>
            </View>
          )}
        </View>

        {/* Content Section */}
        <View className="px-5 pt-6 pb-24">
          {/* Project Title & Location */}
          <View className="mb-6">
            <Text className="text-3xl font-manrope-extrabold text-slate-900 leading-tight mb-3">{projectDetails?.title}</Text>
            <View className="flex-row flex-wrap items-center gap-4">
              <View className="flex-row items-center gap-1.5">
                <MapPinIcon size={16} color={primary.base} weight="bold" />
                <Text className="text-sm font-manrope-semibold text-slate-500">{projectDetails?.city?.name}</Text>
              </View>
              <View className="flex-row items-center gap-1.5">
                <UsersThreeIcon size={16} color="#64748b" weight="bold" />
                <Text className="text-sm font-manrope-semibold text-slate-500">
                  {translateNumber(projectDetails?.total_investors || 0)} {tran("Investors")}
                </Text>
              </View>
              <Pressable onPress={openMap} className="px-2 py-1 bg-slate-50 rounded-md border border-slate-100">
                <Text className="text-[10px] font-manrope-bold text-slate-600 uppercase">{tran("View Map")}</Text>
              </Pressable>
            </View>
          </View>

          {/* Quick Stats Grid */}
          <View className="flex-row gap-3 mb-8">
            <View className="flex-1 p-3.5 rounded-2xl border border-slate-100" style={{ backgroundColor: primary[5] }}>
              <View className="w-8 h-8 rounded-full bg-white items-center justify-center mb-2 shadow-sm">
                <ChartLineUpIcon size={16} color={primary.base} weight="bold" />
              </View>
              <Text className="text-[10px] font-manrope-bold text-slate-400 uppercase tracking-wider mb-0.5">{tran("Target ROI")}</Text>
              <Text className="text-lg font-manrope-extrabold text-slate-900">{translateNumber(projectDetails?.roi || 0)}%</Text>
            </View>

            <View className="flex-1 p-3.5 rounded-2xl border border-slate-100" style={{ backgroundColor: secondary[10] }}>
              <View className="w-8 h-8 rounded-full bg-white items-center justify-center mb-2 shadow-sm">
                <CoinsIcon size={16} color={secondary.base} weight="bold" />
              </View>
              <Text className="text-[10px] font-manrope-bold text-slate-400 uppercase tracking-wider mb-0.5">{tran("Share Price")}</Text>
              <Text className="text-lg font-manrope-extrabold text-slate-900">
                {appInfo?.application_info?.company_info?.currency_symbol}
                {translateNumber(projectDetails?.share_value || 0)}
              </Text>
            </View>

            <View className="flex-1 p-3.5 rounded-2xl bg-slate-50 border border-slate-100">
              <View className="w-8 h-8 rounded-full bg-white items-center justify-center mb-2 shadow-sm">
                <HourglassLowIcon size={16} color="#64748b" weight="bold" />
              </View>
              <Text className="text-[10px] font-manrope-bold text-slate-400 uppercase tracking-wider mb-0.5">{tran("Term")}</Text>
              <Text className="text-lg font-manrope-extrabold text-slate-900">{projectDetails?.share_type === "infinite" ? "∞" : "Fixed"}</Text>
            </View>
          </View>

          {/* Tabs/Sections Area */}
          <View className="mb-8">
            <View className="flex-row items-center justify-between mb-4 border-b border-slate-100 pb-4">
              <Text className="text-xl font-manrope-extrabold text-slate-900">{tran("Project Overview")}</Text>
              <View className="px-2 py-1 bg-emerald-50 rounded-md">
                <Text className="text-[10px] font-manrope-bold text-emerald-600 uppercase">{projectDetails?.code}</Text>
              </View>
            </View>
            {projectDetails?.description ? (
              <RenderHTML
                contentWidth={SCREEN_WIDTH - 40}
                source={{ html: projectDetails.description }}
                tagsStyles={{
                  body: {
                    color: "#475569",
                    fontFamily: "Manrope-Medium",
                    fontSize: 15,
                    lineHeight: 24,
                  },
                  p: {
                    marginBottom: 10,
                  },
                }}
              />
            ) : (
              <Text className="text-slate-600 font-manrope-medium leading-6">{tran("No description available for this project.")}</Text>
            )}
          </View>

          <PropertyVideo videoUrl={projectDetails?.video_tour_url} thumbnail={projectDetails?.thumbnail} />

          <InvestmentTerms
            roi={projectDetails?.roi}
            share_value={projectDetails?.share_value}
            number_of_shares={projectDetails?.number_of_shares}
            share_sold={projectDetails?.share_sold}
            effective_date={projectDetails?.effective_date}
            maturity_date={projectDetails?.maturity_date}
            roi_distribution={projectDetails?.roi_distribution}
            marketplace_resale={projectDetails?.marketplace_resale}
            share_type={projectDetails?.share_type}
          />

          {/* Marketplace Investment Card */}
          <MarketplaceInvestCard {...detailsInfoProps} />

          {/* Multi-Section Area */}
          <View className="mt-8 pb-10">
            {projectDetails?.documents && (
              <View className="mb-10">
                <Documents documents={projectDetails.documents} />
              </View>
            )}

            {projectDetails?.documents && <View className="h-px bg-slate-100 w-full mb-10" />}

            <View>
              <Reviews reviews={projectDetails?.reviews} projectSlug={projectDetails?.slug} />
            </View>
          </View>
        </View>
      </ScrollView>
    </View>
  );
}
