
"use client";

import { useState, useEffect } from "react";
import { useRouter, useSearchParams } from "next/navigation";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import {
  Card,
  CardContent,
  CardFooter,
  CardHeader,
  CardTitle,
  CardDescription,
} from "@/components/ui/card";
import { Shield, Key, ArrowLeft, Eye, EyeOff } from "lucide-react";
import Link from "next/link";
import { useResetPassword } from "@/modules/auth/hooks/auth.hooks";

function FieldError({ msg }: { msg?: string }) {
  if (!msg) return null;
  return <p className="text-xs text-destructive">{msg}</p>;
}

type Errors = {
  otp?: string;
  newPassword?: string;
  confirmPassword?: string;
};

export default function ResetPassword() {
  const router = useRouter();
  const searchParams = useSearchParams();

  const emailParam = searchParams.get("email") || "";

  const [otp, setOtp] = useState("");
  const [newPassword, setNewPassword] = useState("");
  const [confirmPassword, setConfirmPassword] = useState("");
  const [showNew, setShowNew] = useState(false);
  const [showConfirm, setShowConfirm] = useState(false);
  const [errors, setErrors] = useState<Errors>({});

  const { mutate: resetPassword, isPending } = useResetPassword();

  useEffect(() => {
    if (!emailParam) {
      router.replace("/forgot-password");
    }
  }, [emailParam, router]);

  function validate(): Errors {
    const errs: Errors = {};

    if (!otp || otp.length < 6) {
      errs.otp = "Enter the 6-digit OTP code";
    }

    if (!newPassword) {
      errs.newPassword = "Password is required";
    } else if (newPassword.length < 8) {
      errs.newPassword = "Min 8 characters";
    } else if (!/(?=.*[a-z])(?=.*[A-Z])(?=.*\d)/.test(newPassword)) {
      errs.newPassword =
        "Must contain uppercase, lowercase and a number";
    }

    if (!confirmPassword) {
      errs.confirmPassword = "Please confirm your password";
    } else if (newPassword !== confirmPassword) {
      errs.confirmPassword = "Passwords do not match";
    }

    return errs;
  }

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();

    const errs = validate();

    if (Object.keys(errs).length > 0) {
      setErrors(errs);
      return;
    }

    setErrors({});

    resetPassword(
      {
        email: emailParam,
        otp,
        newPassword,
      },
      {
        onSuccess: () => {
          router.push("/login");
        },
        onError: (error: any) => {
          const msg =
            error?.response?.data?.error ||
            error?.response?.data?.message ||
            "Reset failed. Please try again.";

          if (
            msg.toLowerCase().includes("otp") ||
            msg.toLowerCase().includes("invalid") ||
            msg.toLowerCase().includes("expired") ||
            msg.toLowerCase().includes("attempt")
          ) {
            setErrors({ otp: msg });
            setOtp("");
          } else {
            setErrors({ confirmPassword: msg });
          }
        },
      }
    );
  };

  return (
    <div className="flex min-h-screen items-center justify-center px-4">
      <Card className="w-full max-w-md border-border bg-card shadow-xl">
        <CardHeader className="space-y-1 text-center">
          <div className="mx-auto mb-2 flex h-12 w-12 items-center justify-center rounded-2xl border border-primary/20 bg-primary/10">
            <Shield className="h-6 w-6 text-primary" />
          </div>

          <CardTitle className="text-2xl font-bold tracking-tight text-card-foreground">
            Reset Password
          </CardTitle>

          <CardDescription className="text-muted-foreground">
            Enter the code sent to{" "}
            <span className="font-medium text-foreground">
              {emailParam}
            </span>
          </CardDescription>
        </CardHeader>

        <CardContent>
          <form onSubmit={handleSubmit} className="space-y-4" noValidate>
            {/* OTP */}
            <div className="space-y-1">
              <Label
                htmlFor="otp"
                className="text-sm font-medium text-foreground"
              >
                6-Digit Reset Code
              </Label>

              <Input
                id="otp"
                type="text"
                inputMode="numeric"
                maxLength={6}
                placeholder="123456"
                value={otp}
                onChange={(e) => {
                  setOtp(e.target.value.replace(/\D/g, ""));
                  setErrors((p) => ({ ...p, otp: "" }));
                }}
                className={`h-14 bg-background text-center font-mono text-2xl tracking-[0.5em] ${
                  errors.otp
                    ? "border-destructive focus-visible:ring-destructive"
                    : ""
                }`}
                autoFocus
                disabled={isPending}
              />

              <FieldError msg={errors.otp} />
            </div>

            {/* New Password */}
            <div className="space-y-1">
              <Label
                htmlFor="newPassword"
                className="flex items-center gap-2 text-foreground"
              >
                <Key className="h-4 w-4 text-primary" />
                New Password
              </Label>

              <div className="relative">
                <Input
                  id="newPassword"
                  type={showNew ? "text" : "password"}
                  placeholder="••••••••"
                  value={newPassword}
                  onChange={(e) => {
                    setNewPassword(e.target.value);
                    setErrors((p) => ({
                      ...p,
                      newPassword: "",
                    }));
                  }}
                  className={`bg-background pr-10 ${
                    errors.newPassword
                      ? "border-destructive focus-visible:ring-destructive"
                      : ""
                  }`}
                  disabled={isPending}
                />

                <button
                  type="button"
                  tabIndex={-1}
                  onClick={() => setShowNew((v) => !v)}
                  className="absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground transition-colors hover:text-foreground"
                >
                  {showNew ? (
                    <EyeOff className="h-4 w-4" />
                  ) : (
                    <Eye className="h-4 w-4" />
                  )}
                </button>
              </div>

              <FieldError msg={errors.newPassword} />

              {!errors.newPassword && (
                <p className="text-xs text-muted-foreground">
                  Min 8 chars · uppercase · lowercase · number
                </p>
              )}
            </div>

            {/* Confirm Password */}
            <div className="space-y-1">
              <Label
                htmlFor="confirmPassword"
                className="flex items-center gap-2 text-foreground"
              >
                <Key className="h-4 w-4 text-primary" />
                Confirm Password
              </Label>

              <div className="relative">
                <Input
                  id="confirmPassword"
                  type={showConfirm ? "text" : "password"}
                  placeholder="••••••••"
                  value={confirmPassword}
                  onChange={(e) => {
                    setConfirmPassword(e.target.value);
                    setErrors((p) => ({
                      ...p,
                      confirmPassword: "",
                    }));
                  }}
                  className={`bg-background pr-10 ${
                    errors.confirmPassword
                      ? "border-destructive focus-visible:ring-destructive"
                      : ""
                  }`}
                  disabled={isPending}
                />

                <button
                  type="button"
                  tabIndex={-1}
                  onClick={() => setShowConfirm((v) => !v)}
                  className="absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground transition-colors hover:text-foreground"
                >
                  {showConfirm ? (
                    <EyeOff className="h-4 w-4" />
                  ) : (
                    <Eye className="h-4 w-4" />
                  )}
                </button>
              </div>

              <FieldError msg={errors.confirmPassword} />
            </div>

            <Button
              type="submit"
              className="h-10 w-full bg-primary font-medium text-primary-foreground shadow-sm hover:bg-primary/90"
              disabled={isPending}
            >
              {isPending ? "Resetting..." : "Reset Password"}
            </Button>
          </form>
        </CardContent>

        <CardFooter className="border-t border-border pt-4">
          <Link
            href="/login"
            className="flex items-center gap-2 text-sm font-medium text-primary hover:underline"
          >
            <ArrowLeft className="h-4 w-4" />
            Back to Login
          </Link>
        </CardFooter>
      </Card>
    </div>
  );
}