"use client";

import { useEffect, useState } from "react";
import {
  formatOtpCountdown,
  getOtpRemainingSeconds,
  markOtpSent,
  OTP_VALID_SECONDS,
} from "@/lib/auth/otpTimer";
import { cn } from "@/lib/utils";

interface AuthOtpStatusProps {
  mobile: string | null;
  onResend: () => Promise<void>;
  resendLoading?: boolean;
  className?: string;
  onExpiredChange?: (expired: boolean) => void;
}

export default function AuthOtpStatus({
  mobile,
  onResend,
  resendLoading = false,
  className,
  onExpiredChange,
}: AuthOtpStatusProps) {
  const [remaining, setRemaining] = useState(OTP_VALID_SECONDS);
  const expired = remaining <= 0;

  useEffect(() => {
    setRemaining(getOtpRemainingSeconds());
    const interval = window.setInterval(() => {
      setRemaining(getOtpRemainingSeconds());
    }, 1000);
    return () => window.clearInterval(interval);
  }, []);

  useEffect(() => {
    onExpiredChange?.(expired);
  }, [expired, onExpiredChange]);

  const handleResend = async () => {
    await onResend();
    markOtpSent();
    setRemaining(OTP_VALID_SECONDS);
  };

  if (!mobile) return null;

  return (
    <div className={cn("w-full max-w-sm text-center mb-6 space-y-2", className)}>
      <p className="text-sm sm:text-base font-medium text-gray-800 dark:text-gray-100 leading-relaxed">
        کد ۶ رقمی به شماره{" "}
        <span dir="ltr" className="font-bold text-[#387E65] inline-block">
          {mobile}
        </span>{" "}
        ارسال شد
      </p>

      {!expired ? (
        <p className="text-sm text-gray-600 dark:text-gray-300">
          اعتبار کد:{" "}
          <span
            dir="ltr"
            className="font-bold tabular-nums text-[#FF5C00] text-base"
          >
            {formatOtpCountdown(remaining)}
          </span>
        </p>
      ) : (
        <div className="space-y-2">
          <p className="text-sm font-medium text-red-600 dark:text-red-400">
            کد منقضی شده است. لطفاً دوباره درخواست ارسال کد دهید.
          </p>
          <button
            type="button"
            onClick={handleResend}
            disabled={resendLoading}
            className="text-sm font-bold text-[#667AC1] hover:text-[#0033EA] disabled:opacity-50"
          >
            {resendLoading ? "در حال ارسال..." : "ارسال مجدد کد"}
          </button>
        </div>
      )}
    </div>
  );
}
