import React, { useEffect, useRef, useState } from "react";
import { View, Text, ScrollView, Share } from "react-native";
import { Button } from "~/components/ui/button";
import { SafeAreaView } from "react-native-safe-area-context";
import { router, useLocalSearchParams } from "expo-router";
import { ROUTES } from "~/lib/routes";
import ScreenWrapper from "~/components/ui/ScreenWrapper";
import ModalToast from "~/components/ui/toast";
import { useTranslation } from "react-i18next";
import LottieView from "lottie-react-native";

export default function RecipAddedComp() {
  const { t } = useTranslation();
  const params = useLocalSearchParams<{
    message?: string;
    recipientName?: string;
    recipientPhone?: string;
  }>();

  const [toastVisible, setToastVisible] = useState(false);
  const [toastTitle, setToastTitle] = useState("");
  const [toastDescription, setToastDescription] = useState<string | undefined>(
    undefined
  );
  const [toastVariant, setToastVariant] = useState<
    "success" | "error" | "warning" | "info"
  >("info");
  const toastTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);

  const showToast = (
    title: string,
    description?: string,
    variant: "success" | "error" | "warning" | "info" = "info"
  ) => {
    if (toastTimeoutRef.current) {
      clearTimeout(toastTimeoutRef.current);
    }

    setToastTitle(title);
    setToastDescription(description);
    setToastVariant(variant);
    setToastVisible(true);

    toastTimeoutRef.current = setTimeout(() => {
      setToastVisible(false);
      toastTimeoutRef.current = null;
    }, 2500);
  };

  useEffect(() => {
    return () => {
      if (toastTimeoutRef.current) {
        clearTimeout(toastTimeoutRef.current);
      }
    };
  }, []);

  const handleAddAnother = () => {
    // Navigate to add recipient page
    router.replace(ROUTES.ADD_RECIPIENT);
  };

  const handleGoToRecipients = () => {
    // Navigate to list recipients page
    router.replace(ROUTES.LIST_RECIPIENTS);
  };

  const handleShare = async () => {
    try {
      const shareMessage = params.message
        ? t("recipaddedcomp.shareMessageWithParam", {
            message: params.message,
          })
        : t("recipaddedcomp.shareMessageDefault");

      const result = await Share.share({
        message: shareMessage,
        title: t("recipaddedcomp.shareTitle"),
      });

      if (result.action === Share.sharedAction) {
        // Content was shared
        console.log("Content shared successfully");
      } else if (result.action === Share.dismissedAction) {
        // Share dialog was dismissed
        console.log("Share dialog dismissed");
      }
    } catch (error) {
      console.error("Error sharing:", error);
      showToast(
        t("recipaddedcomp.toastErrorTitle"),
        t("recipaddedcomp.toastShareError"),
        "error"
      );
    }
  };

  return (
    <ScreenWrapper edges={[]}>
      <View className="flex-1 w-full justify-between">
        {/* Center content */}
        <View className="flex-1 justify-center items-center px-5">
          <LottieView
            source={require("../../../assets/lottie/Recipient.json")}
            autoPlay
            loop={false}
            style={{ width: 350, height: 350 }}
          />
          <View className="h-10" />
          <Text className="text-primary text-3xl">
            {t("recipaddedcomp.title")}
          </Text>
          <View className="h-4" />
          <Text className="text-xl font-regular text-gray-400 font-dmsans text-center">
            {t("recipaddedcomp.description")}
          </Text>
        </View>

        <View className="w-full px-5 pb-8">
          <Button
            className="bg-primary rounded-full"
            onPress={handleAddAnother}
          >
            <Text className="font-dmsans text-white">
              {t("recipaddedcomp.addButton")}
            </Text>
          </Button>
          <View className="h-4" />
          <Button
            className="bg-white border border-dashed border-secondary rounded-full"
            onPress={() => router.replace(ROUTES.HOME)}
          >
            <Text className="font-dmsans text-black">
              {t("recipaddedcomp.goHomeButton")}
            </Text>
          </Button>
        </View>
      </View>
      <ModalToast
        visible={toastVisible}
        title={toastTitle}
        description={toastDescription}
        variant={toastVariant}
      />
    </ScreenWrapper>
  );
}
