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

const API = '';

type Permission = { key: string; module: string; action: 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 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;
  }
}

export default function RoleDetailPage() {
  const params = useParams();
  const [role] = createResource(() => params.id, loadRole);

  const permSet = createMemo(() => new Set(role()?.permission_keys ?? []));
  const isSuperAdmin = createMemo(() => (role()?.key || '').toUpperCase() === 'SUPER_ADMIN');

  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>
              <A
                href="/admin/roles/create"
                class="py-4 text-[14px] font-medium text-[rgba(13,13,42,0.5)] hover:text-[#0D0D2A]"
              >
                Create Role
              </A>
            </div>

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

            <Show when={!role.loading && !role()}>
              <div class="px-6 py-10 text-center text-[13px] text-red-500">
                Role not found or backend is not running.
              </div>
            </Show>

            <Show when={role()}>
              {/* Action bar */}
              <div class="flex items-center justify-between px-6 py-4 border-b border-[#e5e7eb]">
                <div>
                  <h2 class="text-[16px] font-semibold text-[#0D0D2A]">{role()!.name}</h2>
                  <p class="text-[12px] text-[rgba(13,13,42,0.5)] mt-0.5">{role()!.key}</p>
                </div>
                <div class="flex items-center gap-2">
                  <A
                    href="/admin/roles"
                    class="px-4 py-2 text-[13px] font-medium border border-[#e5e7eb] rounded-lg text-[rgba(13,13,42,0.7)] hover:border-[#0D0D2A] transition-colors"
                  >
                    Back to List
                  </A>
                  <A
                    href={`/admin/roles/${params.id}/edit`}
                    class="px-4 py-2 text-[13px] font-semibold bg-[#0D0D2A] text-white rounded-lg hover:bg-[#000050] transition-colors"
                  >
                    Edit Role
                  </A>
                </div>
              </div>

              {/* General info */}
              <div class="px-6 py-5 border-b border-[#e5e7eb]">
                <h3 class="text-[13px] font-semibold text-[#0D0D2A] mb-4">General Information</h3>
                <div class="grid grid-cols-2 gap-5 mb-4">
                  <ReadField label="Role Name" value={role()!.name} />
                  <ReadField label="Role Code" value={role()!.key} />
                </div>
                <div class="grid grid-cols-2 gap-5">
                  <ReadField label="Department" value={role()!.department_name || '—'} />
                  <ReadField
                    label="Status"
                    value=""
                    custom={
                      <span
                        class={`inline-flex items-center px-2.5 py-1 rounded-md text-[12px] font-semibold ${
                          role()!.is_active
                            ? 'bg-[rgba(34,197,94,0.1)] text-[#16a34a]'
                            : 'bg-[#f1f1f1] text-[rgba(13,13,42,0.5)]'
                        }`}
                      >
                        {role()!.is_active ? 'Active' : 'Inactive'}
                      </span>
                    }
                  />
                </div>
                <Show when={role()!.description}>
                  <div class="mt-4">
                    <ReadField label="Description" value={role()!.description!} />
                  </div>
                </Show>
              </div>

              {/* Module Access */}
              <div class="px-6 py-5 border-b border-[#e5e7eb]">
                <h3 class="text-[13px] font-semibold text-[#0D0D2A] mb-4">Module Access</h3>
                <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>
                      </tr>
                    </thead>
                    <tbody class="divide-y divide-[#e5e7eb]">
                      <For each={STATIC_MODULES}>
                        {(module) => (
                          <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);
                                const checked = () => isSuperAdmin() || permSet().has(key);
                                return (
                                  <td class="px-4 py-3.5 text-center">
                                    <input
                                      type="checkbox"
                                      checked={checked()}
                                      disabled
                                      class="h-4 w-4 accent-[#fa5014]"
                                    />
                                  </td>
                                );
                              }}
                            </For>
                          </tr>
                        )}
                      </For>
                    </tbody>
                  </table>
                </div>
              </div>

              {/* Role Settings */}
              <div class="px-6 py-5">
                <h3 class="text-[13px] font-semibold text-[#0D0D2A] mb-4">Role Settings</h3>
                <div class="space-y-3">
                  <SettingRow
                    label="Allow Role to Approve Requests"
                    description="Enable this role to approve various requests"
                    value={role()!.can_approve_requests}
                  />
                  <SettingRow
                    label="Allow Role to Manage System Settings"
                    description="Enable this role to manage system settings and configurations"
                    value={role()!.can_manage_system_settings}
                  />
                </div>
              </div>
            </Show>
          </div>
        </div>
      </div>
  );
}

function ReadField(props: { label: string; value: string; custom?: any }) {
  return (
    <div>
      <p class="text-[12px] text-[rgba(13,13,42,0.5)] mb-1">{props.label}</p>
      {props.custom ?? (
        <p class="text-[14px] font-medium text-[#0D0D2A]">{props.value || '—'}</p>
      )}
    </div>
  );
}

function SettingRow(props: { label: string; description: string; value: boolean }) {
  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>
      <div
        class={`relative inline-flex h-6 w-11 items-center rounded-full transition-colors ${
          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'
          }`}
        />
      </div>
    </div>
  );
}
