"use client";
import { useState, type ReactNode, type SubmitEvent } from "react";
import Link from "next/link";
import { apiFetch, formatApiMsg } from "@/lib/api";
import {
  STRENGTH_BAR_COLORS,
  STRENGTH_LABELS,
  getPasswordRequirements,
  getPasswordStrength,
  getStrengthTextColor,
} from "@/lib/password/strength";

type Step = "form" | "success";

function ChangePasswordSuccess() {
  return (
    <div className="flex flex-col items-center justify-center py-16 text-center">
      <div className="w-20 h-20 bg-[#FCD704]/15 rounded-full flex items-center justify-center mb-6">
        <div className="w-20 h-20 flex items-center justify-center">
          <i className="ri-shield-check-line text-[#FCD704] text-4xl" />
        </div>
      </div>
      <h2 className="text-white font-black text-2xl mb-2">تم تغيير كلمة المرور</h2>
      <p className="text-gray-400 text-sm mb-8 max-w-xs">
        تم تحديث كلمة المرور بنجاح. يُنصح بتسجيل الدخول مجدداً للأمان.
      </p>
      <Link
        href="/profile"
        className="bg-[#FCD704] text-[#13151A] font-bold px-8 py-3.5 rounded-xl cursor-pointer whitespace-nowrap text-sm"
      >
        العودة للملف الشخصي
      </Link>
    </div>
  );
}

function PasswordField({
  label,
  value,
  onChange,
  show,
  onToggleShow,
  placeholder,
  trailingIcon,
}: Readonly<{
  label: string;
  value: string;
  onChange: (value: string) => void;
  show: boolean;
  onToggleShow: () => void;
  placeholder: string;
  trailingIcon?: ReactNode;
}>) {
  return (
    <div>
      <p className="text-gray-400 text-xs text-right mb-2">{label}</p>
      <div className="bg-[#13151A] rounded-xl flex items-center px-4 py-3.5 gap-3 border border-white/5 focus-within:border-[#FCD704]/40 transition-colors">
        <button
          type="button"
          onClick={onToggleShow}
          className="w-5 h-5 flex items-center justify-center cursor-pointer flex-shrink-0"
        >
          <i
            className={`${show ? "ri-eye-off-line" : "ri-eye-line"} text-gray-400 text-base`}
          />
        </button>
        <input
          type={show ? "text" : "password"}
          value={value}
          onChange={(e) => onChange(e.target.value)}
          placeholder={placeholder}
          className="flex-1 bg-transparent text-white text-sm outline-none text-right"
          dir="rtl"
        />
        <div className="w-5 h-5 flex items-center justify-center">
          {trailingIcon}
        </div>
      </div>
    </div>
  );
}

export default function ChangePasswordForm() {
  const [step, setStep] = useState<Step>("form");
  const [showCurrent, setShowCurrent] = useState(false);
  const [showNew, setShowNew] = useState(false);
  const [showConfirm, setShowConfirm] = useState(false);
  const [current, setCurrent] = useState("");
  const [newPass, setNewPass] = useState("");
  const [confirm, setConfirm] = useState("");
  const [error, setError] = useState("");
  const [loading, setLoading] = useState(false);

  const requirements = getPasswordRequirements(newPass);
  const allRulesPass = requirements.every((r) => r.ok);
  const hasUpper = requirements[1].ok;
  const hasNumber = requirements[2].ok;
  const hasSymbol = requirements[3].ok;
  const strength = getPasswordStrength(newPass, hasUpper, hasNumber, hasSymbol);

  const handleSubmit = async (e: SubmitEvent<HTMLFormElement>) => {
    e.preventDefault();
    setError("");
    if (!current) {
      setError("يرجى إدخال كلمة المرور الحالية");
      return;
    }
    if (!allRulesPass) {
      setError("كلمة المرور الجديدة لا تستوفي جميع المتطلبات");
      return;
    }
    if (newPass !== confirm) {
      setError("كلمة المرور الجديدة وتأكيدها غير متطابقتين");
      return;
    }

    setLoading(true);
    await apiFetch("/provider/update-password", {
      method: "PATCH",
      body: JSON.stringify({
        old_password: current,
        password: newPass,
      }),
      successCase: () => {
        setCurrent("");
        setNewPass("");
        setConfirm("");
        setStep("success");
      },
      errorCase: (res) => {
        setError(
          formatApiMsg(res.msg) ||
            "تعذّر تغيير كلمة المرور، تحقق من كلمة المرور الحالية",
        );
      },
    }).finally(() => {
      setLoading(false);
    });
  };

  if (step === "success") {
    return <ChangePasswordSuccess />;
  }

  return (
    <form onSubmit={handleSubmit} className="flex flex-col gap-5 max-w-md mx-auto">
      <PasswordField
        label="كلمة المرور الحالية"
        value={current}
        onChange={setCurrent}
        show={showCurrent}
        onToggleShow={() => setShowCurrent((value) => !value)}
        placeholder="أدخل كلمة المرور الحالية"
        trailingIcon={<i className="ri-lock-2-line text-gray-500 text-base" />}
      />

      <div>
        <PasswordField
          label="كلمة المرور الجديدة"
          value={newPass}
          onChange={setNewPass}
          show={showNew}
          onToggleShow={() => setShowNew((value) => !value)}
          placeholder="أدخل كلمة مرور جديدة"
          trailingIcon={<i className="ri-key-2-line text-gray-500 text-base" />}
        />
        {newPass.length > 0 && (
          <div className="mt-2">
            <div className="flex gap-1 mb-1">
              {[1, 2, 3, 4].map((bar) => (
                <div
                  key={bar}
                  className={`flex-1 h-1 rounded-full transition-all ${bar <= strength ? STRENGTH_BAR_COLORS[strength] : "bg-white/10"}`}
                />
              ))}
            </div>
            <p className={`text-xs text-right ${getStrengthTextColor(strength)}`}>
              قوة كلمة المرور: {STRENGTH_LABELS[strength]}
            </p>
          </div>
        )}
      </div>

      <div>
        <p className="text-gray-400 text-xs text-right mb-2">
          تأكيد كلمة المرور الجديدة
        </p>
        <div
          className={`bg-[#13151A] rounded-xl flex items-center px-4 py-3.5 gap-3 border transition-colors ${confirm && newPass !== confirm ? "border-red-500/50" : "border-white/5 focus-within:border-[#FCD704]/40"}`}
        >
          <button
            type="button"
            onClick={() => setShowConfirm((value) => !value)}
            className="w-5 h-5 flex items-center justify-center cursor-pointer flex-shrink-0"
          >
            <i
              className={`${showConfirm ? "ri-eye-off-line" : "ri-eye-line"} text-gray-400 text-base`}
            />
          </button>
          <input
            type={showConfirm ? "text" : "password"}
            value={confirm}
            onChange={(e) => setConfirm(e.target.value)}
            placeholder="أعد إدخال كلمة المرور الجديدة"
            className="flex-1 bg-transparent text-white text-sm outline-none text-right"
            dir="rtl"
          />
          <div className="w-5 h-5 flex items-center justify-center">
            {confirm ? (
              <i
                className={`${newPass === confirm ? "ri-check-line text-green-400" : "ri-close-line text-red-400"} text-base`}
              />
            ) : (
              <i className="ri-lock-2-line text-gray-500 text-base" />
            )}
          </div>
        </div>
      </div>

      <div className="bg-[#1E2128] rounded-xl p-4 flex flex-col gap-2">
        <p className="text-gray-400 text-xs font-semibold mb-1">
          متطلبات كلمة المرور:
        </p>
        {requirements.map((r) => (
          <div key={r.text} className="flex items-center gap-2 ">
            <span className={`text-xs ${r.ok ? "text-gray-300" : "text-gray-500"}`}>
              {r.text}
            </span>
            <div
              className={`w-4 h-4 flex items-center justify-center rounded-full ${r.ok ? "bg-[#FCD704]/20" : "bg-white/5"}`}
            >
              <i
                className={`text-xs ${r.ok ? "ri-check-line text-[#FCD704]" : "ri-close-line text-gray-600"}`}
              />
            </div>
          </div>
        ))}
      </div>

      {error && (
        <div className="bg-red-500/10 border border-red-500/30 rounded-xl p-4 text-center">
          <p className="text-red-400 text-sm">{error}</p>
        </div>
      )}

      <button
        type="submit"
        disabled={loading || !allRulesPass || newPass !== confirm}
        className="w-full bg-[#FCD704] text-[#13151A] font-bold text-base py-4 rounded-xl cursor-pointer whitespace-nowrap disabled:opacity-60 flex items-center justify-center gap-2"
      >
        {loading ? (
          <>
            <div className="w-5 h-5 border-2 border-[#13151A]/30 border-t-[#13151A] rounded-full animate-spin" />
            جاري الحفظ...
          </>
        ) : (
          "تغيير كلمة المرور"
        )}
      </button>

      <Link
        href="/profile"
        className="text-gray-400 text-sm text-center cursor-pointer whitespace-nowrap hover:text-white transition-colors"
      >
        إلغاء والعودة
      </Link>
    </form>
  );
}
