import React, { useEffect, useState } from "react";
import { authFetch } from "../../../../utils/authFetch";
import { showToast } from "../../../toast/toastUtils.js";
import { useNavigate } from "react-router-dom";
import { useTranslation } from "react-i18next";

function VerifyUserSetPermission({ userData }) {
  const [allPermissions, setAllPermissions] = useState([]);
  const [selected, setSelected] = useState(
    Array.isArray(userData?.permissions)
      ? userData.permissions.map((p) => (typeof p === "string" ? p : p.name))
      : []
  );
  const [submitting, setSubmitting] = useState(false);
  const [successMsg, setSuccessMsg] = useState("");
  const [errorMsg, setErrorMsg] = useState("");
  const navigate = useNavigate();
  const { t } = useTranslation('verify_user');

  // Fetch all available permissions
  useEffect(() => {
    async function fetchPermissions() {
      try {
        const res = await authFetch(
          `${import.meta.env.VITE_API_BASE_URL}/api/permissions`,
          { method: "GET" }
        );
        console.log("[VerifyUserSetPermission] Permissions fetch response:", res);
        if (!res.ok) throw new Error("Failed to fetch permissions");
        const data = await res.json();
        console.log("[VerifyUserSetPermission] Permissions response data:", data);
        // If permissions are objects, map to names
        setAllPermissions(
          Array.isArray(data.permissions)
            ? data.permissions.map((perm) =>
                typeof perm === "string" ? perm : perm.name
              )
            : []
        );
      } catch (e) {
        setErrorMsg(t('messages.loadPermFail'));
      }
    }
    fetchPermissions();
  }, []);

  // Log selected permissions whenever they change
  useEffect(() => {
    console.log("[VerifyUserSetPermission] Selected permissions:", selected);
  }, [selected]);

  // Handle checkbox change
  const handleCheckbox = (perm) => {
    setSelected((prev) =>
      prev.includes(perm)
        ? prev.filter((p) => p !== perm)
        : [...prev, perm]
    );
  };

  // Handle verify & set permissions
  const handleVerify = async (e) => {
    e.preventDefault();
    setSubmitting(true);
    setSuccessMsg("");
    setErrorMsg("");
    try {
      const res = await authFetch(
        `${import.meta.env.VITE_API_BASE_URL}/api/admin/verify-user/${
          userData.user?.id || userData.user?.user_id || userData.user_id
        }`,
        {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({ permissions: selected }),
        }
      );
      if (!res.ok) {
        const errData = await res.json().catch(() => ({}));
        throw new Error(errData.message || "Verification failed");
      }
      setSuccessMsg(t('messages.verifySuccess'));
      showToast({ type: "success", message: t('messages.verifySuccess') });
      // Redirect after short delay
      setTimeout(() => {
        navigate("/admin/verify-users");
      }, 1200);
    } catch (err) {
      setErrorMsg(err.message || t('messages.verifyFail'));
      showToast({ type: "error", message: err.message || t('messages.verifyFail') });
    }
    setSubmitting(false);
  };

  return (
    <form
      className="bg-white rounded-2xl shadow-xl border border-blue-100 max-w-2xl mx-auto p-8 mt-12"
      onSubmit={handleVerify}
    >
      <h2 className="text-2xl font-bold text-blue-900 mb-6 text-center">
        {t('headings.setPermissionsTitle')}
      </h2>
      <div className="mb-6">
        <p className="text-gray-700 font-medium mb-4 text-center">
          {t('buttons.verify')}
        </p>
        <div className="flex flex-wrap gap-4 justify-center">
          {allPermissions.length === 0 ? (
            <span className="text-gray-400">{t('messages.noPermissions')}</span>
          ) : (
            allPermissions.map((perm) => (
              <label
                key={perm}
                className="flex items-center bg-blue-50 px-4 py-2 rounded-lg shadow border border-blue-200 cursor-pointer hover:border-blue-400 transition"
              >
                <input
                  type="checkbox"
                  className="mr-2 accent-blue-600"
                  checked={selected.includes(perm)}
                  onChange={() => handleCheckbox(perm)}
                  disabled={submitting}
                />
                <span className="text-sm text-blue-900 font-semibold">{perm}</span>
              </label>
            ))
          )}
        </div>
      </div>
      <button
        type="submit"
        className="w-full mt-4 px-6 py-3 bg-blue-700 text-white font-bold rounded-lg shadow hover:bg-blue-800 transition disabled:opacity-60"
        disabled={submitting}
      >
        {submitting ? t('messages.verifying') : t('buttons.verifySet')}
      </button>
      {successMsg && (
        <div className="mt-4 text-green-600 font-semibold text-center">{successMsg}</div>
      )}
      {errorMsg && (
        <div className="mt-4 text-red-600 font-semibold text-center">{errorMsg}</div>
      )}
    </form>
  );
}

export default VerifyUserSetPermission;
