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

const API = '';

type UserDetail = {
  id: string;
  publicId?: string;
  name?: string;
  full_name?: string;
  email?: string;
  status?: string;
  profilePicture?: string;
  createdAt?: string;
  created_at?: string;
  lastLogin?: string;
  accountType?: string;
};

type RoleProfileSummary = {
  id: string;
  publicId?: string;
  roleType?: string;
  verificationStatus?: string;
  submittedAt?: string | null;
  updatedAt?: string | null;
  isApproval?: boolean;
};

type UserBundle = {
  user: UserDetail;
  roleProfiles: RoleProfileSummary[];
};

const ROLE_LABELS: Record<string, string> = {
  customer: 'Customer',
  job_seeker: 'Job Seeker',
  jobseeker: 'Job Seeker',
  photographer: 'Photographer',
  tutor: 'Tutor',
  developer: 'Developer',
  makeup_artist: 'Makeup Artist',
};

async function fetchUser(id: string): Promise<UserDetail | null> {
  try {
    const adminRes = await fetch(`${API}/api/admin/users/${id}`);
    if (adminRes.ok) return adminRes.json();

    const fallback = await fetch(`${API}/api/users/${id}`);
    if (!fallback.ok) return null;
    return fallback.json();
  } catch {
    return null;
  }
}

async function fetchRoleProfiles(userId: string): Promise<RoleProfileSummary[]> {
  const urls = [
    `${API}/api/role-profiles?userId=${encodeURIComponent(userId)}`,
    `${API}/api/admin/role-profiles?userId=${encodeURIComponent(userId)}`,
  ];

  for (const url of urls) {
    try {
      const res = await fetch(url);
      if (!res.ok) continue;
      const data = await res.json();
      if (Array.isArray(data?.profiles)) return data.profiles;
      if (Array.isArray(data)) return data;
    } catch {
      continue;
    }
  }
  return [];
}

async function fetchApprovals(userId: string): Promise<RoleProfileSummary[]> {
  try {
    const res = await fetch(`${API}/api/approvals?requesterId=${encodeURIComponent(userId)}`);
    if (!res.ok) return [];
    const data = await res.json();
    const list = Array.isArray(data) ? data : data?.approvals || [];
    if (!Array.isArray(list)) return [];

    return list.map((item: any) => ({
      id: item.id,
      publicId: item.id,
      roleType: item.requestType || item.entityType || 'Role Request',
      verificationStatus: item.status || item.currentStatus || 'PENDING',
      submittedAt: item.createdAt || null,
      updatedAt: item.updatedAt || null,
      isApproval: true,
    }));
  } catch {
    return [];
  }
}

function normalizeRole(value: string | undefined): string {
  return (value || '').toLowerCase().replace(/ /g, '_');
}

function formatDate(value: string | null | undefined): string {
  if (!value) return '—';
  return new Date(value).toLocaleDateString('en-US', { year: 'numeric', month: 'short', day: 'numeric' });
}

function statusClass(status: string | undefined): string {
  const normalized = (status || '').toUpperCase();
  if (normalized === 'APPROVED') return 'status-approved';
  if (normalized === 'REJECTED') return 'status-rejected';
  if (normalized === 'NEEDS_INFO') return 'status-info';
  return 'status-pending';
}

async function fetchUserBundle(id: string): Promise<UserBundle | null> {
  const user = await fetchUser(id);
  if (!user) return null;
  const userId = user.id || id;

  const [profiles, approvals] = await Promise.all([
    fetchRoleProfiles(userId),
    fetchApprovals(userId),
  ]);

  const roleProfiles = [...profiles, ...approvals].sort((a, b) => {
    const ta = a.submittedAt ? new Date(a.submittedAt).getTime() : 0;
    const tb = b.submittedAt ? new Date(b.submittedAt).getTime() : 0;
    return tb - ta;
  });

  return { user, roleProfiles };
}

export default function UserDetailPage() {
  const params = useParams();
  const [searchParams] = useSearchParams();
  const [bundle] = createResource(() => params.id, fetchUserBundle);

  const user = createMemo(() => bundle()?.user || null);
  const roleProfiles = createMemo(() => bundle()?.roleProfiles || []);
  const roleFilter = createMemo(() => (typeof searchParams.roleFilter === 'string' ? searchParams.roleFilter : Array.isArray(searchParams.roleFilter) ? searchParams.roleFilter[0] : '') || '');
  const displayName = createMemo(() => user()?.name || user()?.full_name || 'Unknown User');
  const userCreatedAt = createMemo(() => user()?.createdAt || user()?.created_at || '');

  const displayedProfiles = createMemo(() => {
    const filter = roleFilter();
    if (!filter) return roleProfiles();
    const normalizedFilter = normalizeRole(filter);
    return roleProfiles().filter((item) => normalizeRole(item.roleType) === normalizedFilter);
  });

  const verifiedCount = createMemo(() => displayedProfiles().filter((rp) => (rp.verificationStatus || '').toUpperCase() === 'APPROVED').length);
  const roleTitleLabel = createMemo(() => {
    const filter = roleFilter();
    if (!filter) return '';
    return ROLE_LABELS[filter] || filter.replace(/_/g, ' ');
  });

  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 flex items-center justify-between">
        <div>
          <h1 class="text-xl font-semibold text-gray-900">{roleTitleLabel() ? `${roleTitleLabel()} Profile` : 'User Details'}</h1>
          <p class="text-sm text-gray-500 mt-0.5">Review account profile and role registration data with approval status.</p>
        </div>
        <div class="flex items-center gap-2">
          <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/users">Back to Users</A>
          <A class="btn-primary" href={`/admin/users/${params.id}/edit`}>Edit User</A>
        </div>
      </div>
      <div class="p-6 flex-1">

      <Show when={bundle.loading}>
        <div class="rounded-xl border border-gray-200 bg-white shadow-sm"><p class="notice">Loading user...</p></div>
      </Show>
      <Show when={!bundle.loading && !user()}>
        <div class="rounded-xl border border-gray-200 bg-white shadow-sm"><p class="notice">User not found.</p></div>
      </Show>

      <Show when={user()}>
        <>
          <section class="rounded-xl border border-gray-200 bg-white shadow-sm" style="padding:22px">
            <div style="display:flex;align-items:flex-start;justify-content:space-between;gap:16px;flex-wrap:wrap">
              <div style="display:flex;gap:14px;align-items:center;min-width:260px">
                <div class="identity-avatar">
                  {displayName().charAt(0).toUpperCase() || '?'}
                </div>
                <div>
                  <h2 style="margin:0;font-size:24px">{displayName()}</h2>
                  <p class="notice" style="margin:4px 0 0">{user()!.email || '—'}</p>
                  <p class="notice" style="margin:3px 0 0">{user()!.publicId || user()!.id}</p>
                </div>
              </div>
              <div style="display:flex;gap:18px">
                <div class="mini-stat">
                  <p class="mini-stat-value">{roleFilter() ? displayedProfiles().length : roleProfiles().length}</p>
                  <p class="mini-stat-label">{roleFilter() ? 'Profiles' : 'Total Roles'}</p>
                </div>
                <div class="mini-stat">
                  <p class="mini-stat-value">{verifiedCount()}</p>
                  <p class="mini-stat-label">{roleFilter() ? 'Approved' : 'Verified'}</p>
                </div>
              </div>
            </div>
            <div style="display:flex;gap:8px;margin-top:12px;flex-wrap:wrap">
              <span class={`status-pill ${user()!.status === 'active' ? 'status-approved' : 'status-rejected'}`}>{user()!.status || 'unknown'}</span>
              <span class="meta-chip">Joined {formatDate(userCreatedAt())}</span>
              <Show when={user()!.lastLogin}>
                <span class="meta-chip">Last seen {formatDate(user()!.lastLogin)}</span>
              </Show>
            </div>
          </section>

          <section class="rounded-xl border border-gray-200 bg-white shadow-sm" style="margin-top:16px;padding:0;overflow:hidden">
            <div style="padding:16px 18px;border-bottom:1px solid #e2e8f0;background:#f8fafc">
              <h2 style="margin:0;font-size:18px">{roleTitleLabel() ? `${roleTitleLabel()} Registration Data` : 'Registered Roles & Profiles'}</h2>
            </div>
            <Show when={displayedProfiles().length > 0} fallback={
              <div style="padding:24px">
                <p class="notice">This user has no registered role profiles yet.</p>
              </div>
            }>
              <div class="overflow-x-auto">
                <table class="w-full text-sm">
                  <thead>
                    <tr>
                      <Show when={!roleFilter()}>
                        <th>Role</th>
                      </Show>
                      <th>Profile ID</th>
                      <th>Verification</th>
                      <th>Submitted</th>
                      <th>Last Updated</th>
                      <th class="text-right">Action</th>
                    </tr>
                  </thead>
                  <tbody>
                    <For each={displayedProfiles()}>
                      {(item) => (
                        <tr>
                          <Show when={!roleFilter()}>
                            <td>{ROLE_LABELS[normalizeRole(item.roleType)] || item.roleType || 'Role'}</td>
                          </Show>
                          <td>{item.publicId || item.id}</td>
                          <td>
                            <span class={`status-pill ${statusClass(item.verificationStatus)}`}>
                              {(item.verificationStatus || 'UNKNOWN').replace(/_/g, ' ')}
                            </span>
                          </td>
                          <td>{formatDate(item.submittedAt)}</td>
                          <td>{formatDate(item.updatedAt)}</td>
                          <td class="text-right">
                            <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 ${item.isApproval ? '' : 'orange'}`} href={item.isApproval ? `/admin/approval/${item.id}` : `/admin/profile/${item.publicId || item.id}`}>
                              {item.isApproval ? 'View Request' : 'Open Profile'}
                            </A>
                          </td>
                        </tr>
                      )}
                    </For>
                  </tbody>
                </table>
              </div>
            </Show>
          </section>
        </>
      </Show>
      </div>
      </div>
  );
}
