import { useState } 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 } from "react-router-dom";
import { changePassword } from "@/shared/services/authService";
import Cookies from "js-cookie";
import { useAuthUser } from "@/record-management/hooks/useAuthUser";
import { t } from "i18next";

export const ResetPassword = () => {
  const navigate = useNavigate();
  const [newPassword, setNewPassword] = useState("");
  const [oldPassword, setOldPassword] = useState("");
  const [confirmPassword, setConfirmPassword] = useState("");
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState("");
  const [showPassword, setShowPassword] = useState(false);
  const [showConfirmPassword, setShowConfirmPassword] = useState(false);
  const { logout } = useAuthUser();
  const handleLogout = () => {
    logout();
  };
  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setError("");

    // Validate old password
    if (!oldPassword) {
      setError(t("msg.currentPasswordRequired"));
      return;
    }

    // Validate new password
    if (!newPassword) {
      setError(t("msg.newPasswordRequired"));
      return;
    }

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

    // Check if new password is same as old password
    if (newPassword === oldPassword) {
      setError(t("msg.passwordMustBeDifferent"));
      return;
    }

    // Validate confirm password
    if (!confirmPassword) {
      setError(t("msg.confirmPasswordRequired"));
      return;
    }

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

    // Check for password complexity
    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 {
      await changePassword({
        oldPassword,
        newPassword,
        confirmPassword,
      });

      toast.success(t("msg.successChange"), {
        description: "Your password has been changed successfully",
      });

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

  return (
    <div
      className="flex items-center justify-center bg-gray-100 dark:bg-gray-900 p-4"
      style={{ height: "100vh" }}
    >
      <div className="w-full max-w-md bg-white dark:bg-gray-800 rounded-xl shadow-lg p-8">
        <div className="mb-8 text-center">
          <img
            src="/assets/smart-office-logo.svg"
            alt="Smart Office Logo"
            className="h-10 mb-6 mx-auto"
          />
          <h1 className="text-2xl font-bold text-gray-900 dark:text-gray-100 mb-2">
            {t("change_password")}
          </h1>
          <p className="text-sm text-gray-500 dark:text-gray-400">
            {t("msg.changePasswordMsg")}
          </p>
        </div>

        <form onSubmit={handleSubmit} className="space-y-6">
          <div className="space-y-4">
            <div className="relative">
              <div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                <Lock className="h-5 w-5 text-gray-400 dark:text-gray-500" />
              </div>
              <Input
                type={showPassword ? "text" : "password"}
                placeholder={t("msg.oldPassword")}
                className="h-10 rounded-md border dark:border-gray-600 px-4 text-sm ps-10 dark:bg-gray-700 dark:text-gray-100"
                value={oldPassword}
                onChange={(e) => setOldPassword(e.target.value)}
                required
              />
              <div
                className="absolute inset-y-0 right-0 pr-3 flex items-center cursor-pointer"
                onClick={() => setShowPassword(!showPassword)}
              >
                {showPassword ? (
                  <EyeOff className="h-4 w-4 text-gray-400 dark:text-gray-500" />
                ) : (
                  <Eye className="h-4 w-4 text-gray-400 dark:text-gray-500" />
                )}
              </div>
            </div>
            <div className="relative">
              <div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                <Lock className="h-5 w-5 text-gray-400 dark:text-gray-500" />
              </div>
              <Input
                type={showPassword ? "text" : "password"}
                placeholder={t("msg.newPassword")}
                className="h-10 rounded-md border dark:border-gray-600 px-4 text-sm ps-10 dark:bg-gray-700 dark:text-gray-100"
                value={newPassword}
                onChange={(e) => setNewPassword(e.target.value)}
                required
              />
              <div
                className="absolute inset-y-0 right-0 pr-3 flex items-center cursor-pointer"
                onClick={() => setShowPassword(!showPassword)}
              >
                {showPassword ? (
                  <EyeOff className="h-4 w-4 text-gray-400 dark:text-gray-500" />
                ) : (
                  <Eye className="h-4 w-4 text-gray-400 dark:text-gray-500" />
                )}
              </div>
            </div>

            <div className="relative">
              <div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                <Lock className="h-5 w-5 text-gray-400 dark:text-gray-500" />
              </div>
              <Input
                type={showConfirmPassword ? "text" : "password"}
                placeholder={t("msg.confirmNewPassword")}
                className="h-10 rounded-md border dark:border-gray-600 px-4 text-sm ps-10 dark:bg-gray-700 dark:text-gray-100"
                value={confirmPassword}
                onChange={(e) => setConfirmPassword(e.target.value)}
                required
              />
              <div
                className="absolute inset-y-0 right-0 pr-3 flex items-center cursor-pointer"
                onClick={() => setShowConfirmPassword(!showConfirmPassword)}
              >
                {showConfirmPassword ? (
                  <EyeOff className="h-4 w-4 text-gray-400 dark:text-gray-500" />
                ) : (
                  <Eye className="h-4 w-4 text-gray-400 dark:text-gray-500" />
                )}
              </div>
            </div>

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

          <div className="flex flex-col gap-4">
            <Button
              type="submit"
              className="w-full h-10 bg-primary hover:bg-primary-300 text-white text-sm"
              disabled={loading}
            >
              {loading ? (
                <span className="flex items-center justify-center">
                  <RefreshCw className="animate-spin h-5 w-5 mr-2" />
                  changing...
                </span>
              ) : (
                t("change_password")
              )}
            </Button>

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

export default ResetPassword;
