import { useColor } from "@/hooks/useColor";
import { useCurrency } from "@/hooks/useCurrency";
import { useInvestModal } from "@/providers/InvestModalProvider";
import { useTranslations } from "@/providers/TranslationProviders";
import { useWishlist } from "@/providers/WishlistProvider";
import { Project } from "@/types/project";
import { showToast } from "@/utils/toast";
import { router } from "expo-router";
import { ArrowRightIcon, ChartLineUpIcon, CoinsIcon, FileTextIcon, HeartIcon, HourglassLowIcon, MapPinIcon, TagIcon, UsersThreeIcon } from "phosphor-react-native";
import { useState } from "react";
import { Pressable, Text, View } from "react-native";
import Button from "../ui/Button";
import ImageLoader from "../ui/ImageLoader";

export default function ProjectCard({ project }: { project: Project }) {
  const { primary, secondary } = useColor();
  const { tran, translateNumber } = useTranslations();
  const { addItem, removeItem, isInWishlist } = useWishlist();
  const { openModal: investModal } = useInvestModal();
  const { currency } = useCurrency();

  const [quantity] = useState(1);
  const inWishlist = isInWishlist(project.id);

  const handleWishlistToggle = () => {
    if (inWishlist) {
      // When removing, we pass the project.id. The provider's removeItem
      // should handle whether this ID is a temporary one (for guests) or a
      // real wishlist item ID (for logged-in users).
      removeItem(project.id);
      showToast({
        type: "success",
        text: tran("Removed from wishlist"),
      });
    } else {
      addItem({
        id: project.id,
        project_id: project.id,
        title: project.title,
        slug: project.slug,
        code: project.code,
        thumbnail: project.thumbnail,
      });
      showToast({
        type: "success",
        text: tran("Added to wishlist"),
      });
    }
  };

  // Calculate duration in months
  const calculateDuration = () => {
    if (project.share_type === "infinite") return "∞";

    const startDate = new Date(project.effective_date);
    const endDate = project.maturity_date ? new Date(project.maturity_date) : project.renewal_date ? new Date(project.renewal_date) : null;

    if (!endDate) return "N/A";

    const months = Math.round((endDate.getTime() - startDate.getTime()) / (1000 * 60 * 60 * 24 * 30));
    return `${months}M`;
  };

  // Calculate time remaining until effective date
  const calculateTimeRemaining = () => {
    const now = new Date();
    const effectiveDate = new Date(project.effective_date);
    const diff = effectiveDate.getTime() - now.getTime();

    if (diff <= 0) return tran("Active");

    const days = Math.floor(diff / (1000 * 60 * 60 * 24));
    const hours = Math.floor((diff % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
    const minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60));

    return `${days}D:${hours}H:${minutes}M`;
  };

  const handleInvest = () => {
    investModal({
      title: project.title,
      slug: project.slug,
      share_count: quantity,
      share_value: project.share_value,
      max: project.number_of_shares - project.share_sold,
    });
  };
  return (
    <Pressable
      className="bg-white rounded-2xl border overflow-hidden"
      style={{
        borderColor: primary[20],
      }}
      onPress={() => router.push(`/(screens)/project-details?project=${project.slug}`)}
    >
      {/* Fixed-height image section */}
      <View className="">
        {/* Featured Ribbon */}
        {project.is_featured ? (
          <Text
            className="absolute top-4 -left-9 w-32 py-1 text-center text-white font-bold uppercase tracking-wider -rotate-45 z-20 text-xs"
            style={{
              backgroundColor: secondary.base,
            }}
          >
            {tran("Featured")}
          </Text>
        ) : null}

        {/* Badges Row */}
        <View className={`absolute top-0 z-10 w-full py-2 pe-2  flex-row items-center gap-2 text-sm ${project.is_featured ? "ps-14" : "ps-2"}`}>
          <View
            className="px-3 py-1.5 rounded-full text-white text-[12px] flex-row items-center gap-1"
            style={{
              backgroundColor: primary.base,
            }}
          >
            <TagIcon color="white" size={14} />

            <Text className="text-white capitalize">{tran(project.share_type)}</Text>
          </View>
          <Text className="px-3 py-1.5 bg-white text-heading-stock rounded-full capitalize">{tran(project.type.name)}</Text>
          <Pressable
            onPress={handleWishlistToggle}
            className={`ms-auto p-2 rounded-full inline-flex-row items-center justify-center transition-colors ${
              inWishlist ? "bg-red-500 text-white" : "bg-white text-heading-stock hover:bg-red-50 hover:text-red-500"
            }`}
          >
            <HeartIcon weight={inWishlist ? "fill" : "regular"} size={18} color={inWishlist ? "white" : primary.base} />
          </Pressable>
        </View>
        <View className="rounded-t-2xl overflow-hidden">
          <ImageLoader src={project.thumbnail} alt={project.title} className="w-full h-[200px]" />
        </View>

        {/* Floating share badge */}
        <View className="absolute bottom-2 right-2 bg-white rounded-lg subcard-shadow p-3 flex flex-col items-center gap-3">
          <View className="flex-row items-center gap-2">
            <Text
              style={{
                backgroundColor: primary.base,
              }}
              className="text-2xl rounded-full p-2 items-center justify-center w-10 h-10"
            >
              <FileTextIcon color="white" />
            </Text>
            <View className="flex flex-col">
              <Text
                style={{
                  color: primary.base,
                }}
                className="text-lg font-manrope-medium"
              >
                {translateNumber(project.share_sold)}/{translateNumber(project.number_of_shares)}
              </Text>
              <Text className="text-sm text-slate-500">{tran("Shares")}</Text>
            </View>
          </View>
          <Text className="border-t border-dotted border-slate-500 pt-2 text-sm font-medium text-slate-700">{translateNumber(calculateTimeRemaining())}</Text>
        </View>
      </View>

      <View className="p-4">
        <Text className="text-xl font-manrope-bold mb-4">{tran(project.title)}</Text>

        <View className="mt-auto space-y-6">
          <View className="flex-row items-center gap-6 text-sm pb-3">
            <View className="flex-row items-center gap-1.5">
              <MapPinIcon size={18} />
              <Text className="text-slate-500">{tran(project.city.name)}</Text>
            </View>
            <View className="flex-row items-center gap-1.5">
              <UsersThreeIcon size={18} />
              <Text className="text-slate-500">
                {translateNumber(project.total_investors)} {tran("Investors")}
              </Text>
            </View>
          </View>

          {/* Stats Grid with Container Query */}
          <View className="">
            <View className="flex-row justify-between items-center gap-2">
              <View
                className="p-2 rounded-lg border flex-1 justify-center items-center"
                style={{
                  borderColor: primary[30],
                  backgroundColor: primary[10],
                }}
              >
                <View className="flex-row items-center justify-center gap-1 ">
                  <CoinsIcon size={18} />
                  <Text className="font-manrope-bold ">
                    {currency.symbol}
                    {translateNumber(project.share_value)}
                  </Text>
                </View>
                <Text className="text-[10px] block mt-1 leading-none text-slate-600">{tran("Per Share")}</Text>
              </View>

              <View
                className="p-2 rounded-lg border flex-1 justify-center items-center"
                style={{
                  borderColor: secondary[30],
                  backgroundColor: secondary[10],
                }}
              >
                <View className="flex-row items-center justify-center gap-1 ">
                  <ChartLineUpIcon size={18} />
                  <Text className="font-manrope-bold ">{translateNumber(project.roi)}%</Text>
                </View>
                <Text className="text-[10px] block mt-1 leading-none text-slate-600">{tran("ROI/yr")}</Text>
              </View>
              <View className="p-2 rounded-lg border flex-1 justify-center items-center border-yellow-300 bg-yellow-50">
                <View className="flex-row items-center justify-center gap-1 text-lg">
                  <HourglassLowIcon size={18} />
                  <Text className="font-manrope-bold ">{calculateDuration()}</Text>
                </View>
                <Text className="text-[10px] block mt-1 leading-none text-slate-600">{tran("Duration")}</Text>
              </View>
            </View>
            <View className="flex-row gap-3 pt-5">
              <View className="flex-1">
                <Button onPress={handleInvest} text={tran("Invest Now")} />
              </View>
              <Pressable
                onPress={() => router.push(`/(screens)/project-details?project=${project.slug}`)}
                className="w-12 h-12 rounded-full border items-center justify-center -rotate-45"
                style={{
                  borderColor: primary[20],
                  backgroundColor: primary[10],
                }}
              >
                <ArrowRightIcon color={primary.base} size={20} weight="bold" />
              </Pressable>
            </View>
          </View>
        </View>
      </View>
    </Pressable>
  );
}
