import { A, useNavigate, useParams } from '@solidjs/router';
import { createEffect, createMemo, createResource, createSignal, For, Show } from 'solid-js';

const API = '';

type Permission = { key: string; module: string; action: string };
type Department = { id: string; name: string };
type RoleDetail = {
  id: string;
  key: string;
  name: string;
  audience: string;
  description?: string;
  department_id?: string;
  department_name?: string;
  is_active: boolean;
  can_approve_requests: boolean;
  can_manage_system_settings: boolean;
  permission_keys: string[];
  created_at: string;
};

const STATIC_MODULES = [
  'Department Management', 'Designation Management', 'Internal Role Management',
  'Employee Management', 'External Role Management',
  'Internal Dashboard Management', 'External Dashboard Management', 'Verification Management',
  'Approval Management', 'Users Management', 'Company Management', 'Candidate Management',
  'Customer Management', 'Photographer Management', 'Makeup Artist Management',
  'Tutor Management', 'Developer Management', 'Fitness Trainer Management',
  'Graphic Designer Management', 'Social Media Management', 'Video Editor Management',
  'Catering Services Management', 'Jobs Management', 'Leads Management',
  'Applications Management', 'Responses Management', 'Review Management',
  'Pricing Management', 'Credit Management', 'Coupon Management', 'Discount Management',
  'Tax Management', 'Order Management', 'Invoice Management', 'Ledger Management',
  'Knowledge Base Management', 'Support Management', 'Report Management', 'Notifications',
];
const ACTIONS = ['View', 'Create', 'Update', 'Delete'] as const;

function makeKey(module: string, action: string) {
  return `${module.replace(/ /g, '_').toLowerCase()}:${action.toLowerCase()}`;
}

async function loadPermissions(): Promise<Permission[]> {
  try {
    const res = await fetch(`${API}/api/admin/permissions`);
    if (!res.ok) throw new Error();
    const data = await res.json();
    return Array.isArray(data) ? data : [];
  } catch {
    return STATIC_MODULES.flatMap((module) =>
      ACTIONS.map((action) => ({
        key: makeKey(module, action),
        module,
        action,
      })),
    );
  }
}

async function loadDepartments(): Promise<Department[]> {
  try {
    const res = await fetch(`${API}/api/admin/departments`);
    if (!res.ok) return [];
    const data = await res.json();
    return Array.isArray(data) ? data : (data.departments ?? []);
  } catch {
    return [];
  }
}

async function loadRole(id: string): Promise<RoleDetail | null> {
  try {
    const res = await fetch(`${API}/api/admin/roles/${id}`);
    if (!res.ok) return null;
    return res.json();
  } catch {
    return null;
  }
}

type SubTab = 'general' | 'module' | 'settings';

export default function EditInternalRolePage() {
  const params = useParams();
  const navigate = useNavigate();

  const [role] = createResource(() => params.id, loadRole);
  const [permissions] = createResource(loadPermissions);
  const [departments] = createResource(loadDepartments);

  const [subTab, setSubTab] = createSignal<SubTab>('general');

  // General Information
  const [roleName, setRoleName] = createSignal('');
  const [roleCode, setRoleCode] = createSignal('');
  const [departmentId, setDepartmentId] = createSignal('');
  const [description, setDescription] = createSignal('');

  // Module Access
  const [selectedKeys, setSelectedKeys] = createSignal<Set<string>>(new Set());

  // Role Settings
  const [isActive, setIsActive] = createSignal(true);
  const [canApprove, setCanApprove] = createSignal(false);
  const [canManage, setCanManage] = createSignal(false);

  const [saving, setSaving] = createSignal(false);
  const [error, setError] = createSignal('');

  // Pre-populate from loaded role
  createEffect(() => {
    const r = role();
    if (!r) return;
    setRoleName(r.name);
    setRoleCode(r.key);
    setDepartmentId(r.department_id ?? '');
    setDescription(r.description ?? '');
    setIsActive(r.is_active);
    setCanApprove(r.can_approve_requests);
    setCanManage(r.can_manage_system_settings);
    setSelectedKeys(new Set(r.permission_keys ?? []));
  });

  // Group permissions by module
  const permsByModule = createMemo(() => {
    const src = permissions() ?? [];
    const map: Record<string, Permission[]> = {};
    src.forEach((p) => {
      if (!map[p.module]) map[p.module] = [];
      map[p.module].push(p);
    });
    // ensure all static modules present
    STATIC_MODULES.forEach((module) => {
      if (!map[module]) {
        map[module] = ACTIONS.map((action) => ({ key: makeKey(module, action), module, action }));
      }
    });
    return map;
  });

  const allModules = createMemo(() => STATIC_MODULES);

  const toggleKey = (key: string) => {
    const next = new Set(selectedKeys());
    if (next.has(key)) next.delete(key);
    else next.add(key);
    setSelectedKeys(next);
  };

  const toggleRow = (module: string) => {
    const perms = permsByModule()[module] ?? [];
    const allSelected = perms.every((p) => selectedKeys().has(p.key));
    const next = new Set(selectedKeys());
    if (allSelected) perms.forEach((p) => next.delete(p.key));
    else perms.forEach((p) => next.add(p.key));
    setSelectedKeys(next);
  };

  const selectAll = () => {
    const all = STATIC_MODULES.flatMap((m) => ACTIONS.map((a) => makeKey(m, a)));
    setSelectedKeys(new Set(all as string[]));
  };
  const deselectAll = () => setSelectedKeys(new Set<string>());
  const allSelected = () => {
    const total = STATIC_MODULES.length * ACTIONS.length;
    return selectedKeys().size === total;
  };

  const handleSave = async () => {
    if (saving()) return;
    if (!roleName().trim()) { setError('Role name is required'); setSubTab('general'); return; }
    setError('');
    try {
      setSaving(true);
      const accessToken = typeof sessionStorage !== 'undefined'
        ? (sessionStorage.getItem('nxtgauge_admin_access_token') || '').trim()
        : '';
      const res = await fetch(`${API}/api/admin/roles/${params.id}`, {
        method: 'PATCH',
        headers: {
          'Content-Type': 'application/json',
          Accept: 'application/json',
          ...(accessToken ? { Authorization: `Bearer ${accessToken}` } : {}),
        },
        credentials: 'include',
        body: JSON.stringify({
          name: roleName().trim(),
          description: description().trim() || null,
          department_id: departmentId() || null,
          is_active: isActive(),
          can_approve_requests: canApprove(),
          can_manage_system_settings: canManage(),
          permission_keys: [...selectedKeys()],
        }),
      });
      const raw = await res.text();
      let message = '';
      if (raw) {
        try {
          const parsed = JSON.parse(raw) as { message?: string; error?: string };
          message = parsed?.message || parsed?.error || '';
        } catch {
          message = raw;
        }
      }
      if (!res.ok) throw new Error(message || `Failed to update role (${res.status})`);
      navigate(`/admin/roles/${params.id}`);
    } catch (err: any) {
      setError(String(err?.message || '').trim() || 'Failed to update role');
    } finally {
      setSaving(false);
    }
  };

  return (
      <div class="flex flex-col -mx-6 -mt-6 min-h-full">

        {/* Page title */}
        <div class="bg-white border-b border-[#e5e7eb] px-6 py-5">
          <h1 class="text-[20px] font-semibold text-[#0D0D2A]">Internal Role Management</h1>
          <p class="text-[13px] text-[rgba(13,13,42,0.5)] mt-0.5">Manage internal roles and permissions</p>
        </div>

        <div class="p-6">
          <div class="rounded-xl border border-[#e5e7eb] bg-white shadow-sm overflow-hidden">

            {/* Outer tabs */}
            <div class="flex border-b border-[#e5e7eb] px-6">
              <A
                href="/admin/roles"
                class="py-4 text-[14px] font-medium text-[rgba(13,13,42,0.5)] hover:text-[#0D0D2A] mr-6"
              >
                All Roles
              </A>
              <button class="relative py-4 text-[14px] font-semibold text-[#fa5014]">
                Edit Role
                <span class="absolute bottom-0 left-0 right-0 h-[2px] bg-[#fa5014] rounded-t" />
              </button>
            </div>

            <Show when={role.loading}>
              <div class="px-6 py-10 text-center text-[13px] text-[rgba(13,13,42,0.4)]">Loading…</div>
            </Show>

            <Show when={!role.loading}>
              {/* Inner sub-tabs */}
              <div class="flex border-b border-[#e5e7eb] px-6 gap-6">
                <For each={[
                  { key: 'general', label: 'General Information' },
                  { key: 'module', label: 'Module Access' },
                  { key: 'settings', label: 'Role Settings' },
                ] as const}>{(t) => (
                  <button
                    onClick={() => setSubTab(t.key)}
                    class={`relative py-3.5 text-[13px] font-medium transition-colors ${
                      subTab() === t.key
                        ? 'text-[#0D0D2A] font-semibold'
                        : 'text-[rgba(13,13,42,0.5)] hover:text-[#0D0D2A]'
                    }`}
                  >
                    {t.label}
                    <Show when={subTab() === t.key}>
                      <span class="absolute bottom-0 left-0 right-0 h-[2px] bg-[#0D0D2A] rounded-t" />
                    </Show>
                  </button>
                )}</For>
              </div>

              {/* Error banner */}
              <Show when={error()}>
                <div class="mx-6 mt-4 rounded-lg border border-red-200 bg-red-50 px-4 py-3 text-[13px] text-red-700">
                  {error()}
                </div>
              </Show>

              {/* ── Tab: General Information ── */}
              <Show when={subTab() === 'general'}>
                <div class="p-6 space-y-5">
                  <div class="grid grid-cols-2 gap-5">
                    <div>
                      <label class="block text-[13px] font-medium text-[#0D0D2A] mb-1.5">
                        Role Name <span class="text-red-500">*</span>
                      </label>
                      <input
                        type="text"
                        placeholder="Enter role name"
                        value={roleName()}
                        onInput={(e) => setRoleName(e.currentTarget.value)}
                        class="w-full px-3 py-2.5 text-[13px] border border-[#e5e7eb] rounded-lg outline-none focus:border-[#fa5014] focus:ring-1 focus:ring-[#fa5014] text-[#0D0D2A] placeholder-[rgba(13,13,42,0.3)]"
                      />
                    </div>
                    <div>
                      <label class="block text-[13px] font-medium text-[#0D0D2A] mb-1.5">
                        Role Code
                      </label>
                      <input
                        type="text"
                        value={roleCode()}
                        disabled
                        class="w-full px-3 py-2.5 text-[13px] border border-[#e5e7eb] rounded-lg bg-[#fafafa] text-[rgba(13,13,42,0.4)] cursor-not-allowed"
                      />
                    </div>
                  </div>
                  <div>
                    <label class="block text-[13px] font-medium text-[#0D0D2A] mb-1.5">Department</label>
                    <select
                      value={departmentId()}
                      onChange={(e) => setDepartmentId(e.currentTarget.value)}
                      class="w-full px-3 py-2.5 text-[13px] border border-[#e5e7eb] rounded-lg outline-none focus:border-[#fa5014] focus:ring-1 focus:ring-[#fa5014] bg-white text-[#0D0D2A]"
                    >
                      <option value="">Select department</option>
                      <For each={departments() ?? []}>
                        {(dept) => (
                          <option value={dept.id} selected={dept.id === departmentId()}>
                            {dept.name}
                          </option>
                        )}
                      </For>
                    </select>
                  </div>
                  <div>
                    <label class="block text-[13px] font-medium text-[#0D0D2A] mb-1.5">Description</label>
                    <textarea
                      placeholder="Enter role description"
                      value={description()}
                      onInput={(e) => setDescription(e.currentTarget.value)}
                      rows={4}
                      class="w-full px-3 py-2.5 text-[13px] border border-[#e5e7eb] rounded-lg outline-none focus:border-[#fa5014] focus:ring-1 focus:ring-[#fa5014] text-[#0D0D2A] placeholder-[rgba(13,13,42,0.3)] resize-none"
                    />
                  </div>
                </div>
              </Show>

              {/* ── Tab: Module Access ── */}
              <Show when={subTab() === 'module'}>
                <div class="p-6">
                  <p class="text-[13px] text-[rgba(13,13,42,0.5)] mb-4">
                    Configure module access permissions for this role.
                  </p>
                  <div class="overflow-x-auto rounded-lg border border-[#e5e7eb]">
                    <table class="w-full">
                      <thead>
                        <tr class="bg-[#0D0D2A] text-white text-[12px] font-semibold uppercase tracking-wide">
                          <th class="px-5 py-3 text-left w-[40%]"> </th>
                          <th class="px-4 py-3 text-center">View</th>
                          <th class="px-4 py-3 text-center">Create</th>
                          <th class="px-4 py-3 text-center">Update</th>
                          <th class="px-4 py-3 text-center">Delete</th>
                          <th class="px-4 py-3 text-center">
                            <button
                              type="button"
                              onClick={() => (allSelected() ? deselectAll() : selectAll())}
                              class="text-[11px] font-semibold text-white hover:text-[#fca87c] transition-colors whitespace-nowrap"
                            >
                              {allSelected() ? 'Deselect All' : 'Select All'}
                            </button>
                          </th>
                        </tr>
                      </thead>
                      <tbody class="divide-y divide-[#e5e7eb]">
                        <For each={allModules()}>
                          {(module) => {
                            const rowAllSelected = () =>
                              ACTIONS.every((a) => selectedKeys().has(makeKey(module, a)));
                            return (
                              <tr class="hover:bg-[#fafafa]">
                                <td class="px-5 py-3.5 text-[13px] font-medium text-[#0D0D2A]">
                                  {module}
                                </td>
                                <For each={ACTIONS}>
                                  {(action) => {
                                    const key = makeKey(module, action);
                                    return (
                                      <td class="px-4 py-3.5 text-center">
                                        <input
                                          type="checkbox"
                                          checked={selectedKeys().has(key)}
                                          onChange={() => toggleKey(key)}
                                          class="h-4 w-4 accent-[#fa5014] cursor-pointer"
                                        />
                                      </td>
                                    );
                                  }}
                                </For>
                                <td class="px-4 py-3.5 text-center">
                                  <input
                                    type="checkbox"
                                    checked={rowAllSelected()}
                                    onChange={() => toggleRow(module)}
                                    class="h-4 w-4 accent-[#fa5014] cursor-pointer"
                                  />
                                </td>
                              </tr>
                            );
                          }}
                        </For>
                      </tbody>
                    </table>
                  </div>
                </div>
              </Show>

              {/* ── Tab: Role Settings ── */}
              <Show when={subTab() === 'settings'}>
                <div class="p-6 space-y-6">
                  <div>
                    <p class="text-[13px] font-semibold text-[#0D0D2A] mb-3">Role Status</p>
                    <div class="flex items-center gap-2">
                      <button
                        type="button"
                        onClick={() => setIsActive(true)}
                        class={`px-5 py-2 rounded-lg text-[13px] font-medium transition-colors ${
                          isActive()
                            ? 'bg-[#fa5014] text-white'
                            : 'border border-[#e5e7eb] text-[rgba(13,13,42,0.6)] hover:border-[#0D0D2A]'
                        }`}
                      >
                        Active
                      </button>
                      <button
                        type="button"
                        onClick={() => setIsActive(false)}
                        class={`px-5 py-2 rounded-lg text-[13px] font-medium transition-colors ${
                          !isActive()
                            ? 'bg-[#fa5014] text-white'
                            : 'border border-[#e5e7eb] text-[rgba(13,13,42,0.6)] hover:border-[#0D0D2A]'
                        }`}
                      >
                        Inactive
                      </button>
                    </div>
                  </div>
                  <div class="space-y-3">
                    <SettingToggle
                      label="Allow Role to Approve Requests"
                      description="Enable this role to approve various requests"
                      value={canApprove()}
                      onChange={setCanApprove}
                    />
                    <SettingToggle
                      label="Allow Role to Manage System Settings"
                      description="Enable this role to manage system settings and configurations"
                      value={canManage()}
                      onChange={setCanManage}
                    />
                  </div>
                </div>
              </Show>

              {/* Footer */}
              <div class="flex items-center justify-end gap-3 px-6 py-4 border-t border-[#e5e7eb]">
                <A
                  href={`/admin/roles/${params.id}`}
                  class="px-5 py-2.5 text-[13px] font-medium border border-[#e5e7eb] rounded-lg text-[rgba(13,13,42,0.7)] hover:border-[#0D0D2A] transition-colors"
                >
                  Cancel
                </A>
                <button
                  onClick={handleSave}
                  disabled={saving()}
                  class="px-5 py-2.5 text-[13px] font-semibold bg-[#0D0D2A] text-white rounded-lg hover:bg-[#000050] transition-colors disabled:opacity-60"
                >
                  {saving() ? 'Saving…' : 'Save Changes'}
                </button>
              </div>
            </Show>
          </div>
        </div>
      </div>
  );
}

function SettingToggle(props: {
  label: string;
  description: string;
  value: boolean;
  onChange: (v: boolean) => void;
}) {
  return (
    <div class="flex items-center justify-between rounded-xl border border-[#e5e7eb] px-5 py-4">
      <div>
        <p class="text-[13px] font-semibold text-[#0D0D2A]">{props.label}</p>
        <p class="text-[12px] text-[rgba(13,13,42,0.5)] mt-0.5">{props.description}</p>
      </div>
      <button
        type="button"
        role="switch"
        aria-checked={props.value}
        onClick={() => props.onChange(!props.value)}
        class={`relative inline-flex h-6 w-11 items-center rounded-full transition-colors focus:outline-none ${
          props.value ? 'bg-[#fa5014]' : 'bg-[#d1d5db]'
        }`}
      >
        <span
          class={`inline-block h-4 w-4 transform rounded-full bg-white shadow transition-transform ${
            props.value ? 'translate-x-6' : 'translate-x-1'
          }`}
        />
      </button>
    </div>
  );
}
