import { A, useParams } from '@solidjs/router';
import { createMemo } from 'solid-js';
import ApprovalManagementPage from './approval';
import VerificationManagementPage from './verification';
import UsersManagementPage from './users';

function toTitle(value: string): string {
  return value
    .split(/[-_/]/g)
    .filter(Boolean)
    .map((part) => part.charAt(0).toUpperCase() + part.slice(1))
    .join(' ');
}

const LEGACY_ADMIN_ORIGIN = import.meta.env.VITE_LEGACY_ADMIN_ORIGIN || 'http://localhost:3001';

function resolveLegacyPath(modulePath: string): string {
  switch (modulePath) {
    case 'roles':
      return '/roles?scope=internal';
    case 'approval-management':
    case 'approvals':
      return '/approval';
    case 'onboarding-management':
      return '/';
    case 'internal-dashboard-management':
      return '/internal-dashboard-management';
    case 'external-dashboard-management':
      return '/external-dashboard-management';
    case 'support':
      return '/help';
    default:
      return `/${modulePath}`;
  }
}

export default function LegacyModuleShellPage() {
  const params = useParams();
  const modulePath = String((params as any).module || '').trim();

  if (modulePath === 'approval' || modulePath === 'approval-management' || modulePath === 'approvals' || modulePath === 'approval-status') {
    return <ApprovalManagementPage />;
  }

  if (modulePath === 'verification' || modulePath === 'verification-status' || modulePath === 'verification-management') {
    return <VerificationManagementPage />;
  }

  if (modulePath === 'users' || modulePath === 'users-management' || modulePath === 'user-management') {
    return <UsersManagementPage />;
  }

  const moduleName = createMemo(() => toTitle(modulePath || 'Management'));
  const legacyPath = createMemo(() => resolveLegacyPath(modulePath));
  const legacyUrl = createMemo(() => `${LEGACY_ADMIN_ORIGIN}${legacyPath()}`);

  return (
      <h1 class="text-2xl font-bold text-gray-900">{moduleName()}</h1>
      <p class="mt-1 text-sm text-gray-500">
        Live legacy module embedded for exact design and functionality parity during migration.
      </p>
      <section class="rounded-xl border border-gray-200 bg-white shadow-sm">
        <div class="actions">
          <A class="inline-flex items-center rounded-lg border border-gray-200 bg-white px-4 py-2 text-sm font-medium text-gray-700 hover:bg-gray-50 transition-colors" href={legacyUrl()} target="_blank">Open Module In New Tab</A>
        </div>
        <iframe
          src={legacyUrl()}
          title={`${moduleName()} (Legacy)`}
          style={{ width: '100%', height: '72vh', border: '1px solid #e2e8f0', 'border-radius': '10px', 'margin-top': '10px' }}
        />
      </section>
  );
}
