import PayoutsModal from "@/components/modals/payouts-modal";
import TransferShareModal from "@/components/modals/transfer-share-modal";
import ReviewModal from "@/components/sections/details/add-review-modal";
import BackButtonTitle from "@/components/ui/BackButtonTitle";
import BottomSheet from "@/components/ui/BottomSheet";
import Button from "@/components/ui/Button";
import NoDataFound from "@/components/ui/no-data-found";
import { API_BASE_URL } from "@/configs";
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 { formatDate } from "@/utils/helper";
import * as FileSystem from "expo-file-system/legacy";
import { router, useLocalSearchParams } from "expo-router";
import * as Sharing from "expo-sharing";
import {
  BuildingsIcon,
  CalendarIcon,
  CheckIcon,
  DotsThreeIcon,
  DownloadSimpleIcon,
  EyeIcon,
  FileTextIcon,
  InfoIcon,
  ListChecksIcon,
  MapPinLineIcon,
  SwapIcon,
  TrendUpIcon,
} from "phosphor-react-native";
import { useState } from "react";
import { ActivityIndicator, Platform, Pressable, RefreshControl, ScrollView, Text, TouchableOpacity, View } from "react-native";
import { showToast } from "@/utils/toast";
import { SafeAreaView } from "react-native-safe-area-context";

export default function MySharesDetailsScreen() {
  const { primary, secondary, success } = useColor();
  const { tran, translateNumber } = useTranslations();
  const { currency } = useCurrency();
  const { slug } = useLocalSearchParams<{ slug: string }>();

  const [isReviewModalOpen, setIsReviewModalOpen] = useState(false);
  const [isPayoutsModalOpen, setIsPayoutsModalOpen] = useState(false);
  const [isTransferModalOpen, setIsTransferModalOpen] = useState(false);
  const [isOptionsOpen, setIsOptionsOpen] = useState(false);
  const [selectedShare, setSelectedShare] = useState<any>(null);
  const [downloadingId, setDownloadingId] = useState<number | null>(null);

  const { token } = useAuthStore((state) => state);

  const {
    data: project,
    isLoading,
    refetch,
    isFetching,
  } = useGetQuery({
    url: `/client/projects/${slug}`,
  });

  if (isLoading) {
    return (
      <View className="flex-1 bg-white justify-center items-center">
        <ActivityIndicator size="large" color={primary.base} />
      </View>
    );
  }

  if (!project) {
    return (
      <SafeAreaView className="flex-1 bg-white">
        <View className="px-6">
          <BackButtonTitle title={tran("Details Not Found")} />
        </View>
        <NoDataFound title={tran("Project Not Found")} description={tran("We couldn't find the details for this investment.")} />
      </SafeAreaView>
    );
  }

  const hasReview = !!project.user_review;

  const stats = [
    {
      label: "Active Shares",
      value: translateNumber(project.summary.active_shares),
      icon: FileTextIcon,
      color: primary.base,
      bg: primary[10],
    },
    {
      label: "Listed Shares",
      value: translateNumber(project.summary.listed_shares),
      icon: ListChecksIcon,
      color: "#6366f1",
      bg: "#eef2ff",
    },
    {
      label: "Sold Shares",
      value: translateNumber(project.summary.sold_shares),
      icon: CheckIcon,
      color: success.base,
      bg: success[10],
    },
    {
      label: "ROI Received",
      value: `${currency.symbol}${translateNumber(project.summary.total_roi_received.toFixed(2))}`,
      icon: TrendUpIcon,
      color: secondary.base,
      bg: secondary[10],
    },
  ];

  const handleDownloadDocument = async (share: any) => {
    if (!share?.id || downloadingId) return;
    setDownloadingId(share.id);
    try {
      const safeFileName = `Ownership_${(share.share_number || share.id).toString().replace(/[^a-zA-Z0-9._-]/g, "_")}.pdf`;
      const downloadUrl = `${API_BASE_URL}/client/projects/${slug}/share/${share.id}/download?token=${encodeURIComponent(token ?? "")}`;
      const fileUri = `${FileSystem.documentDirectory}${safeFileName}`;

      console.log("📥 Downloading:", downloadUrl);
      console.log("📥 Saving to:", fileUri);

      const result = await FileSystem.downloadAsync(downloadUrl, fileUri, {
        headers: {
          Accept: "application/pdf",
          Authorization: `Bearer ${token ?? ""}`,
        },
      });

      console.log("📥 Download result:", result.status, result.uri, result.headers);

      if (result.status < 200 || result.status >= 300) {
        const text = await FileSystem.readAsStringAsync(result.uri).catch(() => "");
        console.warn("Download non-2xx body:", text?.slice(0, 500));
        showToast({ type: "error", text: tran("Failed to download document") + ` (${result.status})` });
        return;
      }

      if (Platform.OS === "android") {
        const permissions = await FileSystem.StorageAccessFramework.requestDirectoryPermissionsAsync();
        if (permissions.granted) {
          const base64 = await FileSystem.readAsStringAsync(result.uri, { encoding: FileSystem.EncodingType.Base64 });
          const destUri = await FileSystem.StorageAccessFramework.createFileAsync(permissions.directoryUri, safeFileName, "application/pdf");
          await FileSystem.writeAsStringAsync(destUri, base64, { encoding: FileSystem.EncodingType.Base64 });
          showToast({ type: "success", text: tran("Document saved successfully") });
          return;
        }
        // User denied folder permission — fall back to share dialog
      }

      if (await Sharing.isAvailableAsync()) {
        await Sharing.shareAsync(result.uri, { mimeType: "application/pdf", dialogTitle: tran("Ownership Document"), UTI: "com.adobe.pdf" });
      } else {
        showToast({ type: "success", text: tran("Saved to") + " " + result.uri });
      }
    } catch (err: any) {
      console.warn("Download failed:", err, err?.message, err?.code);
      showToast({ type: "error", text: err?.message || tran("Failed to download document") });
    } finally {
      setDownloadingId(null);
    }
  };

  return (
    <SafeAreaView className="flex-1 bg-white" edges={["top"]}>
      <View className="px-6 mb-4 flex-row items-center justify-between">
        <BackButtonTitle title={tran("My Share Details")} />
        <Pressable onPress={() => setIsReviewModalOpen(true)} className="bg-primary px-3 py-2 rounded-xl flex-row items-center gap-1.5 shadow-sm ">
          <View>
            <Text className=" font-manrope-bold text-[11px] uppercase tracking-wider">{hasReview ? tran("Edit Review") : tran("Add Review")}</Text>
          </View>
        </Pressable>
      </View>

      <ScrollView
        showsVerticalScrollIndicator={false}
        refreshControl={<RefreshControl refreshing={isFetching} onRefresh={refetch} tintColor={primary.base} />}
        contentContainerStyle={{ paddingBottom: 60 }}
      >
        {/* Header Section */}
        <View className="px-6 pt-2 pb-6">
          <View className="flex-row items-start gap-4">
            <View className="w-16 h-16 rounded-2xl items-center justify-center shadow-lg shadow-black/5" style={{ backgroundColor: primary[10] }}>
              <BuildingsIcon size={32} color={primary.base} weight="duotone" />
            </View>
            <View className="flex-1">
              <Text className="text-2xl font-manrope-extrabold text-slate-900 leading-tight">{tran(project.title)}</Text>
              <View className="flex-row items-center gap-1.5 mt-1">
                <MapPinLineIcon size={16} color="#64748b" />
                <Text className="text-sm font-manrope-semibold text-slate-500">{tran(project.city.name)}</Text>
              </View>
            </View>
          </View>
        </View>

        {/* Stats Grid */}
        <View className="px-6 flex-row flex-wrap gap-3">
          {stats.map((stat, index) => (
            <View key={index} className="rounded-2xl w-[48%] p-4 border border-slate-50 shadow-sm shadow-slate-100" style={{ backgroundColor: "white" }}>
              <View className="w-10 h-10 rounded-xl items-center justify-center mb-3" style={{ backgroundColor: stat.bg }}>
                <stat.icon color={stat.color} size={20} weight="bold" />
              </View>
              <Text className="text-[10px] font-manrope-bold text-slate-400 uppercase tracking-widest mb-0.5">{tran(stat.label)}</Text>
              <Text className="text-lg font-manrope-extrabold text-slate-900">{stat.value}</Text>
            </View>
          ))}
        </View>

        {/* Shares Table Section */}
        <View className="px-6 pt-10">
          <View className="flex-row items-center justify-between mb-4">
            <Text className="text-xl font-manrope-extrabold text-slate-900">{tran("Your Shares")}</Text>
            <Pressable onPress={() => router.push(`/(screens)/my-shares?search=${project.code}`)}>
              <Text className="text-xs font-manrope-bold text-primary uppercase tracking-widest">{tran("View All")}</Text>
            </Pressable>
          </View>

          <View className="gap-3">
            {project.shares.slice(0, 3).map((share: any) => (
              <View key={share.id} className="bg-white border border-slate-100 rounded-2xl p-4 shadow-sm shadow-slate-50">
                <View className="flex-row justify-between items-center mb-3">
                  <View>
                    <Text className="text-[10px] font-manrope-bold text-slate-400 uppercase tracking-widest mb-0.5">{tran("Share Number")}</Text>
                    <Text className="text-base font-manrope-bold text-slate-900">{share.share_number}</Text>
                  </View>
                  <View className="flex-row items-center gap-2">
                    <View className="bg-emerald-50 px-3 py-1 rounded-full">
                      <Text className="text-[10px] font-manrope-extrabold text-emerald-600 uppercase tracking-widest">{tran(share.status)}</Text>
                    </View>
                    <TouchableOpacity
                      onPress={() => {
                        setSelectedShare(share);
                        setIsOptionsOpen(true);
                      }}
                      hitSlop={{ top: 20, bottom: 20, left: 20, right: 20 }}
                      className="w-10 h-10 rounded-full bg-slate-50 items-center justify-center"
                    >
                      <DotsThreeIcon size={24} color="#64748b" weight="bold" />
                    </TouchableOpacity>
                  </View>
                </View>

                <View className="flex-row justify-between pt-3 border-t border-slate-50">
                  <View>
                    <Text className="text-[10px] font-manrope-bold text-slate-400 uppercase tracking-widest mb-0.5">{tran("Batch ID")}</Text>
                    <Text className="text-xs font-manrope-semibold text-slate-600">{share.batch_id}</Text>
                  </View>
                  <View className="items-end">
                    <Text className="text-[10px] font-manrope-bold text-slate-400 uppercase tracking-widest mb-0.5">{tran("Purchased")}</Text>
                    <Text className="text-xs font-manrope-semibold text-slate-600">{formatDate(share.purchased_at)}</Text>
                  </View>
                </View>
              </View>
            ))}
          </View>
        </View>

        {/* Received Payouts Section */}
        <View className="px-6 pt-10">
          <View className="flex-row items-center justify-between mb-4">
            <Text className="text-xl font-manrope-extrabold text-slate-900">{tran("Received Payouts")}</Text>
            <Pressable onPress={() => router.push(`/(screens)/roi-recieved?search=${project.code}`)}>
              <Text className="text-xs font-manrope-bold text-primary uppercase tracking-widest">{tran("View All")}</Text>
            </Pressable>
          </View>

          {project.received_roi.length > 0 ? (
            <View className="gap-3">
              {project.received_roi.slice(0, 3).map((payout: any) => (
                <View key={payout.id} className="bg-slate-50 border border-slate-100 rounded-2xl p-4 flex-row items-center gap-4">
                  <View className="w-12 h-12 rounded-xl bg-white items-center justify-center shadow-sm">
                    <TrendUpIcon size={24} color={success.base} weight="bold" />
                  </View>
                  <View className="flex-1">
                    <View className="flex-row justify-between items-center mb-1">
                      <Text className="text-sm font-manrope-bold text-slate-900">
                        {tran("Share")}: {payout.share.share_number}
                      </Text>
                      <Text className="text-base font-manrope-extrabold text-emerald-600">
                        +{currency.symbol}
                        {translateNumber(payout.amount.toFixed(2))}
                      </Text>
                    </View>
                    <Text className="text-[10px] font-manrope-semibold text-slate-400 uppercase tracking-wider">
                      {tran("Paid on")} {formatDate(payout.paid_at)}
                    </Text>
                  </View>
                </View>
              ))}
            </View>
          ) : (
            <View className="p-8 bg-slate-50 rounded-3xl items-center border border-dashed border-slate-200">
              <Text className="text-slate-400 font-manrope-semibold">{tran("No payouts received yet")}</Text>
            </View>
          )}
        </View>

        {/* Upcoming Payouts Section */}
        <View className="px-6 pt-10">
          <View className="flex-row items-center justify-between mb-4">
            <Text className="text-xl font-manrope-extrabold text-slate-900">{tran("Upcoming Payouts")}</Text>
            <Pressable onPress={() => router.push(`/(screens)/upcoming-payouts?search=${project.code}`)}>
              <Text className="text-xs font-manrope-bold text-primary uppercase tracking-widest">{tran("View All")}</Text>
            </Pressable>
          </View>

          {project.upcoming_roi.length > 0 ? (
            <View className="gap-3">
              {project.upcoming_roi.slice(0, 3).map((payout: any) => (
                <View key={payout.id} className="bg-white border border-slate-100 rounded-2xl p-4 flex-row items-center gap-4">
                  <View className="w-12 h-12 rounded-xl bg-slate-50 items-center justify-center">
                    <CalendarIcon size={24} color={primary.base} weight="bold" />
                  </View>
                  <View className="flex-1">
                    <View className="flex-row justify-between items-center mb-1">
                      <Text className="text-sm font-manrope-bold text-slate-900">
                        {tran("Share")}: {payout.share.share_number}
                      </Text>
                      <Text className="text-base font-manrope-extrabold text-slate-900">
                        {currency.symbol}
                        {translateNumber(payout.amount.toFixed(2))}
                      </Text>
                    </View>
                    <Text className="text-[10px] font-manrope-semibold text-slate-400 uppercase tracking-wider">
                      {tran("Due on")} {formatDate(payout.due_at)}
                    </Text>
                  </View>
                </View>
              ))}
            </View>
          ) : (
            <View className="p-8 bg-slate-50 rounded-3xl items-center border border-dashed border-slate-200">
              <Text className="text-slate-400 font-manrope-semibold">{tran("No upcoming payouts scheduled")}</Text>
            </View>
          )}
        </View>

        {/* Project Summary Section */}
        <View className="px-6 pt-12">
          <View className="bg-slate-900 rounded-[32px] p-7 shadow-2xl shadow-slate-900/50">
            <View className="flex-row items-center justify-between mb-8">
              <View className="flex-row items-center gap-3">
                <View className="w-11 h-11 rounded-2xl bg-white/10 items-center justify-center border border-white/10">
                  <InfoIcon size={24} color="white" weight="duotone" />
                </View>
                <Text className="text-xl font-manrope-extrabold text-white">{tran("Project Summary")}</Text>
              </View>
              <View className="bg-white/10 px-3 py-1 rounded-lg border border-white/10">
                <Text className="text-[10px] font-manrope-bold text-white uppercase tracking-widest">{project.code}</Text>
              </View>
            </View>

            <View className="flex-row flex-wrap gap-y-7">
              <View className="w-1/2 pr-2">
                <Text className="text-[10px] font-manrope-bold text-slate-500 uppercase tracking-widest mb-1.5">{tran("Share Type")}</Text>
                <View className="bg-slate-800 self-start px-2 py-0.5 rounded-md border border-white/5">
                  <Text className="text-[13px] font-manrope-extrabold text-white capitalize">{tran(project.share_type)}</Text>
                </View>
              </View>
              <View className="w-1/2 pl-2">
                <Text className="text-[10px] font-manrope-bold text-slate-500 uppercase tracking-widest mb-1.5">{tran("Share Value")}</Text>
                <Text className="text-base font-manrope-extrabold text-white">
                  {currency.symbol}
                  {translateNumber(project.share_value?.toFixed(2) || "0")}
                </Text>
              </View>
              <View className="w-1/2 pr-2">
                <Text className="text-[10px] font-manrope-bold text-slate-500 uppercase tracking-widest mb-1.5">{tran("ROI Rate")}</Text>
                <Text className="text-base font-manrope-extrabold text-emerald-400">
                  {translateNumber(project.roi?.toString() || "0")}% / {tran("yearly")}
                </Text>
              </View>
              <View className="w-1/2 pl-2">
                <Text className="text-[10px] font-manrope-bold text-slate-500 uppercase tracking-widest mb-1.5">{tran("Distribution")}</Text>
                <Text className="text-base font-manrope-extrabold text-white capitalize">{tran(project.roi_distribution)}</Text>
              </View>
              <View className="w-1/2 pr-2">
                <Text className="text-[10px] font-manrope-bold text-slate-500 uppercase tracking-widest mb-1.5">{tran("Total Shares")}</Text>
                <Text className="text-base font-manrope-extrabold text-white">{translateNumber(project.number_of_shares)}</Text>
              </View>
              <View className="w-1/2 pl-2">
                <Text className="text-[10px] font-manrope-bold text-slate-500 uppercase tracking-widest mb-1.5">{tran("Project Size")}</Text>
                <Text className="text-base font-manrope-extrabold text-white">{translateNumber(project.size)} sqft</Text>
              </View>
              <View className="w-1/2 pr-2">
                <Text className="text-[10px] font-manrope-bold text-slate-500 uppercase tracking-widest mb-1.5">{tran("Effective Date")}</Text>
                <Text className="text-sm font-manrope-bold text-slate-300">{formatDate(project.effective_date)}</Text>
              </View>
              {project.maturity_date && (
                <View className="w-1/2 pl-2">
                  <Text className="text-[10px] font-manrope-bold text-slate-500 uppercase tracking-widest mb-1.5">{tran("Maturity Date")}</Text>
                  <Text className="text-sm font-manrope-bold text-slate-300">{formatDate(project.maturity_date)}</Text>
                </View>
              )}
            </View>
          </View>
        </View>

        <View className="px-6 pt-10">
          <Button text={tran("View Public Details")} type="secondary" onPress={() => router.push(`/(screens)/project-details?project=${project.slug}`)} />
        </View>
      </ScrollView>

      {/* Modals & Sheets */}
      <ReviewModal isOpen={isReviewModalOpen} onClose={() => setIsReviewModalOpen(false)} projectSlug={project.slug} existingReview={project.user_review} />

      <PayoutsModal isOpen={isPayoutsModalOpen} onClose={() => setIsPayoutsModalOpen(false)} share={selectedShare} payouts={selectedShare?.roi_payouts || []} />

      <TransferShareModal isOpen={isTransferModalOpen} onClose={() => setIsTransferModalOpen(false)} share_id={selectedShare?.id} project_id={project.id} share_value={project.share_value} />

      {/* Share Options BottomSheet */}
      <BottomSheet visible={isOptionsOpen} onClose={() => setIsOptionsOpen(false)} title={tran("Share Options")}>
        <View className="px-6 pb-10">
          <Text className="text-sm font-manrope-bold text-slate-400 uppercase tracking-widest mb-6">{tran("Select Action")}</Text>

          <View className="gap-3">
            <Pressable
              onPress={() => {
                setIsOptionsOpen(false);
                setIsPayoutsModalOpen(true);
              }}
              className="flex-row items-center gap-4 bg-slate-50 p-5 rounded-[24px] border border-slate-100 active:bg-slate-100"
            >
              <View className="w-12 h-12 rounded-2xl bg-primary/10 items-center justify-center">
                <EyeIcon size={24} color={primary.base} weight="bold" />
              </View>
              <View className="flex-1">
                <Text className="text-base font-manrope-extrabold text-slate-900">{tran("Payouts")}</Text>
                <Text className="text-xs font-manrope-medium text-slate-500 mt-0.5">{tran("View individual ROI history")}</Text>
              </View>
            </Pressable>

            <Pressable
              onPress={() => {
                setIsOptionsOpen(false);
                setIsTransferModalOpen(true);
              }}
              className="flex-row items-center gap-4 bg-slate-50 p-5 rounded-[24px] border border-slate-100 active:bg-slate-100"
            >
              <View className="w-12 h-12 rounded-2xl bg-secondary/10 items-center justify-center">
                <SwapIcon size={24} color={secondary.base} weight="bold" />
              </View>
              <View className="flex-1">
                <Text className="text-base font-manrope-extrabold text-slate-900">{tran("Transfer Share")}</Text>
                <Text className="text-xs font-manrope-medium text-slate-500 mt-0.5">{tran("Securely send to another user")}</Text>
              </View>
            </Pressable>

            <Pressable
              disabled={downloadingId === selectedShare?.id}
              onPress={() => {
                setIsOptionsOpen(false);
                handleDownloadDocument(selectedShare);
              }}
              className="flex-row items-center gap-4 bg-slate-50 p-5 rounded-[24px] border border-slate-100 active:bg-slate-100"
            >
              <View className="w-12 h-12 rounded-2xl bg-emerald-100 items-center justify-center">
                {downloadingId === selectedShare?.id ? (
                  <ActivityIndicator size="small" color={success.base} />
                ) : (
                  <DownloadSimpleIcon size={24} color={success.base} weight="bold" />
                )}
              </View>
              <View className="flex-1">
                <Text className="text-base font-manrope-extrabold text-slate-900">
                  {downloadingId === selectedShare?.id ? tran("Generating") + "..." : tran("Ownership Document")}
                </Text>
                <Text className="text-xs font-manrope-medium text-slate-500 mt-0.5">{tran("Download legal certificate")}</Text>
              </View>
            </Pressable>
          </View>
        </View>
      </BottomSheet>
    </SafeAreaView>
  );
}
