import { For, Show, createSignal, onMount } from 'solid-js';
import { RefreshCw, ArrowLeft } from 'lucide-solid';
import { BTN_GHOST, BTN_PRIMARY, CARD } from '~/components/DashboardShell';
import RoleWizard from '~/components/dashboard/RoleWizard';
import { roleKeyToPrefix, isIdentityField } from '~/lib/role-utils';

const API = '';
const NAVY = '#0D0D2A';
const ORANGE = '#FF5E13';

type UserRoleItem = {
  role_key: string;
  role_name?: string;
  status?: string;
  approved_at?: string | null;
};

async function apiFetch(path: string, opts?: RequestInit) {
  const token =
    typeof window !== "undefined"
      ? window.sessionStorage.getItem("nxtgauge_access_token") || ""
      : "";
  return fetch(`${API}${path}`, {
    ...opts,
    credentials: "include",
    headers: {
      "Content-Type": "application/json",
      ...(token ? { Authorization: `Bearer ${token}` } : {}),
      ...(opts?.headers ?? {}),
    },
  });
}

const REGISTER_OPTIONS = [
  { key: 'PHOTOGRAPHER',          label: 'Photographer' },
  { key: 'MAKEUP_ARTIST',         label: 'Makeup Artist' },
  { key: 'TUTOR',                 label: 'Tutor' },
  { key: 'DEVELOPER',             label: 'Developer' },
  { key: 'VIDEO_EDITOR',          label: 'Video Editor' },
  { key: 'UGC_CONTENT_CREATOR',   label: 'UGC Content Creator' },
  { key: 'GRAPHIC_DESIGNER',      label: 'Graphic Designer' },
  { key: 'SOCIAL_MEDIA_MANAGER',  label: 'Social Media Manager' },
  { key: 'FITNESS_TRAINER',       label: 'Fitness Trainer' },
  { key: 'CATERING_SERVICES',     label: 'Catering Services' },
  { key: 'COMPANY',               label: 'Company' },
  { key: 'CUSTOMER',              label: 'Customer' },
  { key: 'JOB_SEEKER',            label: 'Job Seeker' },
];

/**
 * Fetches the user's active role profile and extracts doc URLs for fields
 * that are identity fields (shared across roles).  These are passed as
 * `prefilledDocs` to RoleWizard so the user doesn't have to re-upload
 * Aadhaar / PAN / selfie etc. when registering a second role.
 */
async function fetchSharedIdentityDocs(activeRoleKey: string): Promise<Record<string, string>> {
  if (!activeRoleKey) return {};
  try {
    const res = await apiFetch(`/api/profile?roleKey=${activeRoleKey}`);
    if (!res.ok) return {};
    const data = await res.json().catch(() => ({}));
    const profile: Record<string, unknown> = data?.profile_data ?? data ?? {};

    // Keep only string values (URLs / field values) for fields whose key
    // looks like an identity document — we don't know the schema here, so
    // we use the convention-based check (adminFlagged = false).
    const shared: Record<string, string> = {};
    for (const [key, val] of Object.entries(profile)) {
      if (typeof val === 'string' && val && isIdentityField(key, false)) {
        shared[key] = val;
      }
    }
    return shared;
  } catch {
    return {};
  }
}

export default function SwitchServicesPage() {
  const [roles, setRoles] = createSignal<UserRoleItem[]>([]);
  const [activeRole, setActiveRole] = createSignal('');
  const [loading, setLoading] = createSignal(true);
  const [busyRole, setBusyRole] = createSignal<string | null>(null);
  const [msg, setMsg] = createSignal('');
  const [err, setErr] = createSignal('');

  // ── wizard state ──────────────────────────────────────────────────────────
  /** When set, the wizard is shown inline for this role key. */
  const [wizardRole, setWizardRole] = createSignal<string | null>(null);
  const [wizardLabel, setWizardLabel] = createSignal('');
  const [sharedDocs, setSharedDocs] = createSignal<Record<string, string>>({});

  const loadRoles = async () => {
    setLoading(true);
    setErr('');
    try {
      const raw = typeof window !== 'undefined'
        ? (window.sessionStorage.getItem('nxtgauge_auth_user') || window.localStorage.getItem('nxtgauge_auth_user'))
        : null;
      const parsed = raw ? JSON.parse(raw) : null;
      const active = String(parsed?.active_role || parsed?.role || '').trim().toUpperCase();
      setActiveRole(active);
    } catch {
      setActiveRole('');
    }
    try {
      const res = await apiFetch('/api/me/roles');
      const data = await res.json().catch(() => []);
      if (!res.ok) {
        setErr('Failed to load roles.');
        setRoles([]);
        return;
      }
      setRoles(Array.isArray(data) ? data : []);
    } catch {
      setErr('Network error while loading roles.');
    } finally {
      setLoading(false);
    }
  };

  onMount(loadRoles);

  const registerRole = async (roleKey: string, label: string) => {
    setBusyRole(roleKey);
    setMsg('');
    setErr('');
    try {
      const res = await apiFetch('/api/me/roles/register', {
        method: 'POST',
        body: JSON.stringify({ role_key: roleKey }),
      });
      const data = await res.json().catch(() => ({}));
      if (!res.ok) {
        setErr(data.error || data.message || 'Failed to register role.');
        return;
      }

      // Fetch identity docs from the user's current active role to pre-fill
      const shared = await fetchSharedIdentityDocs(activeRole());
      setSharedDocs(shared);

      await loadRoles();

      // Launch the verification wizard inline
      setWizardLabel(label);
      setWizardRole(roleKey);
    } catch {
      setErr('Network error while registering role.');
    } finally {
      setBusyRole(null);
    }
  };

  const switchRole = async (roleKey: string) => {
    setBusyRole(roleKey);
    setMsg('');
    setErr('');
    try {
      const res = await apiFetch('/api/auth/switch-role', {
        method: 'POST',
        body: JSON.stringify({ role_key: roleKey }),
      });
      const data = await res.json().catch(() => ({}));
      if (!res.ok) {
        setErr(data.error || data.message || 'Failed to switch role.');
        return;
      }

      const accessToken = String(data?.access_token || '').trim();
      if (accessToken && typeof window !== 'undefined') {
        window.sessionStorage.setItem('nxtgauge_access_token', accessToken);
        window.sessionStorage.setItem('nxtgauge_frontend_access_token', accessToken);
      }

      if (typeof window !== 'undefined') {
        const keys = ['nxtgauge_auth_user', 'nxtgauge_user', 'nxtgauge_signup_profile_v1'];
        for (const key of keys) {
          const raw = window.localStorage.getItem(key);
          if (!raw) continue;
          try {
            const parsed = JSON.parse(raw);
            const next = {
              ...parsed,
              active_role: roleKey,
              role: roleKey.toLowerCase(),
              roleKey: roleKey.toLowerCase(),
            };
            window.localStorage.setItem(key, JSON.stringify(next));
          } catch {
            // ignore malformed payload
          }
        }
      }

      setActiveRole(roleKey);
      setMsg(`Switched to ${roleKey}. Refreshing dashboard...`);
      setTimeout(() => {
        window.location.href = '/dashboard';
      }, 250);
    } catch {
      setErr('Network error while switching role.');
    } finally {
      setBusyRole(null);
    }
  };

  const hasRole = (roleKey: string) => roles().some((r) => String(r.role_key || '').toUpperCase() === roleKey);
  const isActive = (roleKey: string) => activeRole() === roleKey;

  const exitWizard = () => {
    setWizardRole(null);
    setSharedDocs({});
    setWizardLabel('');
  };

  const onWizardSubmitted = async (_status: string) => {
    exitWizard();
    await loadRoles();
    setMsg('Your verification has been submitted. We\'ll review it shortly.');
  };

  // ── wizard view ───────────────────────────────────────────────────────────
  return (
    <div style={{ display: 'grid', gap: '14px', 'max-width': '980px' }}>
      {/* Header */}
      <div
        style={{
          background: NAVY,
          "border-radius": "12px",
          padding: "16px 20px",
          display: "flex",
          "align-items": "center",
          gap: "12px",
        }}
      >
        <Show
          when={wizardRole()}
          fallback={<span style={{ color: ORANGE }}><RefreshCw size={24} /></span>}
        >
          <button
            type="button"
            onClick={exitWizard}
            style={{ background: "none", border: "none", cursor: "pointer", color: ORANGE, display: "flex", "align-items": "center", padding: "0" }}
            aria-label="Back to Switch Services"
          >
            <ArrowLeft size={24} />
          </button>
        </Show>
        <div>
          <p style={{ margin: "0", "font-size": "18px", "font-weight": "800", color: "#fff" }}>
            <Show when={wizardRole()} fallback="Switch Services">
              {wizardLabel()} — Verification
            </Show>
          </p>
          <p style={{ margin: "4px 0 0", "font-size": "13px", color: "rgba(255,255,255,0.65)" }}>
            <Show when={wizardRole()} fallback="Manage approved roles and register additional services.">
              Complete your profile to submit for admin approval.
            </Show>
          </p>
        </div>
      </div>

      {/* Inline wizard — shown after successful registration */}
      <Show when={wizardRole()}>
        <RoleWizard
          roleKey={wizardRole()!}
          rolePrefix={roleKeyToPrefix(wizardRole()!)}
          prefilledDocs={sharedDocs()}
          onSubmitted={onWizardSubmitted}
        />
      </Show>

      {/* Main list + registration — hidden while wizard is open */}
      <Show when={!wizardRole()}>
        <Show when={msg()}>
          <div style={{ ...CARD, border: '1px solid #BBF7D0', background: '#ECFDF5', padding: '12px 14px', color: '#065F46', 'font-size': '13px', 'font-weight': '600' }}>{msg()}</div>
        </Show>
        <Show when={err()}>
          <div style={{ ...CARD, border: '1px solid #FECACA', background: '#FEF2F2', padding: '12px 14px', color: '#B91C1C', 'font-size': '13px', 'font-weight': '600' }}>{err()}</div>
        </Show>

        {/* My Roles */}
        <div style={CARD}>
          <div style={{ display: 'flex', 'justify-content': 'space-between', 'align-items': 'center', 'margin-bottom': '10px' }}>
            <p style={{ margin: '0', 'font-size': '16px', 'font-weight': '700', color: '#111827' }}>My Roles</p>
            <button type="button" onClick={loadRoles} style={BTN_GHOST}>Refresh</button>
          </div>
          <Show when={loading()}>
            <p style={{ margin: '0', color: '#9CA3AF', 'font-size': '13px' }}>Loading roles...</p>
          </Show>
          <Show when={!loading() && roles().length === 0}>
            <p style={{ margin: '0', color: '#6B7280', 'font-size': '13px' }}>No roles found for this user.</p>
          </Show>
          <Show when={!loading() && roles().length > 0}>
            <div style={{ display: 'grid', gap: '8px' }}>
              <For each={roles()}>
                {(r) => {
                  const rk = () => String(r.role_key || '').toUpperCase();
                  const isPending = () => String(r.status || '').toUpperCase() === 'PENDING';
                  return (
                    <div style={{ border: '1px solid #E5E7EB', 'border-radius': '10px', padding: '10px', background: '#FCFCFD', display: 'flex', 'justify-content': 'space-between', gap: '10px', 'flex-wrap': 'wrap' }}>
                      <div>
                        <p style={{ margin: '0', 'font-size': '13px', 'font-weight': '700', color: '#111827' }}>{r.role_name || r.role_key}</p>
                        <p style={{ margin: '4px 0 0', 'font-size': '12px', color: '#6B7280' }}>
                          Status: {String(r.status || 'APPROVED').replace(/_/g, ' ')} {r.approved_at ? `• Approved ${new Date(r.approved_at).toLocaleString('en-IN')}` : ''}
                        </p>
                      </div>
                      <div style={{ display: 'flex', 'align-items': 'center', gap: '8px' }}>
                        <Show
                          when={!isPending()}
                          fallback={
                            <span style={{ display: 'inline-flex', height: '24px', 'align-items': 'center', padding: '0 10px', 'border-radius': '999px', background: '#FEF9C3', color: '#A16207', 'font-size': '11px', 'font-weight': '700' }}>
                              Under Review
                            </span>
                          }
                        >
                          <span style={{ display: 'inline-flex', height: '24px', 'align-items': 'center', padding: '0 10px', 'border-radius': '999px', background: '#ECFDF5', color: '#15803D', 'font-size': '11px', 'font-weight': '700' }}>
                            Approved
                          </span>
                        </Show>
                        <Show when={!isPending()}>
                          <button
                            type="button"
                            onClick={() => switchRole(rk())}
                            disabled={busyRole() === rk() || isActive(rk())}
                            style={{ ...BTN_PRIMARY, height: '30px', 'font-size': '12px', padding: '0 10px', opacity: busyRole() === rk() || isActive(rk()) ? '0.7' : '1' }}
                          >
                            {isActive(rk()) ? 'Active' : busyRole() === rk() ? 'Switching...' : 'Switch'}
                          </button>
                        </Show>
                      </div>
                    </div>
                  );
                }}
              </For>
            </div>
          </Show>
        </div>

        {/* Register Another Service */}
        <div style={CARD}>
          <p style={{ margin: '0 0 10px', 'font-size': '16px', 'font-weight': '700', color: '#111827' }}>Register Another Service</p>
          <div style={{ display: 'grid', 'grid-template-columns': 'repeat(3,minmax(0,1fr))', gap: '10px' }}>
            <For each={REGISTER_OPTIONS}>
              {(opt) => (
                <div style={{ border: '1px solid #E5E7EB', 'border-radius': '10px', padding: '10px', background: '#FCFCFD' }}>
                  <p style={{ margin: '0', 'font-size': '13px', 'font-weight': '700', color: '#111827' }}>{opt.label}</p>
                  <button
                    type="button"
                    disabled={hasRole(opt.key) || busyRole() === opt.key}
                    onClick={() => registerRole(opt.key, opt.label)}
                    style={{ ...BTN_PRIMARY, height: '30px', 'font-size': '12px', padding: '0 10px', 'margin-top': '8px', width: '100%', opacity: hasRole(opt.key) || busyRole() === opt.key ? '0.7' : '1' }}
                  >
                    {hasRole(opt.key) ? 'Registered' : busyRole() === opt.key ? 'Registering...' : 'Register'}
                  </button>
                </div>
              )}
            </For>
          </div>
        </div>
      </Show>
    </div>
  );
}
