import { useState } from "react";

import {
  LockKeyhole,
  Mail,
  Eye,
  EyeOff,
  ArrowLeft,
  ShieldCheck,
  KeyRound,
  RefreshCw,
} from "lucide-react";
import { Button } from "@/shared/common/ui/button";
import { useNavigate } from "react-router-dom";
import { Input } from "@/shared/common/ui/input";
import { Label } from "@/shared/common/ui/label";
import { motion } from "framer-motion";
import { cn } from "@/shared/lib/utils";
import {
  changePassword,
  requestPasswordReset,
} from "@/record-management/services/api/userService";

const ChangePasswordPage = () => {
  const navigate = useNavigate();
  const [email, setEmail] = useState("");
  const [verificationCode, setVerificationCode] = useState("");
  const [newPassword, setNewPassword] = useState("");
  const [confirmPassword, setConfirmPassword] = useState("");
  const [loading, setLoading] = useState(false);
  const [showPassword, setShowPassword] = useState(false);
  const [showConfirmPassword, setShowConfirmPassword] = useState(false);
  const [message, setMessage] = useState<{
    type: "success" | "error";
    text: string;
  } | null>(null);
  const [resendLoading, setResendLoading] = useState(false);
  const [step, setStep] = useState<"email" | "verify">("email");

  const handleEmailSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setLoading(true);
    setMessage(null);

    try {
      await requestPasswordReset(email);
      setMessage({
        type: "success",
        text: "Verification code sent to your email",
      });
      setStep("verify");
    } catch (err: any) {
      setMessage({
        type: "error",
        text: err.message || "Failed to send verification code",
      });
    } finally {
      setLoading(false);
    }
  };

  const handlePasswordSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setLoading(true);
    setMessage(null);

    if (newPassword !== confirmPassword) {
      setMessage({ type: "error", text: "Passwords do not match" });
      setLoading(false);
      return;
    }

    try {
      await changePassword({
        email,
        verificationCode,
        newPassword,
        confirmPassword,
      });
      setMessage({
        type: "success",
        text: "Password changed successfully! Redirecting...",
      });

      setTimeout(() => navigate("/profile"), 2000);
    } catch (err: any) {
      setMessage({
        type: "error",
        text: err.message || "Failed to change password",
      });
    } finally {
      setLoading(false);
    }
  };

  const handleResendCode = async () => {
    setResendLoading(true);
    try {
      await requestPasswordReset(email);
      setMessage({
        type: "success",
        text: "Verification code resent to your email",
      });
    } catch {
      setMessage({ type: "error", text: "Failed to resend code" });
    } finally {
      setResendLoading(false);
    }
  };

  return (
    <div className="min-h-screen bg-gradient-to-br from-gray-50 to-indigo-50/30 flex items-center justify-center p-4">
      <motion.div
        initial={{ opacity: 0, y: 20 }}
        animate={{ opacity: 1, y: 0 }}
        transition={{ duration: 0.3 }}
        className="w-full max-w-md"
      >
        <div className="border-0 shadow-xl rounded-2xl overflow-hidden bg-white/90 backdrop-blur-sm">
          <div className="bg-gradient-to-r from-indigo-600 to-purple-600 p-6 text-white">
            <div className="flex items-center gap-4">
              <Button
                variant="ghost"
                size="icon"
                onClick={() => navigate(-1)}
                className="rounded-full bg-white/10 hover:bg-white/20"
              >
                <ArrowLeft className="h-5 w-5" />
              </Button>
              <div>
                <h2 className="text-2xl font-bold">
                  {step === "email"
                    ? "Request Password Reset"
                    : "Change Password"}
                </h2>
                <p className="text-sm text-indigo-100">
                  {step === "email"
                    ? "Enter your email to receive a verification code"
                    : "Secure your account with a new password"}
                </p>
              </div>
            </div>
          </div>

          <div className="p-6">
            {message && (
              <motion.div
                initial={{ opacity: 0, y: -10 }}
                animate={{ opacity: 1, y: 0 }}
                className={cn(
                  "p-4 rounded-lg mb-6 flex items-start gap-3",
                  message.type === "success"
                    ? "bg-primary-50 text-primary-700"
                    : "bg-red-50 text-red-700"
                )}
              >
                <ShieldCheck
                  className={cn(
                    "h-5 w-5 flex-shrink-0 mt-0.5",
                    message.type === "success"
                      ? "text-primary-500"
                      : "text-red-500"
                  )}
                />
                <div>
                  <p className="font-medium">{message.text}</p>
                  {message.type === "success" &&
                    message.text.includes("Redirecting") && (
                      <div className="w-full bg-primary-200 rounded-full h-1.5 mt-2">
                        <div
                          className="bg-primary-600 h-1.5 rounded-full"
                          style={{ width: "100%" }}
                        ></div>
                      </div>
                    )}
                </div>
              </motion.div>
            )}

            {step === "email" ? (
              <form onSubmit={handleEmailSubmit} className="space-y-5">
                <div className="space-y-2">
                  <Label htmlFor="email" className="text-gray-700">
                    Email Address
                  </Label>
                  <div className="relative">
                    <div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                      <Mail className="h-5 w-5 text-gray-400" />
                    </div>
                    <Input
                      id="email"
                      type="email"
                      value={email}
                      onChange={(e) => setEmail(e.target.value)}
                      required
                      placeholder="Enter your email"
                      className="pl-10 py-5 rounded-xl border-gray-300 focus:ring-2 focus:ring-indigo-500 focus:border-transparent"
                    />
                  </div>
                </div>

                <Button
                  type="submit"
                  disabled={loading}
                  className="w-full py-6 rounded-xl bg-gradient-to-r from-indigo-600 to-purple-600 hover:from-indigo-700 hover:to-purple-700 text-white font-medium shadow-lg transition-all duration-300"
                >
                  {loading ? (
                    <span className="flex items-center justify-center">
                      <RefreshCw className="animate-spin h-5 w-5 mr-2" />
                      Sending Code...
                    </span>
                  ) : (
                    "Send Verification Code"
                  )}
                </Button>
              </form>
            ) : (
              <form onSubmit={handlePasswordSubmit} className="space-y-5">
                <div className="space-y-2">
                  <Label htmlFor="code" className="text-gray-700">
                    Verification Code
                  </Label>
                  <div className="relative">
                    <div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                      <KeyRound className="h-5 w-5 text-gray-400" />
                    </div>
                    <Input
                      id="code"
                      type="text"
                      value={verificationCode}
                      onChange={(e) => setVerificationCode(e.target.value)}
                      required
                      placeholder="Enter 6-digit code"
                      className="pl-10 py-5 rounded-xl border-gray-300 focus:ring-2 focus:ring-indigo-500 focus:border-transparent"
                    />
                  </div>
                </div>

                <div className="space-y-2">
                  <Label htmlFor="newPassword" className="text-gray-700">
                    New Password
                  </Label>
                  <div className="relative">
                    <div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                      <LockKeyhole className="h-5 w-5 text-gray-400" />
                    </div>
                    <Input
                      id="newPassword"
                      type={showPassword ? "text" : "password"}
                      value={newPassword}
                      onChange={(e) => setNewPassword(e.target.value)}
                      required
                      placeholder="At least 8 characters"
                      className="pl-10 py-5 rounded-xl border-gray-300 focus:ring-2 focus:ring-indigo-500 focus:border-transparent pr-10"
                    />
                    <button
                      type="button"
                      onClick={() => setShowPassword(!showPassword)}
                      className="absolute inset-y-0 right-0 pr-3 flex items-center text-gray-400 hover:text-indigo-600"
                    >
                      {showPassword ? (
                        <EyeOff className="h-5 w-5" />
                      ) : (
                        <Eye className="h-5 w-5" />
                      )}
                    </button>
                  </div>
                  <p className="text-xs text-gray-500 mt-1">
                    Must include uppercase, lowercase, number, and special
                    character
                  </p>
                </div>

                <div className="space-y-2">
                  <Label htmlFor="confirmPassword" className="text-gray-700">
                    Confirm Password
                  </Label>
                  <div className="relative">
                    <div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                      <LockKeyhole className="h-5 w-5 text-gray-400" />
                    </div>
                    <Input
                      id="confirmPassword"
                      type={showConfirmPassword ? "text" : "password"}
                      value={confirmPassword}
                      onChange={(e) => setConfirmPassword(e.target.value)}
                      required
                      placeholder="Re-enter your password"
                      className="pl-10 py-5 rounded-xl border-gray-300 focus:ring-2 focus:ring-indigo-500 focus:border-transparent pr-10"
                    />
                    <button
                      type="button"
                      onClick={() =>
                        setShowConfirmPassword(!showConfirmPassword)
                      }
                      className="absolute inset-y-0 right-0 pr-3 flex items-center text-gray-400 hover:text-indigo-600"
                    >
                      {showConfirmPassword ? (
                        <EyeOff className="h-5 w-5" />
                      ) : (
                        <Eye className="h-5 w-5" />
                      )}
                    </button>
                  </div>
                </div>

                <Button
                  type="submit"
                  disabled={loading}
                  className="w-full py-6 rounded-xl bg-gradient-to-r from-indigo-600 to-purple-600 hover:from-indigo-700 hover:to-purple-700 text-white font-medium shadow-lg transition-all duration-300"
                >
                  {loading ? (
                    <span className="flex items-center justify-center">
                      <RefreshCw className="animate-spin h-5 w-5 mr-2" />
                      Changing Password...
                    </span>
                  ) : (
                    "Change Password"
                  )}
                </Button>

                <div className="text-center">
                  <button
                    type="button"
                    onClick={handleResendCode}
                    disabled={resendLoading}
                    className="text-indigo-600 hover:underline text-sm"
                  >
                    {resendLoading
                      ? "Resending..."
                      : "Resend Verification Code"}
                  </button>
                </div>
              </form>
            )}
          </div>
        </div>
      </motion.div>
    </div>
  );
};

export default ChangePasswordPage;
