"use client";

import React, { useState, useEffect, useMemo } from "react";
import { Card, Segmented, Space, Input } from "antd";
import InputItem from "@/app/Components/FormItems";
import { handleChange } from "@/app/utils/form";
import { CardTitle } from "@/app/utils/CardTitle";
import { appPages } from "@/app/utils/allPages";
import { getStatusById } from "@/app/utils/status";
import { parseArrayField } from "@/app/utils/parseArrayField";
import { ROLE_TYPES } from "@/app/utils/roleTypes";
import { mapToLabelValue } from "@/app/utils/mapToLabelValue";

/* =====================================================
   HELPERS
===================================================== */

const formatText = (val = "") => {
  if (typeof val !== "string") return "";

  return val
    // camelCase → camel Case
    .replace(/([a-z])([A-Z])/g, "$1 $2")
    // hyphen / underscore → space
    .replace(/[-_]+/g, " ")
    // normalize spaces
    .replace(/\s+/g, " ")
    .trim()
    // Title Case
    .split(" ")
    .map(
      (word) =>
        word.charAt(0).toUpperCase() + word.slice(1).toLowerCase()
    )
    .join(" ");
};



/** Safely trim a string or return fallback */
const safeKey = (val, fallback = "unknown") => {
  if (typeof val === "string" && val.trim()) return val.trim();
  return fallback;
};

/** Normalize privilege keys before save */
const normalizePrivileges = (privileges = {}) => {
  const clean = {};
  Object.entries(privileges).forEach(([key, value]) => {
    if (typeof key === "string" && key.trim()) {
      clean[key.trim()] = value;
    }
  });
  return clean;
};

export default function RoleForm({
  form,
  setForm,
  isEditMode,
}) {
  const [search, setSearch] = useState("");

  /* =====================================================
     NORMALIZE STATUS (STRING | ARRAY | OBJECT SAFE)
  ===================================================== */
  const normalizedStatus = useMemo(() => {
    return parseArrayField(form?.status);
  }, [form?.status]);

  /* =====================================================
     DEFAULT STATUS (ADD MODE ONLY)
  ===================================================== */
  useEffect(() => {
    if (isEditMode) return;

    if (!normalizedStatus.length) {
      const defaultStatus = getStatusById(12);
      if (!defaultStatus) return;

      setForm((prev) => ({
        ...prev,
        status: [
          {
            id: defaultStatus.id,
            key: defaultStatus.key,
            label: defaultStatus.label,
          },
        ],
      }));
    }
  }, [isEditMode, normalizedStatus, setForm]);

  /* =====================================================
     PERMISSION CHANGE
  ===================================================== */
  const handlePermissionChange = (
    value,
    key,
    subMenu = null,
    isParent = false
  ) => {
    if (typeof key !== "string") return;

    setForm((prev) => {
      const prevPrivileges = prev.privileges || {};

      let permission = { view: false, modify: false };
      if (value === "View") permission.view = true;
      if (value === "Modify")
        permission = { view: true, modify: true };

      const updated = {
        ...prevPrivileges,
        [safeKey(key)]: permission,
      };

      if (isParent && Array.isArray(subMenu)) {
        subMenu.forEach((sub) => {
          if (typeof sub?.item === "string") {
            updated[safeKey(sub.item)] = { ...permission };
          }
        });
      }

      return {
        ...prev,
        privileges: normalizePrivileges(updated),
      };
    });
  };

  /* =====================================================
     QUICK ACTIONS
  ===================================================== */
  const handleQuickAction = (value) => {
    let newPrivileges = {};

    appPages
      .filter((item) => item.role)
      .forEach((item) => {
        if (typeof item.item !== "string") return;

        let permission = { view: false, modify: false };
        if (value === "Set All to View") permission.view = true;
        if (value === "Set All to Full Access")
          permission = { view: true, modify: true };

        newPrivileges[safeKey(item.item)] = permission;

        if (Array.isArray(item.subMenu)) {
          item.subMenu
            .filter((sub) => sub.role)
            .forEach((sub) => {
              if (typeof sub.item === "string") {
                newPrivileges[safeKey(sub.item)] = {
                  ...permission,
                };
              }
            });
        }
      });

    setForm((prev) => ({
      ...prev,
      duration: value,
      privileges: normalizePrivileges(newPrivileges),
    }));
  };

  /* =====================================================
     GET SEGMENT VALUE
  ===================================================== */
  const getSegmentValue = (key) => {
    if (typeof key !== "string") return "None";
    const perm = form.privileges?.[safeKey(key)];
    if (!perm) return "None";
    if (perm.modify) return "Modify";
    if (perm.view) return "View";
    return "None";
  };

  /* =====================================================
     RENDER PARENT + CHILD
  ===================================================== */
const renderParentGroup = (item) => {
  const searchText = search.toLowerCase();
  const parentText = formatText(item.label || item.item || "").toLowerCase();

  const parentMatches =
    parentText.includes(searchText) ||
    item.subMenu?.some(
      (sub) =>
        sub.role &&
        formatText(sub.label || sub.item || "")
          .toLowerCase()
          .includes(searchText)
    );

  if (!parentMatches) return null;

  const filteredChildren = item.subMenu
    ?.filter((sub) => sub.role)
    .filter((sub) =>
      formatText(sub.label || sub.item || "")
        .toLowerCase()
        .includes(searchText)
    );

  return (
    <li
      key={safeKey(item.item)}
      className="border border-gray-200 dark:border-gray-800 rounded-2xl p-7 space-y-3"
    >
      {/* PARENT */}
      <div className="flex justify-between items-center">
        <span className="font-semibold text-gray-900 dark:text-gray-100">
          {formatText(item.label || item.item)}
        </span>

        <Segmented
        size="large"
          value={getSegmentValue(item.item)}
          options={["None", "View", "Modify"]}
          onChange={(e) => handlePermissionChange(e, item.item)}
        />
      </div>

      {/* CHILDREN */}
      {filteredChildren?.length > 0 && (
        <div className="space-y-2">

          {filteredChildren.map((sub, idx) => (
            <div
              key={`${safeKey(sub.item)}-${idx}`}
              className="flex justify-between items-center border border-gray-200 dark:border-gray-800  rounded-xl px-4 py-2 hover:bg-gray-50 dark:hover:bg-gray-500 dark:hover:bg-gray-900 transition"
            >
              <span className="text-sm text-gray-700 dark:text-gray-300">
                {formatText(sub.label || sub.item)}
              </span>

              <Segmented
                size="medium"
                value={getSegmentValue(sub.item)}
                options={["None", "View", "Modify"]}
                onChange={(e) =>
                  handlePermissionChange(e, sub.item)
                }
              />
            </div>
          ))}

        </div>
      )}
    </li>
  );
};


  /* =====================================================
     RENDER
  ===================================================== */
return (
  <div className="container !my-6 grid gap-12">

    {/* ================= ROLE INFO ================= */}
    <section className="space-y-6">
  <div className="grid md:grid-cols-2 gap-6">
        <InputItem
          type="text"
          label="Role Name"
          name="role_name"
          value={form.role_name}
          onChange={(e) => handleChange(e, setForm)}
        />

        <InputItem
          type="select"
          label="Role Type"
          name="role_type"
          value={form.role_type}
          onChange={(e) => handleChange(e, setForm)}
          options={mapToLabelValue(ROLE_TYPES, "label", "id")}
        />
      </div>

    </section>


    {/* ================= PRIVILEGES ================= */}
    <section className="space-y-6">

      <div className="flex flex-col lg:flex-row lg:items-center justify-between gap-4">

        <h2 className="text-base font-semibold text-gray-900 dark:text-gray-100 uppercase">
          Privileges
        </h2>

        <div className="flex flex-col sm:flex-row gap-4 w-full lg:w-auto">

          <Segmented
            options={[
              "Set All to None",
              "Set All to View",
              "Set All to Full Access",
            ]}
            size="large"
            value={form.duration}
            onChange={handleQuickAction}
          />

          <InputItem
            type="text"
            placeholder="Search menu..."
            value={search}
            onChange={(e) => setSearch(e.target.value)}
            allowClear
            className="max-w-sm"
          />

        </div>
      </div>

      <div >

        <ul className="grid gap-6">
          {appPages
            .filter((item) => item.role)
            .filter((item) => item.item !== "dashboard")
            .map(renderParentGroup)}
        </ul>

      </div>

    </section>


    {/* ================= STATUS ================= */}
    <section className="space-y-6">

      <h2 className="text-base font-semibold text-gray-900 dark:text-gray-100 uppercase">
        Status
      </h2>

      <InputItem
          type="select"
          label="Status"
          name="status"
          value={parseArrayField(form.status)}
          onChange={(e) => handleChange(e, setForm)}
          options={[getStatusById(12), getStatusById(13)]}
          arrayType
        />
     

    </section>

  </div>
);



}
