import { useState, useEffect } from "react";
import { Button } from "@/shared/common/ui/button";
import { Input } from "@/shared/common/ui/input";
import { Lock, ArrowLeft, RefreshCw, Eye, EyeOff } from "lucide-react";
import { toast } from "sonner";
import { useNavigate, useSearchParams } from "react-router-dom";
import { setPassword } from "@/shared/services/authService";
import { useTranslation } from "react-i18next";

export const ResetPassword = () => {
  const navigate = useNavigate();
  const [searchParams] = useSearchParams();
  const { t } = useTranslation();

  // Get params from URL
  const email = searchParams.get("email") || "";
  const verificationCode = searchParams.get("verificationCode") || "";
  const userId = searchParams.get("userId") || "";

  const [newPassword, setNewPassword] = useState("");
  const [confirmPassword, setConfirmPassword] = useState("");
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState("");
  const [showPassword, setShowPassword] = useState(false);
  const [showConfirmPassword, setShowConfirmPassword] = useState(false);

  // Check if we have all required parameters from the URL
  useEffect(() => {
    if (!userId && !email) {
      setError(
        "Missing required parameters in the reset link. Please request a new password reset link.",
      );
    } else if (!verificationCode) {
      setError(
        "Missing verification code in the reset link. Please request a new password reset link.",
      );
    } else {
      setError("");
    }
  }, []);

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

    // Validate passwords with specific error messages
    if (!newPassword) {
      setError(t("msg.newPasswordRequired"));
      return;
    }

    if (newPassword.length < 8) {
      setError(t("msg.passwordMinLength"));
      return;
    }

    if (!confirmPassword) {
      setError(t("msg.confirmPasswordRequired"));
      return;
    }

    if (newPassword !== confirmPassword) {
      setError(t("msg.passwordMismatch"));
      return;
    }

    // Check for password complexity (optional but recommended)
    const hasUpperCase = /[A-Z]/.test(newPassword);
    const hasLowerCase = /[a-z]/.test(newPassword);
    const hasNumbers = /\d/.test(newPassword);
    const hasSpecialChar = /[!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]/.test(newPassword);

    const complexityErrors = [];
    if (!hasUpperCase) complexityErrors.push(t("msg.uppercaseLetter"));
    if (!hasLowerCase) complexityErrors.push(t("msg.lowercaseLetter"));
    if (!hasNumbers) complexityErrors.push(t("msg.number"));
    if (!hasSpecialChar) complexityErrors.push(t("msg.specialCharacter"));

    if (complexityErrors.length > 0) {
      setError(t("msg.passwordComplexity") + " " + complexityErrors.join(", "));
      return;
    }

    setLoading(true);

    try {
      const payload: {
        userId?: string;
        email?: string;
        verificationCode: string;
        newPassword: string;
        confirmPassword: string;
      } = {
        verificationCode,
        newPassword,
        confirmPassword,
      };

      // Include both userId and email if available (API expects both)
      if (userId) {
        payload.userId = userId;
      }
      if (email) {
        payload.email = email;
      }

      await setPassword(payload);

      toast.success(t("msg.successChange"), {
        description: t("msg.passwordResetSuccess"),
      });

      // Redirect to login page after successful reset
      setTimeout(() => navigate("/"), 2000);
    } catch (error: unknown) {
      const message = (error as any)?.message || t("msg.failedChange");
      setError(message);
      toast.error(t("msg.failedChange"), {
        description: message,
      });
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="min-h-screen bg-gray-100 p-4 flex items-center justify-center">
      <div className="w-full max-w-md bg-white rounded-xl shadow-lg p-6 md:p-8">
        <div className="mb-6 md:mb-8 text-center">
          <img
            src="/assets/smart-office-logo.svg"
            alt="Smart Office Logo"
            className="h-8 md:h-10 mb-4 md:mb-6 mx-auto"
          />
          <h1 className="text-xl md:text-2xl font-bold text-gray-900 mb-2">
            Reset Password
          </h1>
          <p className="text-xs md:text-sm text-gray-500">
            Set a new password for your account
          </p>
          {email && (
            <p className="text-xs text-gray-400 mt-1 truncate max-w-full px-2">
              Email: {email}
            </p>
          )}
          {userId && (
            <p className="text-xs text-gray-400 mt-1 truncate max-w-full px-2">
              User ID: {userId}
            </p>
          )}
        </div>

        <form onSubmit={handleSubmit} className="space-y-4 md:space-y-6">
          <div className="space-y-3">
            <div className="relative">
              <div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                <Lock className="h-4 w-4 md:h-5 md:w-5 text-gray-400" />
              </div>
              <Input
                type={showPassword ? "text" : "password"}
                placeholder="New Password"
                className="h-10 rounded-md border px-4 text-sm ps-10 pr-10 text-black placeholder:text-gray-500"
                value={newPassword}
                onChange={(e) => setNewPassword(e.target.value)}
                required
              />
              <button
                type="button"
                className="absolute inset-y-0 right-0 pr-3 flex items-center"
                onClick={() => setShowPassword(!showPassword)}
                aria-label={showPassword ? "Hide password" : "Show password"}
              >
                {showPassword ? (
                  <EyeOff className="h-4 w-4 text-gray-400" />
                ) : (
                  <Eye className="h-4 w-4 text-gray-400" />
                )}
              </button>
            </div>

            <div className="relative">
              <div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                <Lock className="h-4 w-4 md:h-5 md:w-5 text-gray-400" />
              </div>
              <Input
                type={showConfirmPassword ? "text" : "password"}
                placeholder="Confirm New Password"
                className="h-10 rounded-md border px-4 text-sm ps-10 pr-10 text-black placeholder:text-gray-500"
                value={confirmPassword}
                onChange={(e) => setConfirmPassword(e.target.value)}
                required
              />
              <button
                type="button"
                className="absolute inset-y-0 right-0 pr-3 flex items-center"
                onClick={() => setShowConfirmPassword(!showConfirmPassword)}
                aria-label={
                  showConfirmPassword ? "Hide password" : "Show password"
                }
              >
                {showConfirmPassword ? (
                  <EyeOff className="h-4 w-4 text-gray-400" />
                ) : (
                  <Eye className="h-4 w-4 text-gray-400" />
                )}
              </button>
            </div>

            {error && (
              <div className="bg-red-50 border border-red-200 rounded-md p-3 md:p-4">
                <p className="text-xs md:text-sm text-red-700 font-medium">
                  {error}
                </p>
              </div>
            )}
          </div>

          <div className="flex flex-col gap-3">
            <Button
              type="submit"
              className="w-full h-10 bg-primary hover:bg-primary-300 text-white text-sm"
              disabled={loading || (!userId && !email) || !verificationCode}
            >
              {loading ? (
                <span className="flex items-center justify-center">
                  <RefreshCw className="animate-spin h-4 w-4 md:h-5 md:w-5 mr-2" />
                  Resetting...
                </span>
              ) : (
                "Reset Password"
              )}
            </Button>

            <Button
              type="button"
              variant="outline"
              className="w-full h-10 text-sm"
              onClick={() => navigate("/")}
            >
              <ArrowLeft className="h-4 w-4 mr-2" />
              Back to Login
            </Button>
          </div>
        </form>
      </div>
    </div>
  );
};

export default ResetPassword;
