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

const API = '';

type Role = { id: string; name: string };
type Employee = { id: string; name?: string; full_name?: string; email: string; role_id?: string; role_name?: string; role?: { id?: string } };

async function fetchEmployee(id: string): Promise<Employee | null> {
  try {
    const accessToken = typeof sessionStorage !== 'undefined'
      ? (sessionStorage.getItem('nxtgauge_admin_access_token') || '').trim()
      : '';
    const res = await fetch(`${API}/api/admin/employees/${id}`, {
      headers: {
        Accept: 'application/json',
        ...(accessToken ? { Authorization: `Bearer ${accessToken}` } : {}),
      },
      credentials: 'include',
    });
    if (!res.ok) return null;
    return res.json();
  } catch {
    return null;
  }
}

async function fetchRoles(): Promise<Role[]> {
  try {
    const accessToken = typeof sessionStorage !== 'undefined'
      ? (sessionStorage.getItem('nxtgauge_admin_access_token') || '').trim()
      : '';
    const res = await fetch(`${API}/api/admin/roles?audience=INTERNAL&per_page=100`, {
      headers: {
        Accept: 'application/json',
        ...(accessToken ? { Authorization: `Bearer ${accessToken}` } : {}),
      },
      credentials: 'include',
    });
    if (!res.ok) return [];
    const data = await res.json();
    return Array.isArray(data) ? data : (data.roles || []);
  } catch {
    return [];
  }
}

export default function EditEmployeePage() {
  const params = useParams();
  const navigate = useNavigate();
  const [employee] = createResource(() => params.id, fetchEmployee);
  const [roles] = createResource(fetchRoles);

  const [name, setName] = createSignal('');
  const [email, setEmail] = createSignal('');
  const [roleId, setRoleId] = createSignal('');
  const [saving, setSaving] = createSignal(false);
  const [error, setError] = createSignal('');

  createMemo(() => {
    const e = employee();
    if (!e) return null;
    setName(e.name || e.full_name || '');
    setEmail(e.email || '');
    setRoleId(e.role_id || e.role?.id || '');
    if (!(e.role_id || e.role?.id) && e.role_name) {
      const byName = (roles() ?? []).find((r) => r.name.trim().toLowerCase() === String(e.role_name).trim().toLowerCase());
      if (byName?.id) setRoleId(byName.id);
    }
    return null;
  });

  const submit = async (e: Event) => {
    e.preventDefault();
    if (!roleId()) {
      setError('Role is required.');
      return;
    }
    try {
      setSaving(true);
      setError('');
      const accessToken = typeof sessionStorage !== 'undefined'
        ? (sessionStorage.getItem('nxtgauge_admin_access_token') || '').trim()
        : '';
      const res = await fetch(`${API}/api/admin/employees/${params.id}`, {
        method: 'PATCH',
        headers: {
          'Content-Type': 'application/json',
          Accept: 'application/json',
          ...(accessToken ? { Authorization: `Bearer ${accessToken}` } : {}),
        },
        credentials: 'include',
        body: JSON.stringify({ role_id: roleId() }),
      });
      if (!res.ok) {
        const payload = await res.json().catch(() => ({}));
        throw new Error(payload.message || 'Failed to update employee');
      }
      navigate('/admin/employees');
    } catch (err: any) {
      setError(err.message || 'Failed to update employee');
    } finally {
      setSaving(false);
    }
  };

  const inputCls = 'w-full rounded-lg border border-gray-200 px-3 py-2 text-sm outline-none focus:border-[#0a1d37] focus:ring-1 focus:ring-[#0a1d37]';
  const labelCls = 'mb-1.5 block text-sm font-medium text-gray-700';

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

        {/* ── Page header ── */}
        <div class="bg-white border-b border-gray-200 px-6 py-4 flex items-center justify-between">
          <div>
            <h1 class="text-xl font-semibold text-gray-900">Edit Employee</h1>
            <p class="text-sm text-gray-500 mt-0.5">Update internal employee profile and role assignment.</p>
          </div>
          <A class="rounded-lg border border-gray-200 px-4 py-2 text-sm font-medium text-gray-700 hover:bg-gray-50 transition-colors" href="/admin/employees">
            Back to Employees
          </A>
        </div>

        {/* ── Content ── */}
        <div class="p-6">
          <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>

          <Show when={employee.loading}>
            <div class="table-card">
              <p class="py-10 text-center text-sm text-slate-400">Loading employee…</p>
            </div>
          </Show>
          <Show when={!employee.loading && !employee()}>
            <div class="table-card">
              <p class="py-10 text-center text-sm text-slate-400">Employee not found.</p>
            </div>
          </Show>

          <Show when={employee()}>
            <form class="rounded-xl border border-gray-200 bg-white shadow-sm p-6" onSubmit={submit}>
              <div class="grid grid-cols-1 gap-5 sm:grid-cols-2">
                <div>
                  <label class={labelCls}>Full Name</label>
                  <input class={inputCls} value={name()} onInput={(e) => setName(e.currentTarget.value)} />
                </div>
                <div>
                  <label class={labelCls}>Email</label>
                  <input type="email" class={inputCls} value={email()} onInput={(e) => setEmail(e.currentTarget.value)} />
                </div>
                <div>
                  <label class={labelCls}>Role</label>
                  <select class={inputCls} value={roleId()} onChange={(e) => setRoleId(e.currentTarget.value)}>
                    <option value="">Select role…</option>
                    <Show when={!roles.loading}>
                      <For each={roles() ?? []}>
                        {(r) => <option value={r.id}>{r.name}</option>}
                      </For>
                    </Show>
                  </select>
                </div>
              </div>
              <div class="mt-6 flex justify-end gap-3 border-t border-gray-100 pt-5">
                <A class="rounded-lg border border-gray-200 px-4 py-2 text-sm font-medium text-gray-700 hover:bg-gray-50 transition-colors" href="/admin/employees">Cancel</A>
                <button class="btn-primary" type="submit" disabled={saving()}>
                  {saving() ? 'Saving…' : 'Save Changes'}
                </button>
              </div>
            </form>
          </Show>
        </div>
      </div>
  );
}
