import { A, useNavigate } from '@solidjs/router';
import { createResource, createSignal, Show } from 'solid-js';
import ExternalRoleForm, { type ExternalRoleConfig } from '~/components/admin/ExternalRoleForm';
import ExternalRoleTabs from '~/components/admin/ExternalRoleTabs';

const API = '';

function defaultConfig(): ExternalRoleConfig {
  return {
    roleKey: '',
    displayName: '',
    vertical: 'marketplace',
    roleCategory: 'provider',
    enabledModules: [],
    permissions: {},
    onboardingSchemaId: 'default_onboarding_v1',
    requiresOnboardingApproval: true,
    requiresLeadApproval: false,
    requiresJobApproval: false,
    featureLimits: {},
    runtimeConfigVersion: 1,
    isActive: true,
  };
}

export default function CreateExternalRolePage() {
  const navigate = useNavigate();
  const [saving, setSaving] = createSignal(false);
  const [error, setError] = createSignal('');
  const [onboardingSchemas] = createResource(async () => {
    try {
      const res = await fetch(`${API}/api/admin/onboarding-config`);
      if (!res.ok) return [] as string[];
      const data = await res.json();
      const rows = Array.isArray(data) ? data : (data.schemas || data.configs || []);
      return rows
        .map((item: any) => String(item?.id || '').trim())
        .filter(Boolean);
    } catch {
      return [] as string[];
    }
  });

  const handleSubmit = async (config: ExternalRoleConfig) => {
    try {
      setSaving(true);
      setError('');
      const res = await fetch(`${API}/api/admin/roles`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          key: config.roleKey.toUpperCase(),
          name: config.displayName,
          audience: 'EXTERNAL',
          config_json: {
            roleKey: config.roleKey,
            displayName: config.displayName,
            vertical: config.vertical,
            roleCategory: config.roleCategory,
            enabledModules: config.enabledModules,
            permissions: config.permissions,
            onboardingSchemaId: config.onboardingSchemaId,
            requiresOnboardingApproval: config.requiresOnboardingApproval,
            requiresLeadApproval: config.requiresLeadApproval,
            requiresJobApproval: config.requiresJobApproval,
            featureLimits: config.featureLimits || {},
            version: config.runtimeConfigVersion || 1,
          },
          is_active: config.isActive,
        }),
      });
      if (!res.ok) {
        const body = await res.json().catch(() => ({}));
        throw new Error(body.message || 'Failed to create runtime role');
      }
      navigate('/admin/runtime-roles');
    } catch (nextError: any) {
      setError(nextError?.message || 'Failed to create runtime role');
    } finally {
      setSaving(false);
    }
  };

  return (
      <div class="flex flex-col -mx-6 -mt-6 min-h-full">
        <div class="bg-white border-b border-gray-200 px-6 py-4">
          <h1 class="text-xl font-semibold text-gray-900">Create External Role</h1>
          <p class="text-sm text-gray-500 mt-0.5">
            Create a new external role and choose what it can access in the app.
          </p>
        </div>

        <div class="flex-1 p-6">
          <ExternalRoleTabs />

          <Show when={error()}>
            <div class="mb-4 rounded-lg border border-red-200 bg-red-50 px-4 py-3 text-sm text-red-700">{error()}</div>
          </Show>

          <ExternalRoleForm
            initialValue={defaultConfig()}
            onboardingSchemaOptions={onboardingSchemas() || []}
            saving={saving()}
            submitLabel="Create External Role"
            onSubmit={handleSubmit}
          />
        </div>
      </div>
  );
}
