"use client";

import { useState } from "react";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { CheckCircle2, Eye, EyeOff, KeyRound, Mail } from "lucide-react";
import Link from "next/link";

import {
  forgotPasswordSchema,
  resetPasswordSchema,
  type ForgotPasswordFormValues,
  type ResetPasswordFormValues,
} from "@/lib/validations/auth.schema";
import { useForgotPassword } from "@/hooks/auth/useForgotPassword";
import { useResetPassword } from "@/hooks/auth/useResetPassword";
import { useTranslation } from "@/hooks/useTranslation";
import { ROUTES } from "@/lib/constants/routes";

import { Button } from "@/components/ui/button";
import { Label } from "@/components/ui/label";
import {
  InputGroup,
  InputGroupAddon,
  InputGroupInput,
  InputGroupButton,
  InputGroupText,
} from "@/components/ui/input-group";
import { OtpInput } from "@/components/auth/OtpInput";
import {
  Card,
  CardContent,
  CardHeader,
  CardTitle,
  CardDescription,
} from "@/components/ui/card";
import { Typography } from "@/components/ui/typography";
import { useRouter } from "next/navigation";

type Step = "request" | "reset" | "success";

export function ForgotPasswordFlow() {
  const { t } = useTranslation();
  const router = useRouter();
  const [step, setStep] = useState<Step>("request");
  const [identifier, setIdentifier] = useState("");
  const [showNewPassword, setShowNewPassword] = useState(false);
  const [showConfirmPassword, setShowConfirmPassword] = useState(false);

  // ─── Step 1 form ─────────────────────────────────────────────────────────
  const step1Form = useForm<ForgotPasswordFormValues>({
    resolver: zodResolver(forgotPasswordSchema),
    defaultValues: { identifier: "" },
    mode: "onTouched",
  });

  const forgotMutation = useForgotPassword({
    onSuccess: () => {
      setIdentifier(step1Form.getValues("identifier"));
      setStep("reset");
    },
  });

  function onStep1Submit(values: ForgotPasswordFormValues) {
    forgotMutation.mutate({ identifier: values.identifier });
  }

  // ─── Step 2 form ─────────────────────────────────────────────────────────
  const step2Form = useForm<ResetPasswordFormValues>({
    resolver: zodResolver(resetPasswordSchema),
    defaultValues: { otpCode: "", newPassword: "", confirmPassword: "" },
    mode: "onTouched",
  });

  const resetMutation = useResetPassword({
    onSuccess: () => setStep("success"),
  });

  function onStep2Submit(values: ResetPasswordFormValues) {
    resetMutation.mutate({
      identifier,
      otpCode: values.otpCode,
      newPassword: values.newPassword,
    });
  }

  // ─── Render ───────────────────────────────────────────────────────────────
  return (
    <Card className="w-full max-w-md">
      {/* ── Step 1: Enter identifier ────────────────────────────────────── */}
      {step === "request" && (
        <>
          <CardHeader className="flex flex-col items-center gap-3 text-center">
            <div className="flex size-16 items-center justify-center rounded-full bg-background">
              <Mail className="size-8 text-primary-blue" />
            </div>
            <CardTitle>{t("auth.forgotPassword.title")}</CardTitle>
            <CardDescription>
              {t("auth.forgotPassword.step1Subtitle")}
            </CardDescription>
          </CardHeader>
          <CardContent>
            <form
              onSubmit={step1Form.handleSubmit(onStep1Submit)}
              noValidate
              className="flex flex-col gap-5"
            >
              <div className="flex flex-col gap-1.5">
                <Label htmlFor="fp-identifier">
                  {t("auth.forgotPassword.identifierLabel")}
                </Label>
                <InputGroup>
                  <InputGroupAddon align="inline-start">
                    <InputGroupText className="pr-2">
                      <Mail className="size-4 text-muted-foreground" />
                    </InputGroupText>
                  </InputGroupAddon>
                  <InputGroupInput
                    id="fp-identifier"
                    type="text"
                    placeholder={t("auth.forgotPassword.identifierPlaceholder")}
                    aria-invalid={
                      step1Form.formState.touchedFields.identifier &&
                      !!step1Form.formState.errors.identifier
                    }
                    {...step1Form.register("identifier")}
                  />
                </InputGroup>
                {step1Form.formState.touchedFields.identifier &&
                  step1Form.formState.errors.identifier && (
                    <Typography
                      as="p"
                      variant="caption"
                      className="text-destructive mt-0.5"
                    >
                      {t(step1Form.formState.errors.identifier.message as any)}
                    </Typography>
                  )}
              </div>

              <Button
                type="submit"
                id="forgot-password-submit"
                className="w-full"
                loading={forgotMutation.isPending}
                disabled={forgotMutation.isPending}
              >
                {t("auth.forgotPassword.submit")}
              </Button>

              <Button
                variant={"ghost"}
                onClick={() => router.push(ROUTES.AUTH.LOGIN)}
                className="flex"
              >
                {t("auth.forgotPassword.backToLogin")}
              </Button>
            </form>
          </CardContent>
        </>
      )}

      {/* ── Step 2: OTP + new password ──────────────────────────────────── */}
      {step === "reset" && (
        <>
          <CardHeader className="flex flex-col items-center gap-3 text-center">
            <div className="flex size-16 items-center justify-center rounded-full bg-background">
              <KeyRound className="size-8 text-primary-blue" />
            </div>
            <CardTitle>{t("auth.forgotPassword.step2Title")}</CardTitle>
            <CardDescription>
              {t("auth.forgotPassword.step2Subtitle")}
            </CardDescription>
          </CardHeader>
          <CardContent>
            <form
              onSubmit={step2Form.handleSubmit(onStep2Submit)}
              noValidate
              className="flex flex-col gap-5"
            >
              {/* OTP Input */}
              <div className="flex flex-col gap-1.5">
                <Label htmlFor="reset-otp">
                  {t("auth.forgotPassword.otpLabel")}
                </Label>
                <div className="flex justify-center">
                  <OtpInput
                    id="reset-otp"
                    value={step2Form.watch("otpCode") ?? ""}
                    onChange={(val) =>
                      step2Form.setValue("otpCode", val, {
                        shouldValidate:
                          step2Form.formState.touchedFields.otpCode,
                      })
                    }
                    hasError={
                      step2Form.formState.touchedFields.otpCode &&
                      !!step2Form.formState.errors.otpCode
                    }
                  />
                </div>
                {step2Form.formState.touchedFields.otpCode &&
                  step2Form.formState.errors.otpCode && (
                    <Typography
                      as="p"
                      variant="caption"
                      className="text-destructive text-center mt-0.5"
                    >
                      {t(step2Form.formState.errors.otpCode.message as any)}
                    </Typography>
                  )}
              </div>

              {/* New Password */}
              <div className="flex flex-col gap-1.5">
                <Label htmlFor="new-password">
                  {t("auth.forgotPassword.newPasswordLabel")}
                </Label>
                <InputGroup>
                  <InputGroupInput
                    id="new-password"
                    type={showNewPassword ? "text" : "password"}
                    placeholder={t(
                      "auth.forgotPassword.newPasswordPlaceholder",
                    )}
                    aria-invalid={
                      step2Form.formState.touchedFields.newPassword &&
                      !!step2Form.formState.errors.newPassword
                    }
                    {...step2Form.register("newPassword")}
                  />
                  <InputGroupAddon align="inline-end">
                    <InputGroupButton
                      type="button"
                      onClick={() => setShowNewPassword((v) => !v)}
                    >
                      {showNewPassword ? (
                        <EyeOff className="size-4 text-muted-foreground" />
                      ) : (
                        <Eye className="size-4 text-muted-foreground" />
                      )}
                    </InputGroupButton>
                  </InputGroupAddon>
                </InputGroup>
                {step2Form.formState.touchedFields.newPassword &&
                  step2Form.formState.errors.newPassword && (
                    <Typography
                      as="p"
                      variant="caption"
                      className="text-destructive mt-0.5"
                    >
                      {t(step2Form.formState.errors.newPassword.message as any)}
                    </Typography>
                  )}
              </div>

              {/* Confirm Password */}
              <div className="flex flex-col gap-1.5">
                <Label htmlFor="confirm-password">
                  {t("auth.forgotPassword.confirmPasswordLabel")}
                </Label>
                <InputGroup>
                  <InputGroupInput
                    id="confirm-password"
                    type={showConfirmPassword ? "text" : "password"}
                    placeholder={t(
                      "auth.forgotPassword.confirmPasswordPlaceholder",
                    )}
                    aria-invalid={
                      step2Form.formState.touchedFields.confirmPassword &&
                      !!step2Form.formState.errors.confirmPassword
                    }
                    {...step2Form.register("confirmPassword")}
                  />
                  <InputGroupAddon align="inline-end">
                    <InputGroupButton
                      type="button"
                      onClick={() => setShowConfirmPassword((v) => !v)}
                    >
                      {showConfirmPassword ? (
                        <EyeOff className="size-4 text-muted-foreground" />
                      ) : (
                        <Eye className="size-4 text-muted-foreground" />
                      )}
                    </InputGroupButton>
                  </InputGroupAddon>
                </InputGroup>
                {step2Form.formState.touchedFields.confirmPassword &&
                  step2Form.formState.errors.confirmPassword && (
                    <Typography
                      as="p"
                      variant="caption"
                      className="text-destructive mt-0.5"
                    >
                      {t(
                        step2Form.formState.errors.confirmPassword
                          .message as any,
                      )}
                    </Typography>
                  )}
              </div>

              <Button
                type="submit"
                id="reset-password-submit"
                className="w-full"
                loading={resetMutation.isPending}
                disabled={resetMutation.isPending}
              >
                {t("auth.forgotPassword.resetSubmit")}
              </Button>

              <Button
                type="button"
                variant={"ghost"}
                onClick={() => setStep("request")}
              >
                <Typography
                  as="span"
                  variant="body"
                  color="secondary"
                  className="hover:text-primary-blue transition-colors"
                >
                  {t("common.back")}
                </Typography>
              </Button>
            </form>
          </CardContent>
        </>
      )}

      {/* ── Step 3: Success ─────────────────────────────────────────────── */}
      {step === "success" && (
        <>
          <CardHeader className="flex flex-col items-center gap-3 text-center">
            <div className="flex size-16 items-center justify-center rounded-full bg-success-light">
              <CheckCircle2 className="size-8 text-success" />
            </div>
            <CardTitle>{t("auth.forgotPassword.successTitle")}</CardTitle>
            <CardDescription>
              {t("auth.forgotPassword.successSubtitle")}
            </CardDescription>
          </CardHeader>
          <CardContent>
            <Link href={ROUTES.AUTH.LOGIN} className="block w-full">
              <Button id="success-back-to-login" className="w-full">
                {t("auth.forgotPassword.backToLogin")}
              </Button>
            </Link>
          </CardContent>
        </>
      )}

      <Button
        variant={"ghost"}
        className={`flex -mt-5! mx-5`}
        onClick={() => router.push(ROUTES.HOME)}
      >
        {t("common.backToHome")}
      </Button>
    </Card>
  );
}
