import { useCurrency } from "@/hooks/useCurrency";
import { useAuthStore } from "@/providers/AuthStoreProviders";
import { useInvestModal } from "@/providers/InvestModalProvider";
import { useTranslations } from "@/providers/TranslationProviders";
import { Link } from "expo-router";
import { useState } from "react";
import { Pressable, Text, View } from "react-native";
import ImageLoader from "../ui/ImageLoader";
import {
  ChartLineUpIcon,
  CoinsIcon,
  FileTextIcon,
  HourglassLowIcon,
  MapPinIcon,
  TagIcon,
  UsersThreeIcon,
  XIcon,
} from "phosphor-react-native";
import { useColor } from "@/hooks/useColor";
import Button from "../ui/Button";

interface WishlistItem {
  id?: number;
  project_id?: number;
  project?: any;
  title?: string;
  slug?: string;
  code?: string;
  thumbnail?: string;
  [key: string]: any;
}

interface WishlistCardProps {
  item: WishlistItem;
  onRemove: (id: number) => void;
}

export default function WishlistCard({ item, onRemove }: WishlistCardProps) {
  const { primary, secondary } = useColor();
  const { tran, translateNumber } = useTranslations();
  const { currency } = useCurrency();
  const { openModal: investModal } = useInvestModal();
  const { isAuthenticated } = useAuthStore((state) => state);
  const [quantity] = useState(1);

  // Handle nested project structure
  const project = item.project || item;

  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`;
  };

  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 = () => {
    if (!isAuthenticated) {
      // router.push(`/sign-in?redirect=${pathname}`);
      // toast.warning("Please login to Invest in this project.");
      return;
    }
    investModal({
      title: project.title,
      slug: project.slug,
      share_count: quantity,
      share_value: project.share_value,
      max: project.number_of_shares - project.share_sold,
    });
  };

  const handleRemoveClick = () => {
    onRemove(item.id || item.project_id || 0);
  };

  return (
    <View
      className="bg-white rounded-2xl border overflow-hidden"
      style={{
        borderColor: primary[20],
      }}
    >
      {/* Fixed-height image section */}
      <View className="relative @container overflow-hidden">
        {/* 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>
        </View>
        <Pressable
          onPress={handleRemoveClick}
          className="bg-red-500 rounded-full absolute top-2 end-2 z-10 p-2"
        >
          <XIcon color="white" size={16} weight="bold" />
        </Pressable>
        <View className="rounded-t-2xl overflow-hidden">
          <ImageLoader
            src={project.thumbnail}
            alt={project.title}
            width={302}
            height={201}
            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>

          {/* Buttons - Always at the bottom */}
          <View className="pt-4">
            <Button onPress={handleInvest} text="Invest Now" />
          </View>
        </View>
      </View>
    </View>
  );
}
