import LogoutModal from "@/components/sections/LogoutModal";
import DashboardCharts from "@/components/sections/dashboard-charts";
import FeatureSections from "@/components/sections/feature-section";
import RecentActivity from "@/components/sections/recent-activity";
import ImageLoader from "@/components/ui/ImageLoader";
import AppText from "@/components/ui/app-text";
import { useGetQuery } from "@/hooks/mutate/useGetQuery";
import { useColor } from "@/hooks/useColor";
import { useCurrency } from "@/hooks/useCurrency";
import { useAuthStore } from "@/providers/AuthStoreProviders";
import { useTranslations } from "@/providers/TranslationProviders";
import { router } from "expo-router";
import {
  ArrowDownIcon,
  ArrowsLeftRightIcon,
  ArrowUpIcon,
  BellSimpleIcon,
  BuildingApartmentIcon,
  ChartLineUpIcon,
  EyeIcon,
  EyeSlashIcon,
  TrendUpIcon,
  WalletIcon,
} from "phosphor-react-native";
import { useCallback, useState } from "react";
import { Pressable, RefreshControl, ScrollView, Text, View } from "react-native";
import { useSafeAreaInsets } from "react-native-safe-area-context";

export default function HomeScreen() {
  const [logoutModal, setLogoutModal] = useState(false);
  const [balanceVisible, setBalanceVisible] = useState(true);
  const insets = useSafeAreaInsets();
  const { primary, success } = useColor();
  const { user, getUser } = useAuthStore((state) => state);
  const { currency } = useCurrency();
  const { tran, translateNumber } = useTranslations();

  // Fetch Summary Data
  const {
    data: summary,
    isLoading,
    refetch,
    isFetching,
  } = useGetQuery({
    url: "/client/summary",
  });

  // Fetch notifications to show unread badge
  const { data: notifData } = useGetQuery({
    url: "/client/notifications?page=1",
    queryKey: ["notifications", 1],
  });
  const unreadCount = notifData?.data?.filter((n: any) => !n.read_at).length ?? 0;

  const overview = summary?.overview;
  const portfolioSummary = summary?.portfolio_summary;

  const onRefresh = useCallback(async () => {
    await Promise.all([refetch(), getUser()]);
  }, [refetch, getUser]);


  return (
    <View className="flex-1 bg-slate-50" style={{ paddingTop: insets.top }}>
      <ScrollView
        showsVerticalScrollIndicator={false}
        refreshControl={<RefreshControl refreshing={isFetching} onRefresh={onRefresh} tintColor={primary.base} />}
      >
        {/* Header */}
        <View className="flex-row justify-between items-center px-5 pt-3 pb-4">
          <Pressable onPress={() => router.push("/(tabs)/account")} className="flex-row items-center gap-3">
            <View className="rounded-2xl overflow-hidden border-2 border-white shadow-sm" style={{ shadowColor: primary.base, shadowOpacity: 0.15, shadowRadius: 8, elevation: 3 }}>
              <ImageLoader src={user?.avatar} alt="" height={48} width={48} className="size-12 object-cover" />
            </View>
            <View>
              <AppText className="font-manrope text-slate-400 text-xs">{tran("Welcome back")}</AppText>
              <AppText size="lg" className="font-manrope-bold text-slate-900 capitalize">
                {user?.first_name ?? tran("User")}
              </AppText>
            </View>
          </Pressable>
          <Pressable onPress={() => router.push("/(screens)/notifications")} className="rounded-2xl p-3 bg-white border border-slate-100 relative shadow-sm" style={{ shadowColor: "#000", shadowOpacity: 0.04, shadowRadius: 8, elevation: 2 }}>
            <View pointerEvents="none">
              <BellSimpleIcon size={20} color="#334155" weight="bold" />
            </View>
            {unreadCount > 0 && (
              <View className="absolute -top-1.5 -right-1.5 rounded-full min-w-[20px] h-[20px] items-center justify-center px-1 border-2 border-slate-50" style={{ backgroundColor: "#ef4444" }}>
                <Text className="text-white text-[9px] font-manrope-extrabold">{unreadCount > 99 ? "99+" : unreadCount}</Text>
              </View>
            )}
          </Pressable>
        </View>

        {/* Main Balance Card */}
        <View className="px-5 pb-2">
          <View className="rounded-[28px] overflow-hidden" style={{ backgroundColor: primary.base }}>
            <View className="p-6">
              <View className="flex-row justify-between items-center mb-1">
                <View className="flex-row items-center gap-2">
                  <WalletIcon size={16} color="rgba(255,255,255,0.7)" weight="fill" />
                  <Text className="text-white/70 font-manrope-bold text-xs uppercase tracking-widest">{tran("Total Balance")}</Text>
                </View>
                <Pressable onPress={() => setBalanceVisible(!balanceVisible)} hitSlop={12} className="p-1">
                  <View pointerEvents="none">
                    {balanceVisible ? <EyeIcon size={18} color="rgba(255,255,255,0.7)" weight="bold" /> : <EyeSlashIcon size={18} color="rgba(255,255,255,0.7)" weight="bold" />}
                  </View>
                </Pressable>
              </View>

              <Text className="text-white font-manrope-extrabold text-[36px] leading-tight tracking-tight pt-1">
                {balanceVisible ? `${currency.symbol}${translateNumber(user?.balance || 0)}` : `${currency.symbol}••••••`}
              </Text>

              {overview && (
                <View className="flex-row items-center gap-1.5 pt-1.5">
                  <View className="flex-row items-center gap-1 bg-white/15 px-2.5 py-1 rounded-full">
                    <TrendUpIcon size={12} color="#fff" weight="bold" />
                    <Text className="text-white font-manrope-bold text-[11px]">
                      +{currency.symbol}
                      {translateNumber(overview?.monthly_investment || 0)}
                    </Text>
                  </View>
                  <Text className="text-white/50 font-manrope-medium text-[11px]">{tran("this month")}</Text>
                </View>
              )}

              {/* Action Buttons */}
              <View className="flex-row gap-3 pt-6">
                <Pressable onPress={() => router.push("/wallet/deposit")} className="flex-row items-center justify-center gap-2 bg-white px-4 py-3.5 rounded-2xl flex-1">
                  <View pointerEvents="none">
                    <ArrowDownIcon size={16} color={primary.base} weight="bold" />
                  </View>
                  <Text className="font-manrope-bold text-sm tracking-tight" style={{ color: primary.base }}>
                    {tran("Deposit")}
                  </Text>
                </Pressable>

                <Pressable onPress={() => router.push("/wallet/withdraw")} className="flex-row items-center justify-center gap-2 bg-white/15 border border-white/20 px-4 py-3.5 rounded-2xl flex-1">
                  <View pointerEvents="none">
                    <ArrowUpIcon size={16} color="white" weight="bold" />
                  </View>
                  <Text className="text-white font-manrope-bold text-sm tracking-tight">{tran("Withdraw")}</Text>
                </Pressable>
              </View>
            </View>
          </View>
        </View>

        {/* Portfolio Overview */}
        <View className="px-5 pt-4">
          <View className="bg-white rounded-[24px] p-5 border border-slate-100 " style={{ shadowColor: "#000", shadowOpacity: 0.03, shadowRadius: 12, elevation: 2 }}>
            <View className="flex-row justify-between items-center pb-4">
              <Text className="text-slate-400 font-manrope-bold text-xs uppercase tracking-wider">{tran("Portfolio Value")}</Text>
              <Pressable onPress={() => router.push("/upcoming-payouts")} className="flex-row items-center gap-1">
                <Text className="font-manrope-bold text-xs" style={{ color: primary.base }}>
                  {tran("Details")}
                </Text>
              </Pressable>
            </View>

            {isLoading ? (
              <View className="h-10 w-40 bg-slate-100 rounded-xl mb-3" />
            ) : (
              <Text className="text-3xl font-manrope-extrabold text-slate-900 pb-1">
                {currency.symbol}
                {translateNumber(overview?.total_investment || 0)}
              </Text>
            )}

            {/* Stats Row */}
            <View className="flex-row gap-2.5 pt-4">
              <View className="flex-1 bg-slate-50 p-3.5 rounded-2xl items-center">
                <Text className="text-lg font-manrope-extrabold" style={{ color: primary.base }}>
                  {currency.symbol}
                  {translateNumber(overview?.total_roi_received || 0)}
                </Text>
                <Text className="uppercase text-[9px] text-slate-400 font-manrope-bold tracking-wider pt-1">{tran("Total ROI")}</Text>
              </View>
              <View className="flex-1 bg-slate-50 p-3.5 rounded-2xl items-center">
                <Text className="text-lg font-manrope-extrabold text-slate-900">{translateNumber(portfolioSummary?.total_projects || 0)}</Text>
                <Text className="uppercase text-[9px] text-slate-400 font-manrope-bold tracking-wider pt-1">{tran("Projects")}</Text>
              </View>
              <View className="flex-1 bg-slate-50 p-3.5 rounded-2xl items-center">
                <Text className="text-lg font-manrope-extrabold" style={{ color: success.base }}>
                  {translateNumber(portfolioSummary?.avg_roi || 0)}%
                </Text>
                <Text className="uppercase text-[9px] text-slate-400 font-manrope-bold tracking-wider pt-1">{tran("Avg ROI")}</Text>
              </View>
            </View>
          </View>
        </View>

        {/* Quick Actions */}
        <View className="px-5 pt-5">
          <View className="flex-row gap-3">
            {[
              { label: tran("Invest"), icon: BuildingApartmentIcon, color: "#0ea5e9", bg: "#f0f9ff", route: "/projects" },
              { label: tran("Marketplace"), icon: ArrowsLeftRightIcon, color: "#8b5cf6", bg: "#f5f3ff", route: "/marketplace" },
              { label: tran("My Shares"), icon: WalletIcon, color: "#f59e0b", bg: "#fffbeb", route: "/my-shares" },
              { label: tran("Analytics"), icon: ChartLineUpIcon, color: "#10b981", bg: "#f0fdf4", route: "/upcoming-payouts" },
            ].map((action) => (
              <Pressable
                key={action.route}
                onPress={() => router.push(action.route as any)}
                className="flex-1 bg-white rounded-2xl py-4 items-center gap-2 border border-slate-100 shadow-sm"
                style={{ shadowColor: "#000", shadowOpacity: 0.02, shadowRadius: 8, elevation: 1 }}
              >
                <View className="p-2.5 rounded-xl" style={{ backgroundColor: action.bg }}>
                  <action.icon size={22} color={action.color} weight="duotone" />
                </View>
                <Text className="text-[11px] font-manrope-bold text-slate-600">{action.label}</Text>
              </Pressable>
            ))}
          </View>
        </View>

        {/* Charts */}
        <View className="px-5">
          <DashboardCharts />
        </View>

        {/* Featured Projects */}
        <View className="pl-5">
          <FeatureSections />
        </View>

        {/* Recent Activity */}
        <View className="px-5">
          <RecentActivity />
        </View>

        <View className="h-8" />
      </ScrollView>

      {logoutModal && <LogoutModal visible={logoutModal} setVisible={setLogoutModal} />}
    </View>
  );
}
