import React, { useState, useRef } from "react";
import { View, Text, ScrollView, TouchableOpacity } from "react-native";
import { router, useLocalSearchParams } from "expo-router";
import ScreenWrapper from "~/components/ui/ScreenWrapper";
import BackButton from "~/components/ui/backButton";
import { AwashIcon, TeleBirrIcon } from "~/components/ui/icons";
import { LucideChevronRightCircle } from "lucide-react-native";
import { Button } from "~/components/ui/button";
import ModalToast from "~/components/ui/toast";
import { useTranslation } from "react-i18next";
import { ROUTES } from "~/lib/routes";
import { awardPoints } from "~/lib/services/pointsService";

export default function RequestProvider() {
  const { t } = useTranslation();
  const params = useLocalSearchParams<{
    amount: string;
    recipientName: string;
    recipientPhoneNumber: string;
    recipientType: string;
    recipientId: string;
    note: string;
    requestorName: string;
    requestorPhoneNumber: string;
    requestorType: string;
    type: string;
  }>();

  const [selectedProvider, setSelectedProvider] = useState<
    "awash" | "telebirr" | null
  >(null);

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

  const handleContinue = () => {
    if (!selectedProvider) {
      showToast(
        t("sendbank.toastErrorTitle"),
        t("sendbank.toastNoMethod"),
        "error"
      );
      return;
    }

    awardPoints("make_request").catch((error) => {
      console.warn(
        "[RequestProvider] Failed to award make request points",
        error
      );
    });

    router.push({
      pathname: ROUTES.NOTIFICATION_OPTION,
      params: {
        ...params,
        provider: selectedProvider,
      } as any,
    });
  };

  return (
    <ScreenWrapper edges={["top"]}>
      <View className="flex-row items-center justify-between">
        <BackButton />
      </View>

      <ScrollView className="flex-1 px-5 pt-2">
        <View className="mb-6">
          <Text className="text-2xl font-dmsans-bold text-black mb-2">
            {t("sendbank.paymentOptionsTitle")}
          </Text>
          <Text className="text-base font-dmsans text-gray-500">
            {selectedProvider
              ? t("sendbank.paymentOptionsSelected", {
                  providerName:
                    selectedProvider === "awash"
                      ? t("sendbank.awashName")
                      : t("sendbank.telebirrName"),
                })
              : t("sendbank.paymentOptionsUnselected")}
          </Text>
        </View>

        {/* Telebirr Section */}
        <View className="mb-6">
          <Text className="text-base font-dmsans-medium text-gray-600 mb-1">
            {t("sendbank.telebirrName")}
          </Text>
          <TouchableOpacity
            onPress={() => setSelectedProvider("telebirr")}
            className={`flex flex-row w-full justify-between items-center py-4 rounded-md px-3 mb-4 ${
              selectedProvider === "telebirr"
                ? "bg-orange-100 border-2 border-orange-300"
                : "bg-green-50 border border-gray-200"
            }`}
          >
            <View className="flex flex-row space-x-3 items-center flex-1">
              <View className="p-2 rounded">
                <TeleBirrIcon />
              </View>
              <View className="w-2" />
              <View className="flex flex-col">
                <Text className="font-dmsans text-primary">
                  {t("sendbank.telebirrName")}
                </Text>
                <Text className="font-dmsans-medium text-secondary text-sm">
                  {t("sendbank.telebirrSubtitle")}
                </Text>
              </View>
            </View>
            <View className="flex space-y-1">
              <LucideChevronRightCircle
                color={selectedProvider === "telebirr" ? "#EA580C" : "#FFB84D"}
                size={24}
              />
            </View>
          </TouchableOpacity>
        </View>

        {/* Bank Section with Awash */}
        <View className="mb-6">
          <Text className="text-base font-dmsans-medium text-gray-600 mb-1">
            Bank
          </Text>
          <TouchableOpacity
            onPress={() => setSelectedProvider("awash")}
            className={`flex flex-row w-full justify-between items-center py-4 rounded-md px-3 ${
              selectedProvider === "awash"
                ? "bg-blue-100 border-2 border-blue-300"
                : "bg-green-50 border border-gray-200"
            }`}
          >
            <View className="flex flex-row space-x-3 items-center flex-1">
              <View className="p-2 rounded">
                <AwashIcon />
              </View>
              <View className="flex flex-col">
                <Text className="font-dmsans text-primary">
                  {t("sendbank.awashName")}
                </Text>
                <Text className="font-dmsans-medium text-secondary text-sm">
                  {t("sendbank.awashSubtitle")}
                </Text>
              </View>
            </View>
            <View className="flex space-y-1">
              <LucideChevronRightCircle
                color={selectedProvider === "awash" ? "#2563EB" : "#FFB84D"}
                size={24}
              />
            </View>
          </TouchableOpacity>
        </View>
      </ScrollView>

      <View className="w-full px-5 pb-6">
        <Button
          className="bg-primary rounded-3xl w-full py-4"
          onPress={handleContinue}
        >
          <Text className="text-white font-dmsans-bold text-lg">
            {t("notificationOption.continueButton")}
          </Text>
        </Button>
      </View>

      <ModalToast
        visible={toastVisible}
        title={toastTitle}
        description={toastDescription}
        variant={toastVariant}
      />
    </ScreenWrapper>
  );
}
