import { A, useParams } from '@solidjs/router';
import { createMemo, createResource, Show } from 'solid-js';
import AdminShell from '~/components/AdminShell';

const API = '/api/gateway';

type Photographer = {
  id: string;
  name?: string;
  full_name?: string;
  email?: string;
  phone?: string;
  status?: string;
  created_at?: string;
  createdAt?: string;
  city?: string;
  state?: string;
  experience?: string;
  portfolio_url?: string;
};

async function fetchPhotographer(id: string): Promise<Photographer | null> {
  try {
    const res = await fetch(`${API}/api/admin/users/${id}`);
    if (res.ok) return res.json();
    const fallback = await fetch(`${API}/api/users/${id}`);
    if (!fallback.ok) return null;
    return fallback.json();
  } catch {
    return null;
  }
}

export default function PhotographerDetailPage() {
  const params = useParams();
  const [profile] = createResource(() => params.id, fetchPhotographer);

  const name = createMemo(() => profile()?.name || profile()?.full_name || 'Photographer');
  const created = createMemo(() => profile()?.createdAt || profile()?.created_at || '');

  return (
    <AdminShell>
      <div class="page-hero-card page-actions">
        <div>
          <h1 class="page-title">Photographer Detail</h1>
          <p class="page-subtitle">View profile snapshot and account metadata for one photographer.</p>
        </div>
        <div class="page-actions-right">
          <A class="btn" href="/admin/photographer">Back to Photographer List</A>
          <A class="btn" href={`/admin/users/details/${params.id}`}>Open User Detail</A>
        </div>
      </div>

      <Show when={profile.loading}>
        <div class="card"><p class="notice">Loading photographer...</p></div>
      </Show>
      <Show when={!profile.loading && !profile()}>
        <div class="card"><p class="notice">Photographer not found.</p></div>
      </Show>

      <Show when={profile()}>
        <section class="card">
          <div class="field-grid-2">
            <p class="notice" style="margin:0"><strong>Name:</strong> {name()}</p>
            <p class="notice" style="margin:0"><strong>Email:</strong> {profile()!.email || '—'}</p>
            <p class="notice" style="margin:0"><strong>Phone:</strong> {profile()!.phone || '—'}</p>
            <p class="notice" style="margin:0"><strong>Status:</strong> {profile()!.status || '—'}</p>
            <p class="notice" style="margin:0"><strong>City/State:</strong> {[profile()!.city, profile()!.state].filter(Boolean).join(', ') || '—'}</p>
            <p class="notice" style="margin:0"><strong>Experience:</strong> {profile()!.experience || '—'}</p>
            <p class="notice" style="margin:0"><strong>Created:</strong> {created() ? new Date(created()).toLocaleString() : '—'}</p>
            <p class="notice" style="margin:0"><strong>Portfolio:</strong> {profile()!.portfolio_url || '—'}</p>
          </div>
        </section>
      </Show>
    </AdminShell>
  );
}
