import { useColor } from "@/hooks/useColor";
import { SetStateAction, useEffect, useRef } from "react";
import {
  NativeSyntheticEvent,
  Pressable,
  StyleSheet,
  Text,
  TextInput,
  TextInputKeyPressEventData,
  View,
} from "react-native";
import OtpTimer from "./OTPTimer";
import Button from "../ui/Button";

interface OTPFieldProps {
  length?: number;
  onComplete?: (otp: string) => void;
  otp: string[];
  setOtp: React.Dispatch<SetStateAction<string[]>>;
  time: number;
  otpSendLoading: boolean;
  handleVerify: () => void;
  onResend?: () => void;
  otpInputHandler: {
    isComplete: boolean;
    isInvalid: boolean;
    otp: string;
    isReset: boolean;
  };
  setOtpInputHandler: React.Dispatch<
    React.SetStateAction<{
      isComplete: boolean;
      isInvalid: boolean;
      otp: string;
      isReset: boolean;
    }>
  >;
  backendError: null | string;
}

export default function OtpForm({
  length = 6,
  onComplete,
  otp,
  setOtp,
  time,
  handleVerify,
  onResend,
  otpInputHandler,
  setOtpInputHandler,
  otpSendLoading,
  backendError,
}: OTPFieldProps) {
  const { primary, secondary } = useColor();
  const inputRefs = useRef<(TextInput | null)[]>([]);

  useEffect(() => {
    // Focus first input on mount
    inputRefs.current[0]?.focus();
  }, []);

  const handleChange = (text: string, index: number): void => {
    if (isNaN(Number(text))) return; // Only allow numbers

    const newOtp = [...otp];
    newOtp[index] = text;
    setOtp(newOtp);

    const joinedOtp = newOtp.join("");

    // Store the OTP string inside otpInputHandler
    setOtpInputHandler((prev) => ({
      ...prev,
      otp: joinedOtp,
      isComplete: joinedOtp.length === length,
      isInvalid: false,
      isReset: false,
    }));

    // Auto-focus next input
    if (text && index < length - 1) {
      inputRefs.current[index + 1]?.focus();
    }

    // Optionally call onComplete when done
    if (joinedOtp.length === length && onComplete) {
      onComplete(joinedOtp);
    }
  };

  const handleKeyPress = (
    e: NativeSyntheticEvent<TextInputKeyPressEventData>,
    index: number,
  ): void => {
    // Handle backspace
    if (e.nativeEvent.key === "Backspace") {
      if (otp[index] === "" && index > 0) {
        // Move to previous input if current is empty
        inputRefs.current[index - 1]?.focus();
      } else {
        // Clear current input
        const newOtp = [...otp];
        newOtp[index] = "";
        setOtp(newOtp);
      }
    }
  };

  const handleClear = (): void => {
    setOtp(Array(length).fill(""));
    inputRefs.current[0]?.focus();
  };

  return (
    <View>
      <View className="flex-row justify-center items-center gap-x-4 pb-6">
        {otp.map((digit, index) => (
          <TextInput
            key={index}
            ref={(ref) => {
              inputRefs.current[index] = ref;
            }}
            style={[
              styles.otpInput,
              digit !== "" && styles.otpInputFilled,
              {
                borderColor: otpInputHandler.isInvalid
                  ? "red"
                  : digit !== ""
                    ? primary.base
                    : "#e5e7eb",
              },
            ]}
            value={digit}
            onChangeText={(text) => handleChange(text, index)}
            onKeyPress={(e) => handleKeyPress(e, index)}
            keyboardType="number-pad"
            maxLength={1}
            selectTextOnFocus
            autoComplete="sms-otp"
          />
        ))}
      </View>

      <View className="flex-row justify-center items-center">
        <Pressable
          onPress={handleClear}
          className="px-4 py-1 rounded-md"
          style={{
            backgroundColor: otpInputHandler.otp ? secondary.base : "#e5e7eb",
          }}
        >
          <Text className="text-white ">Clear</Text>
        </Pressable>
      </View>

      {otpInputHandler.isInvalid && !backendError && (
        <Text className="w-full text-center text-red-500">
          Your OTP is incorrect
        </Text>
      )}
      {backendError && (
        <Text className="w-full text-center text-red-500 pt-3">
          {backendError}
        </Text>
      )}

      <OtpTimer onClick={onResend ?? (() => {})} otpTimerKey="email" time={time * 60} />

      <Button
        className="mt-6"
        onPress={() => handleVerify()}
        text="Verify OTP"
        isLoading={otpSendLoading}
      />
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    backgroundColor: "white",
    borderRadius: 16,
    padding: 24,
    width: "100%",
  },
  title: {
    fontSize: 24,
    fontWeight: "bold",
    color: "#1a1a1a",
    textAlign: "center",
    marginBottom: 8,
  },
  subtitle: {
    fontSize: 14,
    color: "#666",
    textAlign: "center",
    marginBottom: 32,
  },
  otpContainer: {
    flexDirection: "row",
    justifyContent: "space-between",
    marginBottom: 24,
  },
  otpInput: {
    width: 48,
    height: 56,
    borderWidth: 2,
    borderColor: "#e0e0e0",
    borderRadius: 12,
    textAlign: "center",
    fontSize: 24,
    fontWeight: "600",
    color: "#1a1a1a",
    backgroundColor: "#fafafa",
  },
  otpInputFilled: {
    backgroundColor: "#eef2ff",
  },
  clearButton: {
    alignSelf: "center",
    paddingVertical: 12,
    paddingHorizontal: 24,
    borderRadius: 8,
    backgroundColor: "#f3f4f6",
    marginBottom: 16,
  },
  clearButtonText: {
    color: "#4b5563",
    fontSize: 14,
    fontWeight: "600",
  },
  resendButton: {
    alignSelf: "center",
    paddingVertical: 8,
  },
  resendButtonText: {
    color: "#4f46e5",
    fontSize: 14,
    fontWeight: "500",
  },
});
