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

const API = '';

type Lead = {
  id: string;
  requirementId?: string;
  requirement_id?: string;
  profession?: string;
  customerId?: string;
  customer_id?: string;
  professionalId?: string;
  professional_id?: string;
  status?: string;
  createdAt?: string;
  created_at?: string;
  updatedAt?: string;
  updated_at?: string;
};

type Requirement = {
  id: string;
  title?: string;
  description?: string;
  customerName?: string;
  budgetMin?: number;
  budgetMax?: number;
  location?: string;
  status?: string;
};

type LeadBundle = {
  lead: Lead;
  requirement: Requirement | null;
};

async function fetchLeadBundle(id: string): Promise<LeadBundle | null> {
  try {
    const res = await fetch(`${API}/api/leads/${id}`);
    if (!res.ok) return null;
    const data = await res.json();
    const lead: Lead = data.lead || data;

    const requirementId = lead.requirementId || lead.requirement_id || '';
    if (!requirementId) return { lead, requirement: null };

    try {
      const reqRes = await fetch(`${API}/api/requirements/${requirementId}`);
      if (!reqRes.ok) return { lead, requirement: null };
      const reqData = await reqRes.json();
      return { lead, requirement: reqData.requirement || reqData || null };
    } catch {
      return { lead, requirement: null };
    }
  } catch {
    return null;
  }
}

export default function LeadDetailPage() {
  const params = useParams();
  const [bundle] = createResource(() => params.id, fetchLeadBundle);

  const lead = createMemo(() => bundle()?.lead || null);
  const requirement = createMemo(() => bundle()?.requirement || null);
  const requirementId = createMemo(() => lead()?.requirementId || lead()?.requirement_id || '');
  const customerId = createMemo(() => lead()?.customerId || lead()?.customer_id || '');
  const professionalId = createMemo(() => lead()?.professionalId || lead()?.professional_id || '');
  const createdAt = createMemo(() => lead()?.createdAt || lead()?.created_at || '');
  const updatedAt = createMemo(() => lead()?.updatedAt || lead()?.updated_at || '');

  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">Lead Detail</h1>
          <p class="text-sm text-gray-500 mt-0.5">Review one lead and its linked requirement identifiers.</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/leads">Back to Leads</A>
      </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 lead...</p></div>
      </Show>
      <Show when={!bundle.loading && !lead()}>
        <div class="rounded-xl border border-gray-200 bg-white shadow-sm"><p class="notice">Lead not found.</p></div>
      </Show>

      <Show when={lead()}>
        <section class="rounded-xl border border-gray-200 bg-white shadow-sm" style="padding:20px">
          <div class="mt-4 grid grid-cols-1 gap-4 sm:grid-cols-2">
            <div class="kv-item">
              <p class="kv-label">Lead ID</p>
              <p class="kv-value">{lead()!.id}</p>
            </div>
            <div class="kv-item">
              <p class="kv-label">Status</p>
              <p class="kv-value">{lead()!.status || '—'}</p>
            </div>
            <div class="kv-item">
              <p class="kv-label">Profession</p>
              <p class="kv-value">{lead()!.profession || '—'}</p>
            </div>
            <div class="kv-item">
              <p class="kv-label">Professional ID</p>
              <p class="kv-value">{professionalId() || 'Unassigned'}</p>
            </div>
            <div class="kv-item">
              <p class="kv-label">Customer ID</p>
              <p class="kv-value">{customerId() || '—'}</p>
            </div>
            <div class="kv-item">
              <p class="kv-label">Created</p>
              <p class="kv-value">{createdAt() ? new Date(createdAt()).toLocaleString() : '—'}</p>
            </div>
            <Show when={updatedAt()}>
              <div class="kv-item">
                <p class="kv-label">Updated</p>
                <p class="kv-value">{new Date(updatedAt()!).toLocaleString()}</p>
              </div>
            </Show>
            <div class="kv-item">
              <p class="kv-label">Requirement ID</p>
              <p class="kv-value">{requirementId() || '—'}</p>
            </div>
          </div>
          <div class="actions">
            <Show when={requirementId()}>
              <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" href={`/admin/jobs/${requirementId()}`}>Open Linked Requirement/Job</A>
            </Show>
          </div>

          <Show when={requirement()}>
            <div class="sub-card">
              <div class="sub-card-header">
                <h4>Linked Requirement</h4>
              </div>
              <p style="margin:0;font-size:17px;font-weight:700;color:#111827">{requirement()!.title || 'Untitled Requirement'}</p>
              <p class="notice" style="margin-top:8px">{requirement()!.description || 'No description available.'}</p>
              <div class="mt-4 grid grid-cols-1 gap-4 sm:grid-cols-2" style="margin-top:12px">
                <div class="kv-item">
                  <p class="kv-label">Customer</p>
                  <p class="kv-value">{requirement()!.customerName || 'Customer'}</p>
                </div>
                <div class="kv-item">
                  <p class="kv-label">Budget</p>
                  <p class="kv-value">{requirement()!.budgetMin || 0} - {requirement()!.budgetMax || 0}</p>
                </div>
                <div class="kv-item">
                  <p class="kv-label">Location</p>
                  <p class="kv-value">{requirement()!.location || '—'}</p>
                </div>
                <div class="kv-item">
                  <p class="kv-label">Requirement Status</p>
                  <p class="kv-value">{requirement()!.status || '—'}</p>
                </div>
              </div>
            </div>
          </Show>
        </section>
      </Show>
      </div>
      </div>
  );
}
