import InvestedShareCard from "@/components/cards/invested-share-card";
import BackButtonTitle from "@/components/ui/BackButtonTitle";
import { useGetQuery } from "@/hooks/mutate/useGetQuery";
import { useColor } from "@/hooks/useColor";
import { useCurrency } from "@/hooks/useCurrency";
import { ListShareModalProvider } from "@/providers/ListShareModalProvider";
import { useTranslations } from "@/providers/TranslationProviders";
import { ProjectDetails } from "@/types/project";
import { CalendarIcon, ChartPieSliceIcon, FileIcon, WalletIcon } from "phosphor-react-native";
import { useState } from "react";
import { Pressable, RefreshControl, ScrollView, Text, View } from "react-native";
import { SafeAreaView } from "react-native-safe-area-context";

export default function MySharesScreen() {
  const { primary } = useColor();
  const { data: statsData } = useGetQuery({
    url: "/client/projects/stats",
  });
  const { currency } = useCurrency();
  const { tran, translateNumber } = useTranslations();
  const [activeTab, setActiveTab] = useState<"all" | "fixed" | "renewable" | "infinite">("all");

  const {
    data: projectsData,
    isLoading,
    refetch,
  } = useGetQuery({
    url: `/client/projects${activeTab !== "all" ? `?share_type=${activeTab}` : ""}`,
  });

  const tabs = [
    { id: "all", label: "All Shares" },
    { id: "fixed", label: "Fixed" },
    { id: "renewable", label: "Renewable" },
    { id: "infinite", label: "Infinite" },
  ] as const;

  const dashboardStats = [
    {
      icon: FileIcon,
      title: "Active Shares",
      value: statsData?.active_shares,
    },
    {
      icon: WalletIcon,
      title: "Listed Shares",
      value: statsData?.listed_shares,
    },
    {
      icon: ChartPieSliceIcon,
      title: "Portfolio Value",
      value: currency.symbol + (statsData?.portfolio_value ?? 0).toFixed(2),
    },
    {
      icon: CalendarIcon,
      title: "Total ROI Received",
      value: currency.symbol + (statsData?.roi_received ?? 0).toFixed(2),
    },
  ];

  return (
    <ListShareModalProvider>
      <ScrollView refreshControl={<RefreshControl refreshing={isLoading} onRefresh={refetch} />} className="bg-white px-6">
        <SafeAreaView>
          <BackButtonTitle title="My Shares" />
          <View className="pt-8 flex-row flex-wrap gap-y-3 ">
            {dashboardStats.map((stat, idx) => (
              <View
                key={`${idx}`}
                className="w-1/2"
                style={{
                  paddingEnd: idx % 2 ? 0 : 12,
                }}
              >
                <View
                  className="rounded-2xl p-4 border border-slate-100 bg-white shadow-sm shadow-slate-100/50"
                  style={
                    {
                      // border and background matched to standard white card
                    }
                  }
                >
                  <View className="flex-row items-center justify-between gap-2">
                    <View className="space-y-1 flex-1">
                      <Text className="text-xs font-manrope text-slate-500 uppercase tracking-wide">{tran(stat.title)}</Text>
                      <Text className="text-[17px] font-manrope-extrabold text-slate-900 pt-0.5">{translateNumber(stat.value)}</Text>
                    </View>
                    <View className="w-10 h-10 rounded-xl flex items-center justify-center" style={{ backgroundColor: primary[10] }}>
                      <stat.icon color={primary.base} size={20} weight="duotone" />
                    </View>
                  </View>
                </View>
              </View>
            ))}
          </View>

          {/* Filters */}
          <View className="pt-6">
            <ScrollView horizontal showsHorizontalScrollIndicator={false} className="flex-row">
              {tabs.map((tab) => {
                const isActive = activeTab === tab.id;
                return (
                  <Pressable
                    key={tab.id}
                    onPress={() => setActiveTab(tab.id as any)}
                    className="px-4 py-2.5 rounded-xl mr-2"
                    style={{
                      backgroundColor: isActive ? primary.base : "#f1f5f9",
                    }}
                  >
                    <Text className="text-sm font-manrope-bold" style={{ color: isActive ? "white" : "#64748b" }}>
                      {tran(tab.label)}
                    </Text>
                  </Pressable>
                );
              })}
            </ScrollView>
          </View>

          {/* Project List */}
          <View className="pt-6 gap-y-4">
            {projectsData?.data?.map((project: ProjectDetails) => (
              <InvestedShareCard key={project.id} project={project} />
            ))}
          </View>
        </SafeAreaView>
      </ScrollView>
    </ListShareModalProvider>
  );
}
