import React, { useEffect, useRef, useState } from "react";
import {
  View,
  Text,
  TouchableOpacity,
  ActivityIndicator,
  Platform,
} from "react-native";
import { ArrowLeft } from "lucide-react-native";
import { router } from "expo-router";
import {
  CameraView,
  useCameraPermissions,
  type BarcodeScanningResult,
} from "expo-camera";
import ScreenWrapper from "~/components/ui/ScreenWrapper";
import { Button } from "~/components/ui/button";
import ModalToast from "~/components/ui/toast";
import { ROUTES } from "~/lib/routes";

export default function ScanProfileQR() {
  const [hasPermission, setHasPermission] = useState<null | boolean>(null);
  const [scanned, setScanned] = useState(false);

  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 [permission, requestPermission] = useCameraPermissions();

  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);
      }
    };
  }, []);

  useEffect(() => {
    if (Platform.OS === "web") {
      setHasPermission(false);
      return;
    }

    if (!permission) {
      return;
    }

    setHasPermission(permission.granted);
  }, [permission]);

  const handleClose = () => {
    router.back();
  };

  const handleBarCodeScanned = ({ data }: BarcodeScanningResult) => {
    if (scanned) return;

    try {
      setScanned(true);

      const parsed = JSON.parse(data);
      if (!parsed || parsed.type !== "AMBA_PROFILE") {
        showToast(
          "Invalid QR",
          "This is not a valid Amba profile QR.",
          "error"
        );
        setScanned(false);
        return;
      }

      const accountId: string | undefined = parsed.accountId;
      const name: string | undefined = parsed.name;
      const phoneNumber: string | undefined = parsed.phoneNumber;

      if (!phoneNumber) {
        showToast(
          "Invalid QR",
          "This profile QR does not contain a phone number.",
          "error"
        );
        setScanned(false);
        return;
      }

      router.push({
        pathname: ROUTES.SEND_OR_REQUEST_MONEY,
        params: {
          selectedContactId: accountId || phoneNumber,
          selectedContactName: name || "User",
          selectedContactPhone: phoneNumber,
        },
      });
    } catch (error) {
      console.warn("[ScanProfileQR] Failed to parse QR payload", error);
      showToast("Scan failed", "Could not read this QR code.", "error");
      setScanned(false);
    }
  };

  return (
    <ScreenWrapper edges={[]}>
      <View className="flex-1 bg-white">
        {/* Top back button */}
        <View className="flex-row justify-start px-5 pt-5">
          <TouchableOpacity
            onPress={handleClose}
            hitSlop={{ top: 8, bottom: 8, left: 8, right: 8 }}
          >
            <ArrowLeft size={22} color="#111827" />
          </TouchableOpacity>
        </View>

        {Platform.OS === "web" ? (
          <View className="flex-1 items-center justify-center px-5">
            <Text className="text-base font-dmsans text-gray-600 text-center">
              QR scanning is not supported on web. Please use a mobile device.
            </Text>
          </View>
        ) : hasPermission === null ? (
          <View className="flex-1 items-center justify-center px-5">
            <ActivityIndicator size="large" color="#0F7B4A" />
            <View className="h-4" />
            <Text className="text-base font-dmsans text-gray-600">
              Requesting camera permission...
            </Text>
          </View>
        ) : hasPermission === false ? (
          <View className="flex-1 items-center justify-center px-5">
            <Text className="text-base font-dmsans text-gray-800 mb-2 text-center">
              Camera permission needed
            </Text>
            <Text className="text-sm font-dmsans text-gray-500 mb-4 text-center">
              Please grant camera access to scan profile QR codes.
            </Text>
            <Button
              className="rounded-full bg-primary px-8"
              onPress={async () => {
                try {
                  const result = await requestPermission();
                  if (result) {
                    setHasPermission(result.granted);
                  }
                } catch (error) {
                  console.warn(
                    "[ScanProfileQR] Failed to re-request camera permission",
                    error
                  );
                  showToast(
                    "Permission error",
                    "Could not update camera permission.",
                    "error"
                  );
                }
              }}
            >
              <Text className="text-white font-dmsans-medium">
                Grant permission
              </Text>
            </Button>
          </View>
        ) : (
          <View className="flex-1 items-center justify-center px-5">
            <View
              style={{ overflow: "hidden", borderRadius: 24 }}
              className="w-full aspect-square max-w-[320px] bg-black"
            >
              <CameraView
                style={{ width: "100%", height: "100%" }}
                barcodeScannerSettings={{ barcodeTypes: ["qr"] }}
                onBarcodeScanned={scanned ? undefined : handleBarCodeScanned}
                active={true}
              />
            </View>
            <View className="h-6" />
            <Text className="text-base font-dmsans text-gray-800 mb-1 text-center">
              Scan profile QR code
            </Text>
            <Text className="text-sm font-dmsans text-gray-500 text-center px-4">
              Align the QR code inside the frame. We will automatically select
              the account and take you to the amount screen.
            </Text>
          </View>
        )}
      </View>
      <ModalToast
        visible={toastVisible}
        title={toastTitle}
        description={toastDescription}
        variant={toastVariant}
      />
    </ScreenWrapper>
  );
}
