"use client";

import React, { Suspense, useState, useMemo } from "react";
import Link from "next/link";
import { useParams, useRouter } from "next/navigation";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import * as z from "zod";
import { Award, Eye, EyeOff, CheckCircle2, Loader2, ArrowRight } from "lucide-react";
import { apiClient } from "@/lib/api-client";
import { toast } from "sonner";

const resetPasswordSchema = z
  .object({
    password: z.string().min(8, "Password must be at least 8 characters"),
    confirmPassword: z.string().min(1, "Please confirm your password"),
  })
  .refine((data) => data.password === data.confirmPassword, {
    message: "Passwords do not match",
    path: ["confirmPassword"],
  });

type ResetPasswordFormData = z.infer<typeof resetPasswordSchema>;

function ResetPasswordForm() {
  const params = useParams();
  const token = params?.token as string;
  const router = useRouter();
  const [showPassword, setShowPassword] = useState(false);
  const [showConfirmPassword, setShowConfirmPassword] = useState(false);
  const [isLoading, setIsLoading] = useState(false);
  const [isSuccess, setIsSuccess] = useState(false);

  const {
    register,
    handleSubmit,
    watch,
    formState: { errors },
  } = useForm<ResetPasswordFormData>({
    resolver: zodResolver(resetPasswordSchema),
    defaultValues: {
      password: "",
      confirmPassword: "",
    },
  });

  const passwordValue = watch("password") || "";

  // Dynamic Password Strength Calculator (Weak / Medium / Strong)
  const strengthInfo = useMemo(() => {
    let score = 0;
    if (passwordValue.length >= 8) score++;
    if (/[A-Z]/.test(passwordValue)) score++;
    if (/[0-9]/.test(passwordValue)) score++;
    if (/[^A-Za-z0-9]/.test(passwordValue)) score++;

    if (passwordValue.length === 0) {
      return { score: 0, text: "", color: "text-slate-400" };
    }
    if (score <= 1) {
      return { score: 1, text: "Weak", color: "text-rose-500" };
    }
    if (score <= 3) {
      return { score: 2, text: "Medium", color: "text-amber-500" };
    }
    return { score: 4, text: "Strong", color: "text-emerald-600" };
  }, [passwordValue]);

  const onSubmit = async (data: ResetPasswordFormData) => {
    setIsLoading(true);
    try {
      await apiClient.post("/auth/reset-password", {
        token,
        password: data.password,
      });
      setIsSuccess(true);
      toast.success("Password updated successfully.");
      setTimeout(() => {
        router.push("/login");
      }, 2500);
    } catch {
      toast.error("Password reset token is invalid or has expired.");
    } finally {
      setIsLoading(false);
    }
  };

  if (isSuccess) {
    return (
      <div className="py-4 text-center">
        <div className="w-12 h-12 rounded-full bg-emerald-50 text-emerald-600 flex items-center justify-center mx-auto mb-3 border border-emerald-200">
          <CheckCircle2 className="w-6 h-6" />
        </div>
        <h2 className="text-xl font-bold text-slate-900 tracking-tight mb-1.5">
          Password Reset Successful
        </h2>
        <p className="text-xs text-slate-500 mb-6 leading-relaxed">
          Your credentials have been securely updated. Redirecting to the login portal...
        </p>
        <Link
          href="/login"
          className="inline-flex items-center justify-center gap-1.5 w-full py-2.5 px-4 rounded-lg bg-[#C8A45D] hover:bg-[#b8934c] text-slate-950 font-bold text-xs uppercase tracking-wider transition-colors shadow-sm"
        >
          <span>Continue to Login</span>
          <ArrowRight className="w-3.5 h-3.5" />
        </Link>
      </div>
    );
  }

  return (
    <>
      {/* Card Title & Subtitle */}
      <div className="mb-6 text-center">
        <h2 className="text-2xl font-bold text-slate-900 tracking-tight">
          Create New Password
        </h2>
        <p className="text-xs text-slate-500 mt-1.5">
          Enter your new password below.
        </p>
      </div>

      {/* Form */}
      <form onSubmit={handleSubmit(onSubmit)} className="space-y-4 text-left">
        {/* Field 1: New Password */}
        <div>
          <label className="block text-xs font-bold text-slate-800 mb-1.5">
            New Password
          </label>
          <div className="relative">
            <input
              type={showPassword ? "text" : "password"}
              {...register("password")}
              disabled={isLoading}
              placeholder="Enter your new password"
              className="w-full pl-3.5 pr-10 py-2.5 text-xs sm:text-sm rounded-lg border border-slate-300 bg-white placeholder:text-slate-400 focus:outline-none focus:border-[#C8A45D] focus:ring-1 focus:ring-[#C8A45D]/40 transition-colors"
            />
            <button
              type="button"
              onClick={() => setShowPassword(!showPassword)}
              className="absolute right-3 top-1/2 -translate-y-1/2 text-slate-400 hover:text-slate-600 transition-colors"
              aria-label={showPassword ? "Hide password" : "Show password"}
            >
              {showPassword ? (
                <EyeOff className="w-4 h-4" />
              ) : (
                <Eye className="w-4 h-4" />
              )}
            </button>
          </div>
          {errors.password && (
            <p className="text-[11px] text-red-600 mt-1">
              {errors.password.message}
            </p>
          )}
        </div>

        {/* Field 2: Confirm Password */}
        <div>
          <label className="block text-xs font-bold text-slate-800 mb-1.5">
            Confirm Password
          </label>
          <div className="relative">
            <input
              type={showConfirmPassword ? "text" : "password"}
              {...register("confirmPassword")}
              disabled={isLoading}
              placeholder="Repeat your new password"
              className="w-full pl-3.5 pr-10 py-2.5 text-xs sm:text-sm rounded-lg border border-slate-300 bg-white placeholder:text-slate-400 focus:outline-none focus:border-[#C8A45D] focus:ring-1 focus:ring-[#C8A45D]/40 transition-colors"
            />
            <button
              type="button"
              onClick={() => setShowConfirmPassword(!showConfirmPassword)}
              className="absolute right-3 top-1/2 -translate-y-1/2 text-slate-400 hover:text-slate-600 transition-colors"
              aria-label={showConfirmPassword ? "Hide password" : "Show password"}
            >
              {showConfirmPassword ? (
                <EyeOff className="w-4 h-4" />
              ) : (
                <Eye className="w-4 h-4" />
              )}
            </button>
          </div>
          {errors.confirmPassword && (
            <p className="text-[11px] text-red-600 mt-1">
              {errors.confirmPassword.message}
            </p>
          )}
        </div>

        {/* Segmented Password Strength Meter (Exact layout from screenshot) */}
        <div className="pt-1">
          <div className="flex items-center justify-between text-[11px] font-semibold mb-1.5">
            <span className="text-slate-600">Password Strength</span>
            <span className={`font-bold ${strengthInfo.color}`}>
              {strengthInfo.text || "None"}
            </span>
          </div>
          <div className="grid grid-cols-4 gap-1.5 h-1.5">
            <div
              className={`rounded-full transition-colors ${
                strengthInfo.score >= 1 ? "bg-emerald-500" : "bg-slate-200"
              }`}
            />
            <div
              className={`rounded-full transition-colors ${
                strengthInfo.score >= 2 ? "bg-emerald-500" : "bg-slate-200"
              }`}
            />
            <div
              className={`rounded-full transition-colors ${
                strengthInfo.score >= 3 ? "bg-emerald-500" : "bg-slate-200"
              }`}
            />
            <div
              className={`rounded-full transition-colors ${
                strengthInfo.score >= 4 ? "bg-emerald-500" : "bg-slate-200"
              }`}
            />
          </div>
        </div>

        {/* Reset Password Button (Champagne Gold #C8A45D) */}
        <div className="pt-2">
          <button
            type="submit"
            disabled={isLoading}
            className="w-full py-2.5 px-4 rounded-lg bg-[#C8A45D] hover:bg-[#b8934c] active:bg-[#a8823b] text-slate-950 font-bold text-sm tracking-wide shadow-sm hover:shadow transition-all disabled:opacity-50 flex items-center justify-center gap-2 cursor-pointer"
          >
            {isLoading ? (
              <>
                <Loader2 className="w-4 h-4 animate-spin text-slate-950" />
                <span>Updating Password...</span>
              </>
            ) : (
              <span>Reset Password</span>
            )}
          </button>
        </div>
      </form>

      {/* Back to Login link */}
      <div className="pt-6 mt-4 border-t border-slate-100 text-center">
        <Link
          href="/login"
          className="text-xs font-semibold text-slate-600 hover:text-slate-950 transition-colors"
        >
          Back to Login
        </Link>
      </div>
    </>
  );
}

export default function ResetPasswordPage() {
  return (
    <div className="min-h-screen w-full flex flex-col md:flex-row bg-[#F8FAFC] text-slate-800 font-sans selection:bg-[#C8A45D] selection:text-white">
      {/* ============================================================ */}
      {/* LEFT HALF: Campus Architecture Background & Golden Branding */}
      {/* ============================================================ */}
      <div className="relative w-full md:w-1/2 min-h-[340px] md:min-h-screen flex flex-col items-center justify-start p-8 md:p-12 lg:p-16 overflow-hidden bg-[#0B1F33]">
        {/* Campus Heritage Image */}
        <div
          className="absolute inset-0 bg-cover bg-center transition-transform duration-700 scale-105"
          style={{ backgroundImage: `url('/images/ihm_campus_bg.jpg')` }}
        />

        {/* Deep Navy Gradient Overlay */}
        <div className="absolute inset-0 bg-gradient-to-b from-[#0B1F33]/90 via-[#0B1F33]/65 to-[#0B1F33]/30 pointer-events-none" />

        {/* Content Overlaid on Campus Image */}
        <div className="relative z-10 w-full flex flex-col items-center text-center mt-6 md:mt-12">
          {/* Golden Institutional Emblem */}
          <div className="w-16 h-16 sm:w-20 sm:h-20 mb-4 flex items-center justify-center">
            <div className="w-16 h-16 sm:w-20 sm:h-20 rounded-full border-2 border-[#C8A45D] bg-[#0B1F33]/80 backdrop-blur-xs flex items-center justify-center shadow-lg">
              <Award className="w-9 h-9 sm:w-11 sm:h-11 text-[#C8A45D]" />
            </div>
          </div>

          {/* Institution Header Typography */}
          <div className="space-y-1">
            <h2 className="text-sm sm:text-base font-bold uppercase tracking-[0.25em] text-white">
              Institute of
            </h2>
            <h1 className="text-2xl sm:text-3xl lg:text-4xl font-extrabold uppercase tracking-[0.18em] text-white leading-tight">
              Hotel Management
            </h1>
            <h3 className="text-lg sm:text-xl font-bold uppercase tracking-[0.3em] text-white pt-1">
              Kolkata
            </h3>
          </div>

          {/* Golden Motto */}
          <div className="mt-5 pt-3">
            <span className="text-xs sm:text-sm font-semibold tracking-[0.35em] uppercase text-[#C8A45D]">
              Learn • Practice • Excel
            </span>
          </div>
        </div>
      </div>

      {/* ============================================================ */}
      {/* RIGHT HALF: Clean Minimal Floating Reset Password Card      */}
      {/* ============================================================ */}
      <div className="w-full md:w-1/2 flex flex-col justify-center items-center p-6 sm:p-10 lg:p-14 bg-[#F8FAFC]">
        <div className="w-full max-w-[420px] bg-white rounded-2xl border border-slate-200/90 shadow-lg p-8 sm:p-10">
          {/* Top Emblem Seal Icon matching the screenshot */}
          <div className="flex flex-col items-center mb-5 text-center">
            <div className="w-12 h-12 rounded-full border-2 border-[#C8A45D]/60 bg-slate-50 flex items-center justify-center mb-2 shadow-2xs">
              <Award className="w-6 h-6 text-slate-800" />
            </div>
            <div className="w-12 h-0.5 bg-[#C8A45D]" />
          </div>

          <Suspense
            fallback={
              <div className="text-center py-6 text-xs text-slate-400">
                Loading parameters...
              </div>
            }
          >
            <ResetPasswordForm />
          </Suspense>
        </div>
      </div>
    </div>
  );
}
