"use client";

import { FormEvent, useState } from "react";
import { KeyRound, ShieldCheck } from "lucide-react";

import { useLocale } from "@/components/providers/locale-provider";

type PasswordRule = {
  label: string;
  test: (value: string) => boolean;
};

const passwordRules: PasswordRule[] = [
  { label: "Minimal 8 karakter", test: (value) => value.length >= 8 },
  { label: "Huruf besar", test: (value) => /[A-Z]/.test(value) },
  { label: "Huruf kecil", test: (value) => /[a-z]/.test(value) },
  { label: "Angka", test: (value) => /\d/.test(value) },
  { label: "Simbol", test: (value) => /[^A-Za-z0-9]/.test(value) }
];

function getPasswordStrength(value: string) {
  const passedRules = passwordRules.filter((rule) => rule.test(value)).length;

  if (!value) return { label: "Belum diisi", tone: "text-slate-500", activeBars: 0 };
  if (passedRules <= 2) return { label: "Lemah", tone: "text-red-600", activeBars: 1 };
  if (passedRules === 3) return { label: "Cukup", tone: "text-amber-600", activeBars: 2 };
  if (passedRules === 4) return { label: "Kuat", tone: "text-teal-700", activeBars: 3 };
  return { label: "Sangat kuat", tone: "text-moss", activeBars: 4 };
}

export function ChangePasswordClient() {
  const { dict } = useLocale();
  const [currentPassword, setCurrentPassword] = useState("");
  const [password, setPassword] = useState("");
  const [passwordConfirmation, setPasswordConfirmation] = useState("");
  const [submitting, setSubmitting] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [message, setMessage] = useState<string | null>(null);

  const passwordStrength = getPasswordStrength(password);

  async function handleSubmit(event: FormEvent<HTMLFormElement>) {
    event.preventDefault();
    setSubmitting(true);
    setError(null);
    setMessage(null);

    try {
      const response = await fetch("/api/v1/auth/change-password", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          current_password: currentPassword,
          password,
          password_confirmation: passwordConfirmation
        })
      });
      const payload = (await response.json()) as {
        message?: string;
        errors?: Record<string, string[]>;
      };
      if (!response.ok) {
        const firstError = payload.errors ? Object.values(payload.errors)[0]?.[0] : undefined;
        throw new Error(firstError ?? payload.message ?? dict.changePassword.failure);
      }

      setMessage(payload.message ?? dict.changePassword.success);
      setCurrentPassword("");
      setPassword("");
      setPasswordConfirmation("");
    } catch (err) {
      setError(err instanceof Error ? err.message : dict.changePassword.failure);
    } finally {
      setSubmitting(false);
    }
  }

  return (
    <section className="grid items-start gap-6 xl:grid-cols-[1.05fr_0.95fr]">
      <article className="ops-card p-6">
        <div className="flex items-start gap-3">
          <div className="rounded-lg bg-moss/10 p-3 text-moss">
            <KeyRound className="h-5 w-5" />
          </div>
          <div>
            <p className="ops-title">{dict.common.changePassword}</p>
            <p className="mt-2 text-[14px] leading-7 text-slate-600">
              {dict.changePassword.description}
            </p>
          </div>
        </div>

        <form className="mt-8 space-y-5" onSubmit={handleSubmit}>
          <label className="block">
            <span className="ops-label">{dict.changePassword.currentPassword}</span>
            <input
              type="password"
              value={currentPassword}
              onChange={(event) => setCurrentPassword(event.target.value)}
              className="ops-input"
            />
          </label>
          <label className="block">
            <span className="ops-label">{dict.changePassword.newPassword}</span>
            <input
              type="password"
              value={password}
              onChange={(event) => setPassword(event.target.value)}
              className="ops-input"
            />
            <div className="mt-3 rounded border border-line/70 bg-slate-50/70 px-4 py-3">
              <div className="flex items-center justify-between gap-4">
                <span className="text-[12px] font-semibold uppercase tracking-[0.05em] text-slate-500">
                  Kekuatan password
                </span>
                <span className={`text-[13px] font-semibold ${passwordStrength.tone}`}>
                  {passwordStrength.label}
                </span>
              </div>
              <div className="mt-3 grid grid-cols-4 gap-2">
                {Array.from({ length: 4 }, (_, index) => {
                  const isActive = index < passwordStrength.activeBars;
                  const colorClass =
                    passwordStrength.activeBars <= 1
                      ? "bg-red-500"
                      : passwordStrength.activeBars === 2
                        ? "bg-amber-500"
                        : "bg-moss";

                  return (
                    <div
                      key={index}
                      className={`h-2 rounded-full ${isActive ? colorClass : "bg-slate-200"}`}
                    />
                  );
                })}
              </div>
              <div className="mt-3 grid gap-2 md:grid-cols-2">
                {passwordRules.map((rule) => {
                  const passed = rule.test(password);
                  return (
                    <div
                      key={rule.label}
                      className={`rounded border px-3 py-2 text-[12px] ${
                        passed
                          ? "border-emerald-200 bg-emerald-50 text-emerald-700"
                          : "border-line/70 bg-white text-slate-500"
                      }`}
                    >
                      {passed ? "✓" : "•"} {rule.label}
                    </div>
                  );
                })}
              </div>
            </div>
          </label>
          <label className="block">
            <span className="ops-label">{dict.changePassword.confirmPassword}</span>
            <input
              type="password"
              value={passwordConfirmation}
              onChange={(event) => setPasswordConfirmation(event.target.value)}
              className="ops-input"
            />
          </label>

          {error ? (
            <div className="rounded border border-ember/30 bg-ember/10 px-4 py-3 text-sm text-ember">
              {error}
            </div>
          ) : null}
          {message ? (
            <div className="rounded border border-moss/30 bg-moss/10 px-4 py-3 text-sm text-moss">
              {message}
            </div>
          ) : null}

          <button type="submit" disabled={submitting} className="ops-btn-primary">
            {submitting ? dict.common.processing : dict.changePassword.submit}
          </button>
        </form>
      </article>

      <article className="ops-card-dark p-6">
        <div className="flex items-start gap-3">
          <div className="rounded-lg border border-white/15 bg-white/10 p-3 text-white">
            <ShieldCheck className="h-5 w-5" />
          </div>
          <div>
            <p className="text-[11px] font-bold uppercase tracking-[0.05em] text-white/70">
              {dict.changePassword.securityTitle}
            </p>
            <ul className="mt-4 space-y-3 text-[13px] leading-6 text-white/85">
              {dict.changePassword.securityTips.map((item) => (
                <li key={item} className="rounded border border-white/15 bg-white/5 px-4 py-3">
                  {item}
                </li>
              ))}
            </ul>
          </div>
        </div>
      </article>
    </section>
  );
}
