// src/components/auth/OtpModal.tsx

"use client";

import { Dispatch, SetStateAction, useState, useEffect } from "react";
import Image from "next/image";
import { signIn } from "next-auth/react";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogDescription,
  DialogFooter,
} from "@/components/ui/dialog";
import {
  InputOTP,
  InputOTPGroup,
  InputOTPSlot,
} from "@/components/ui/input-otp";
import { Button } from "@/components/ui/button";
import logo from "../../../public/logo.png";
import IconButton from "../icon-button/icon-button";
import { toast } from "sonner";
import { AxiosError } from "axios";
import { useResendOtp } from "@/state/auth/auth.action";

export function OtpModal({
  isOpen,
  setIsOpen,
  email,
  onVerifyOtp,
}: {
  isOpen: boolean;
  setIsOpen: Dispatch<SetStateAction<boolean>>;
  email: string;
  onVerifyOtp: () => void;
}) {
  const [otp, setOtp] = useState("");
  const [error, setError] = useState<string | null>(null);
  const [isLoading, setIsLoading] = useState(false);
  const [timer, setTimer] = useState(30);
  const [canResend, setCanResend] = useState(false);
  const { mutate: resendOtp } = useResendOtp();

  useEffect(() => {
    if (isOpen) {
      setTimer(30);
      setCanResend(false);
      setError(null);
      setOtp("");
    }
  }, [isOpen]);

  useEffect(() => {
    if (!isOpen || timer <= 0) {
      if (timer <= 0) {
        setCanResend(true);
      }
      return;
    }

    const interval = setInterval(() => {
      setTimer((prevTimer) => prevTimer - 1);
    }, 1000);

    return () => clearInterval(interval);
  }, [isOpen, timer]);

  const handleResendOtp = async () => {
    setIsLoading(true);

    resendOtp(
      { email }, // Changed from phone_no: `+${phone}` to email
      {
        onSuccess: (resp) => {
          if (resp) {
            setTimer(30);
            setCanResend(false);
          }
        },
        onError: (err: unknown) => {
          const error = err as AxiosError<{ message: string }>;
          setError(
            error?.response?.data?.message ||
              "An unexpected server error occurred."
          );
        },
        onSettled: () => {
          setIsLoading(false);
        },
      }
    );
  };

  const handleVerify = async () => {
    if (otp.length < 4) return;
    setError(null);
    setIsLoading(true);

    const result = await signIn("credentials", {
      redirect: false,
      email: email,
      otp: otp,
    });

    if (result?.error) {
      setError(result.error);
    } else if (result?.ok) {
      toast.success("User logged in successfully");
      onVerifyOtp();
      window.location.reload();
    }

    setIsLoading(false);
  };

  return (
    <Dialog open={isOpen} onOpenChange={setIsOpen}>
      <DialogContent className="sm:max-w-[550px] bg-[#1a1a1a] p-10 border-gray-700 text-white border rounded-2xl">
        <DialogHeader className="items-center">
          <div className="flex items-center mb-4">
            <Image src={logo} alt="reelfix logo" width={150} height={50} />
          </div>
          <DialogTitle className="text-[24px] text-white font-normal text-center mt-5">
            OTP Verification
          </DialogTitle>
          <DialogDescription className="text-[16px] text-muted-foreground font-normal text-center sm:max-w-[350px]">
            We have sent the verification code to your registered Email Id
            {/* Optional: show email in description */}
          </DialogDescription>
          {email && ` ${email}`}{" "}
        </DialogHeader>
        <div className="grid gap-4 py-4 justify-center mt-4">
          <div className="grid gap-3">
            <label
              htmlFor="otp-input"
              className="text-[16px] text-muted-foreground font-normal"
            >
              OTP
            </label>
            <InputOTP
              id="otp-input"
              maxLength={6}
              value={otp}
              onChange={(value) => setOtp(value)}
            >
              <InputOTPGroup className="gap-3">
                {Array.from({ length: 4 })?.map((_, i) => (
                  <InputOTPSlot
                    key={i}
                    index={i}
                    className="w-14 h-14 text-lg bg-[#0A0A0B] border-gray-700 rounded-md"
                  />
                ))}
              </InputOTPGroup>
            </InputOTP>
          </div>
          {error && (
            <p className="text-sm text-center text-red-500 mt-2">{error}</p>
          )}
          <div className="flex justify-between items-center mt-2">
            <p className="text-muted-foreground">
              00:{timer.toString().padStart(2, "0")}
            </p>
            <Button
              variant="link"
              className="text-white hover:text-red-500 disabled:text-muted-foreground cursor-pointer"
              onClick={handleResendOtp}
              disabled={!canResend}
            >
              Resend OTP
            </Button>
          </div>
        </div>
        <DialogFooter className="w-full justify-center!">
          <IconButton
            label={isLoading ? "Verifying..." : "Verify OTP"}
            onClick={handleVerify}
            className="w-[150px] h-[50px]"
            iconShow={false}
            disabled={isLoading || otp.length < 4}
          />
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}
