"use client";

import { useState, useRef, useEffect } from "react";
import { useTranslation } from "react-i18next";
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from "@/shared/common/ui/card";
import { Button } from "@/shared/common/ui/button";
import { Input } from "@/shared/common/ui/input";
import { useAuthUser } from "@/shared/hooks/useAuthUser";
import {
  isValidEmail,
  isValidEthiopianPhoneNum,
} from "@/record-management/common/editor/Utils";

interface OTPModalProps {
  isOpen: boolean;
  identifier: string; // previously email
  identifierType: "email" | "phone" | "username"; // new
  onClose: () => void;
  isLoading?: boolean;
  title?: string;
  description?: string;
  length?: number;
}

const OTPModal = ({
  isOpen,
  onClose,
  isLoading = false,
  title,
  description,
  length = 6,
  identifier,
  identifierType,
}: OTPModalProps) => {
  const { t } = useTranslation();
  const [otp, setOtp] = useState<string[]>(Array(length).fill(""));

  const inputRefs = useRef<Array<HTMLInputElement | null>>([]);

  const { verifyMFA } = useAuthUser();
  // Default translations
  const modalTitle = title || t("otp.verifyIdentity") || "Verify Your Identity";
  const modalDescription =
    description ||
    t("otp.enterCodeSent") ||
    "Enter the verification code sent to your email";
  const verifyText = t("common.verify") || "Verify";
  const cancelText = t("common.cancel") || "Cancel";

  const [phoneError, setPhoneError] = useState("");

  useEffect(() => {
    inputRefs.current[0]?.focus();
  }, []);

  useEffect(() => {
    if (isOpen) {
      // Reset OTP when modal opens
      setOtp(Array(length).fill(""));
      // Focus first input
      setTimeout(() => {
        inputRefs.current[0]?.focus();
      }, 100);
    }
  }, [isOpen, length]);

  const handleChange = (index: number, value: string) => {
    if (!/^[a-zA-Z0-9]?$/.test(value)) return; // Only allow numbers

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

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

    // Auto-submit if all fields are filled
    if (newOtp.every((digit) => digit !== "") && index === length - 1) {
      handleVerify(newOtp.join(""));
    }
  };

  const handleKeyDown = (
    index: number,
    e: React.KeyboardEvent<HTMLInputElement>
  ) => {
    if (e.key === "Backspace" && !otp[index] && index > 0) {
      // Move to previous input on backspace
      inputRefs.current[index - 1]?.focus();
    }
  };

  const handlePaste = (e: React.ClipboardEvent) => {
    e.preventDefault();
    const pastedData = e.clipboardData.getData("text").slice(0, length);
    const pastedArray = pastedData
      .split("")
      .filter((char) => /^\d?$/.test(char));

    if (pastedArray.length > 0) {
      const newOtp = [...otp];
      pastedArray.forEach((char, index) => {
        if (index < length) {
          newOtp[index] = char;
        }
      });
      setOtp(newOtp);

      // Focus next empty input or last input
      const nextEmptyIndex = newOtp.findIndex((digit) => digit === "");
      const focusIndex =
        nextEmptyIndex === -1
          ? length - 1
          : Math.min(nextEmptyIndex, length - 1);
      inputRefs.current[focusIndex]?.focus();
    }
  };

  const handleVerify = (verificationCode: string) => {
    // Make sure identifier is defined and valid based on login method
    let processedIdentifier = identifier;
    if (identifierType === "phone") {
      if (!isValidEthiopianPhoneNum(processedIdentifier)) {
        setPhoneError(t("auth.err"));
        return;
      }
      // Convert to international format if starts with 0
      if (processedIdentifier.startsWith("0")) {
        processedIdentifier = "+251" + processedIdentifier.slice(1);
      }
    } else if (identifierType === "email") {
      if (!isValidEmail(processedIdentifier)) {
        setPhoneError("Please enter a valid email address");
        return;
      }
    }

    // Payload always uses 'email' key
    const payload = {
      email: processedIdentifier,
      otp: verificationCode,
    };

    verifyMFA(payload);
  };

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

  if (!isOpen) return null;

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-background/80 backdrop-blur-sm dark:bg-black/80">
      <Card className="w-96 shadow-2xl border-0 animate-in fade-in-90 zoom-in-90 bg-white dark:bg-gray-800">
        <CardHeader className="pb-4">
          <div className="flex items-center gap-3">
            <div className="p-2 rounded-lg bg-primary-100 dark:bg-primary-900/30 text-primary-600 dark:text-primary-400">
              <svg
                className="w-5 h-5"
                fill="none"
                stroke="currentColor"
                viewBox="0 0 24 24">
                <path
                  strokeLinecap="round"
                  strokeLinejoin="round"
                  strokeWidth={2}
                  d="M15 7a2 2 0 012 2m4 0a6 6 0 01-7.743 5.743L11 17H9v2H7v2H4a1 1 0 01-1-1v-2.586a1 1 0 01.293-.707l5.964-5.964A6 6 0 1121 9z"
                />
              </svg>
            </div>
            <div>
              <CardTitle className="text-xl dark:text-white">{modalTitle}</CardTitle>
              <CardDescription className="dark:text-gray-400">{modalDescription}</CardDescription>
            </div>
          </div>
        </CardHeader>

        <CardContent className="space-y-6">
          {/* OTP Input Fields */}
          <div className="flex justify-center gap-2">
            {otp.map((digit, index) => (
              <Input
                key={index}
                ref={(el: HTMLInputElement | null) => {
                  if (el) inputRefs.current[index] = el; // assign only if not null
                }}
                type="text"
                inputMode="numeric"
                pattern="[0-9]*"
                maxLength={1}
                value={digit}
                onChange={(e) => handleChange(index, e.target.value)}
                onKeyDown={(e) => handleKeyDown(index, e)}
                onPaste={handlePaste}
                className="w-12 h-12 text-center text-lg font-semibold focus:ring-2 focus:ring-primary-500 border-2 bg-white dark:bg-gray-700 text-gray-900 dark:text-white border-gray-200 dark:border-gray-600 dark:focus:border-primary-500"
                disabled={isLoading}
              />
            ))}
          </div>

          {/* Action Buttons */}
          <div className="flex gap-3 pt-2">
            <Button
              type="button"
              variant="outline"
              onClick={onClose}
              disabled={isLoading}
              className="flex-1 hover:bg-primary-100 dark:hover:bg-primary-900/30 transition-all duration-200 border-gray-200 dark:border-gray-600 text-gray-700 dark:text-gray-300">
              {cancelText}
            </Button>
            <Button
              type="button"
              onClick={() => handleVerify(otp.join(""))}
              disabled={isLoading || otp.join("").length !== length}
              className="flex-1 bg-gradient-to-r from-primary-600 to-primary-700 hover:from-primary-700 hover:to-primary-800 text-white shadow-lg hover:shadow-xl transition-all duration-200 disabled:opacity-50">
              {isLoading ? (
                <div className="flex items-center gap-2">
                  <div className="animate-spin rounded-full h-4 w-4 border-b-2 border-white"></div>
                  {t("common.verifying") || "Verifying..."}
                </div>
              ) : (
                verifyText
              )}
            </Button>
          </div>

          {/* Helper Actions */}
          <div className="flex justify-between items-center text-sm">
            <button
              type="button"
              onClick={clearOtp}
              className="text-primary-600 dark:text-primary-400 hover:text-primary-700 dark:hover:text-primary-300 font-medium transition-colors disabled:opacity-50"
              disabled={isLoading}>
              {t("otp.clearCode") || "Clear Code"}
            </button>

            <button
              type="button"
              className="text-primary-600 dark:text-primary-400 hover:text-primary-700 dark:hover:text-primary-300 font-medium transition-colors disabled:opacity-50"
              disabled={isLoading}>
              {t("otp.resendCode") || "Resend Code"}
            </button>
          </div>
          {phoneError && (
            <p className="text-red-500 dark:text-red-400 text-sm mt-2 flex items-center gap-1">
              <span className="w-1 h-1 bg-red-500 dark:bg-red-400 rounded-full"></span>
              {phoneError}
            </p>
          )}
        </CardContent>
      </Card>

      {/* Loading Overlay */}
      {isLoading && (
        <div className="absolute inset-0 bg-background/50 backdrop-blur-sm rounded-lg flex items-center justify-center">
          <Card className="w-80 shadow-2xl border-0 bg-white dark:bg-gray-800">
            <CardContent className="p-6 flex flex-col items-center gap-4">
              <div className="flex items-center gap-3">
                <div className="animate-spin rounded-full h-6 w-6 border-b-2 border-primary-600"></div>
                <span className="text-lg font-semibold text-primary-800 dark:text-primary-300">
                  {t("common.verifying") || "Verifying..."}
                </span>
              </div>
              <p className="text-muted-foreground dark:text-gray-400 text-center text-sm">
                {t("otp.verifyingCode") ||
                  "Please wait while we verify your code"}
              </p>
            </CardContent>
          </Card>
        </div>
      )}
    </div>
  );
};

export default OTPModal;
