"use client";

import { zodResolver } from "@hookform/resolvers/zod";
import { Eye, EyeOff } from "lucide-react";
import { useTranslations } from "next-intl";
import { 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,
  FormLabel,
  FormMessage,
} from "@/components/ui/form";
import { Input } from "@/components/ui/input";

interface ResetPasswordFormProps {
  email: string;
  onSubmit: (values: {
    otp: string;
    password: string;
    password_confirmation: string;
  }) => Promise<void>;
  onBack: () => void;
  isLoading?: boolean;
}

export function ResetPasswordForm({
  onSubmit,
  onBack,
  isLoading = false,
}: ResetPasswordFormProps) {
  const t = useTranslations("auth.resetPassword");
  const tErrors = useTranslations("auth.errors");
  const [showPassword, setShowPassword] = useState(false);
  const [showConfirmPassword, setShowConfirmPassword] = useState(false);

  // Define form schema with zod
  const formSchema = z
    .object({
      otp: z.string().min(1, { message: tErrors("otpRequired") }),
      password: z.string().min(8, { message: tErrors("passwordMinLength") }),
      confirmPassword: z
        .string()
        .min(1, { message: tErrors("newPasswordRequired") }),
    })
    .refine((data) => data.password === data.confirmPassword, {
      message: tErrors("passwordsNotMatch"),
      path: ["confirmPassword"],
    });

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

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

  return (
    <Form {...form}>
      <form
        onSubmit={form.handleSubmit(handleSubmit)}
        className="flex flex-col gap-4"
      >
        {/* OTP Field */}
        <FormField
          control={form.control}
          name="otp"
          render={({ field }) => (
            <FormItem>
              <FormLabel className="text-sm font-normal text-foreground">
                {t("codeLabel")}
              </FormLabel>
              <FormControl>
                <Input
                  type="text"
                  placeholder={t("codePlaceholder")}
                  className="h-10 rounded"
                  disabled={isLoading}
                  {...field}
                />
              </FormControl>
              <FormMessage />
            </FormItem>
          )}
        />

        {/* New Password Field */}
        <FormField
          control={form.control}
          name="password"
          render={({ field }) => (
            <FormItem>
              <FormLabel className="text-sm font-normal text-foreground">
                {t("newPasswordLabel")}
              </FormLabel>
              <FormControl>
                <div className="relative">
                  <Input
                    type={showPassword ? "text" : "password"}
                    placeholder={t("newPasswordPlaceholder")}
                    className="h-10 rounded pe-10"
                    disabled={isLoading}
                    {...field}
                  />
                  <button
                    type="button"
                    onClick={() => setShowPassword(!showPassword)}
                    className="absolute inset-y-0 end-0 flex items-center pe-3 text-muted-foreground hover:text-foreground"
                    tabIndex={-1}
                  >
                    {showPassword ? (
                      <EyeOff className="h-4 w-4" />
                    ) : (
                      <Eye className="h-4 w-4" />
                    )}
                  </button>
                </div>
              </FormControl>
              <FormMessage />
            </FormItem>
          )}
        />

        {/* Confirm Password Field */}
        <FormField
          control={form.control}
          name="confirmPassword"
          render={({ field }) => (
            <FormItem>
              <FormLabel className="text-sm font-normal text-foreground">
                {t("confirmPasswordLabel")}
              </FormLabel>
              <FormControl>
                <div className="relative">
                  <Input
                    type={showConfirmPassword ? "text" : "password"}
                    placeholder={t("confirmPasswordPlaceholder")}
                    className="h-10 rounded pe-10"
                    disabled={isLoading}
                    {...field}
                  />
                  <button
                    type="button"
                    onClick={() => setShowConfirmPassword(!showConfirmPassword)}
                    className="absolute inset-y-0 end-0 flex items-center pe-3 text-muted-foreground hover:text-foreground"
                    tabIndex={-1}
                  >
                    {showConfirmPassword ? (
                      <EyeOff className="h-4 w-4" />
                    ) : (
                      <Eye className="h-4 w-4" />
                    )}
                  </button>
                </div>
              </FormControl>
              <FormMessage />
            </FormItem>
          )}
        />

        {/* Action Buttons */}
        <div className="flex gap-4  mt-4">
          <Button
            type="button"
            variant="outline"
            className="h-10 rounded"
            onClick={onBack}
            disabled={isLoading}
          >
            {t("back")}
          </Button>
          <Button
            type="submit"
            className="h-10 rounded bg-primary text-base font-medium"
            disabled={isLoading}
          >
            {isLoading ? t("submitting") : t("submit")}
          </Button>
        </div>
      </form>
    </Form>
  );
}
