"use client";

import { zodResolver } from "@hookform/resolvers/zod";
import { Clock } from "lucide-react";
import { useTranslations } from "next-intl";
import { useEffect, useState } from "react";
import { useForm } from "react-hook-form";
import * as z from "zod";

import { Button } from "@/components/ui/button";
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormMessage,
} from "@/components/ui/form";
import {
  InputOTP,
  InputOTPGroup,
  InputOTPSlot,
} from "@/components/ui/input-otp";

interface OTPVerificationFormProps {
  email: string;
  onSubmit: (otp: string) => Promise<void>;
  onResend: () => Promise<void>;
  onBack: () => void;
  isLoading?: boolean;
}

export function OTPVerificationForm({
  email,
  onSubmit,
  onResend,
  onBack,
  isLoading = false,
}: OTPVerificationFormProps) {
  const t = useTranslations("auth.otp");
  const tErrors = useTranslations("auth.errors");
  const [timer, setTimer] = useState(60);
  const [isResending, setIsResending] = useState(false);

  // Define form schema with zod
  const formSchema = z.object({
    otp: z.string().length(6, { message: tErrors("otpLength") }),
  });

  // Initialize form with react-hook-form
  const form = useForm<z.infer<typeof formSchema>>({
    resolver: zodResolver(formSchema),
    defaultValues: {
      otp: "",
    },
  });

  // Countdown timer effect
  useEffect(() => {
    if (timer > 0) {
      const interval = setInterval(() => {
        setTimer((prev) => prev - 1);
      }, 1000);
      return () => clearInterval(interval);
    }
  }, [timer]);

  // Auto-submit when OTP is complete
  const otpValue = form.watch("otp");
  useEffect(() => {
    if (otpValue.length === 6 && !isLoading) {
      form.handleSubmit(handleSubmit)();
    }
  }, [otpValue]);

  const handleSubmit = async (values: z.infer<typeof formSchema>) => {
    await onSubmit(values.otp);
  };

  const handleResend = async () => {
    setIsResending(true);
    try {
      await onResend();
      setTimer(60); // Reset timer
      form.reset(); // Clear OTP input
    } finally {
      setIsResending(false);
    }
  };

  // Format timer as MM:SS
  const formatTimer = (seconds: number) => {
    const mins = Math.floor(seconds / 60);
    const secs = seconds % 60;
    return `${mins.toString().padStart(2, "0")}:${secs.toString().padStart(2, "0")}`;
  };

  return (
    <Form {...form}>
      <form
        onSubmit={form.handleSubmit(handleSubmit)}
        className="flex flex-col gap-4 sm:gap-6"
      >
        {/* Email Display */}
        <div className="text-center text-xs sm:text-sm text-muted-foreground">
          <p>{t("subtitle")}</p>
          <p className="font-medium text-foreground break-all">{email}</p>
        </div>

        {/* OTP Input */}
        <FormField
          control={form.control}
          name="otp"
          render={({ field }) => (
            <FormItem>
              <FormControl>
                <div className="w-full" dir="ltr">
                  <InputOTP
                    maxLength={6}
                    value={field.value}
                    onChange={field.onChange}
                    disabled={isLoading}
                    containerClassName="w-full"
                  >
                    <InputOTPGroup className="flex w-full gap-1.5 sm:gap-2">
                      {[0, 1, 2, 3, 4, 5].map((i) => (
                        <InputOTPSlot
                          key={i}
                          index={i}
                          className="h-11 flex-1 min-w-0 rounded-xl sm:h-14 text-base sm:text-xl font-semibold border-border"
                        />
                      ))}
                    </InputOTPGroup>
                  </InputOTP>
                </div>
              </FormControl>
              <FormMessage className="text-center" />
            </FormItem>
          )}
        />

        {/* Timer / Resend */}
        <div className="flex items-center justify-center gap-2 text-sm">
          {timer > 0 ? (
            <>
              <Clock className="h-4 w-4 text-muted-foreground" />
              <span className="text-muted-foreground">
                {t("resendAfter")} {formatTimer(timer)}
              </span>
            </>
          ) : (
            <Button
              type="button"
              variant="link"
              className="h-auto p-0 text-primary"
              onClick={handleResend}
              disabled={isResending}
            >
              {isResending ? t("resending") : t("resendNow")}
            </Button>
          )}
        </div>

        {/* Action Buttons */}
        <div className="flex flex-col sm:flex-row gap-3 sm:gap-4">
          <Button
            type="button"
            variant="outline"
            className="h-11 sm:flex-1 rounded order-2 sm:order-1"
            onClick={onBack}
            disabled={isLoading}
          >
            {t("previousStep")}
          </Button>
          <Button
            type="submit"
            className="h-11 sm:flex-1 rounded bg-primary text-base font-medium order-1 sm:order-2"
            disabled={isLoading || otpValue.length !== 6}
          >
            {isLoading ? t("confirming") : t("confirm")}
          </Button>
        </div>
      </form>
    </Form>
  );
}
