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

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

type Status = 'UNDER_REVIEW' | 'DOCUMENTS_REQUESTED' | 'REVISION_REQUESTED' | 'APPROVED' | 'REJECTED';

const statusTone = (status: Status) => {
  if (status === 'APPROVED') return { bg: '#ECFDF3', border: '#BBF7D0', text: '#166534', label: 'Approved' };
  if (status === 'DOCUMENTS_REQUESTED') return { bg: '#FFF7ED', border: '#FED7AA', text: '#C2410C', label: 'Request Documents' };
  if (status === 'REVISION_REQUESTED') return { bg: '#FFF7ED', border: '#FED7AA', text: '#C2410C', label: 'Request Changes' };
  if (status === 'REJECTED') return { bg: '#FEF2F2', border: '#FECACA', text: '#B91C1C', label: 'Rejected' };
  return { bg: '#EEF2FF', border: '#C7D2FE', text: '#3730A3', label: 'Under Review' };
};

type DocRequestRow = {
  key: string;
  title: string;
  hint: string;
  enabled: boolean;
  reason: string;
  note: string;
};

type SubmittedDocument = {
  type: string;
  value: string;
  status: string;
};

const formatFieldLabel = (key: string) =>
  String(key || '')
    .replace(/_/g, ' ')
    .replace(/\b\w/g, (c) => c.toUpperCase());

type FieldRevision = {
  id: string;
  field: string;
  currentValue: string;
  reason: string;
  instruction: string;
};

export default function VerificationReviewDetailPage() {
  const params = useParams();
  const [searchParams, setSearchParams] = useSearchParams();

  const [status, setStatus] = createSignal<Status>('UNDER_REVIEW');
  const [tab, setTab] = createSignal<'overview' | 'submitted' | 'documents' | 'missing' | 'requested' | 'activity'>('submitted');

  // ── Real data loaded from backend ─────────────────────────────────────────
  const [verif, setVerif] = createSignal<any>(null);
  const [actionLoading, setActionLoading] = createSignal(false);
  const [actionMsg, setActionMsg] = createSignal('');
  const [rejectReason, setRejectReason] = createSignal('');
  const [showRejectInput, setShowRejectInput] = createSignal(false);

  onMount(async () => {
    const res = await adminFetch(`/api/admin/verifications/${params.id}`);
    if (res.ok) {
      const d = await res.json();
      setVerif(d);
      if (d.status) setStatus(d.status as Status);
    }
  });

  // Catalog of document types that can be requested from the applicant (used by the
  // "Request Documents" action form). This is not the applicant's actual uploaded
  // documents — those come from `verif().documents` via the `uploadedDocs` memo below.
  const [requestCatalog, setRequestCatalog] = createSignal<DocRequestRow[]>([
    { key: 'identity', title: 'Identity Proof', hint: 'Passport, DL or National ID', enabled: true, reason: 'Expired', note: 'Please upload a current valid ID with clear expiry date.' },
    { key: 'address', title: 'Address Proof', hint: 'Utility bill or bank statement (last 3 months)', enabled: false, reason: 'Not Readable', note: '' },
    { key: 'portfolio', title: 'Professional Portfolio', hint: 'Link or PDF showcasing previous work', enabled: false, reason: 'Insufficient', note: '' },
    { key: 'business', title: 'Business Registration', hint: 'Official certificate of incorporation', enabled: false, reason: 'Wrong Document', note: '' },
    { key: 'tax', title: 'Tax Documents', hint: 'GST/VAT registration or annual tax filings', enabled: false, reason: 'Missing', note: '' },
    { key: 'experience', title: 'Experience Certificate', hint: 'Employment letters from previous employers', enabled: false, reason: 'Missing', note: '' },
  ]);

  // Real customer-uploaded documents, from the fetched verification's `documents` field.
  const uploadedDocs = createMemo<SubmittedDocument[]>(() => {
    const list = verif()?.documents;
    return Array.isArray(list) ? list : [];
  });

  // Real submitted profile data, from the fetched verification's `payload` field.
  // A small number of older submissions accidentally stored payload as
  // { roleKey, profile_data: {...} } instead of the flat field object - unwrap
  // defensively so both shapes render correctly here.
  const normalizedPayload = createMemo<Record<string, unknown>>(() => {
    const raw = verif()?.payload ?? {};
    const nested = (raw as any)?.profile_data;
    return (nested && typeof nested === 'object') ? nested : raw;
  });

  const payloadFullName = createMemo(() => {
    const payload = normalizedPayload() as any;
    const name = [payload.first_name, payload.last_name].filter(Boolean).join(' ').trim();
    return name || payload.company_name || payload.full_name || '—';
  });

  const payloadEntries = createMemo<Array<[string, unknown]>>(() => {
    const payload = normalizedPayload();
    const skipKeys = new Set(['first_name', 'last_name', 'company_name', 'full_name', 'documents']);
    return Object.entries(payload).filter(([key, value]) => {
      if (skipKeys.has(key)) return false;
      if (value == null || value === '') return false;
      if (typeof value === 'object') return false;
      return true;
    });
  });

  const [deadline, setDeadline] = createSignal('2026-04-08');
  const [notifyUser, setNotifyUser] = createSignal(true);
  const [markActionRequired, setMarkActionRequired] = createSignal(true);

  const [revisionRows, setRevisionRows] = createSignal<FieldRevision[]>([
    {
      id: '1',
      field: 'Bio',
      currentValue: '"I am a good worker with lots of skills."',
      reason: 'Vague',
      instruction: 'Please provide a detailed professional bio with role-specific outcomes and project context.',
    },
    {
      id: '2',
      field: 'Years of Experience',
      currentValue: '"1 year"',
      reason: 'Inconsistent',
      instruction: 'This value does not match documents. Update to accurate experience timeline.',
    },
  ]);

  const [activityNotes, setActivityNotes] = createSignal<string[]>([
    'Initial submission received.',
    'Verification review started by admin.',
  ]);

  const [reviewerNote, setReviewerNote] = createSignal('Please confirm missing documents and profile correction details.');

  const activeAction = createMemo<'none' | 'request-documents' | 'request-changes'>(() => {
    const action = String(searchParams.action || '').toLowerCase();
    if (action === 'request-documents') return 'request-documents';
    if (action === 'request-changes') return 'request-changes';
    return 'none';
  });

  const requestCount = createMemo(() => requestCatalog().filter((d) => d.enabled).length + revisionRows().length);

  const updateDocRow = (key: string, patch: Partial<DocRequestRow>) => {
    setRequestCatalog((prev) => prev.map((row) => (row.key === key ? { ...row, ...patch } : row)));
  };

  const openRequestDocuments = () => {
    setSearchParams({ ...searchParams, action: 'request-documents' });
    setStatus('DOCUMENTS_REQUESTED');
    setTab('documents');
  };

  const openRequestChanges = () => {
    setSearchParams({ ...searchParams, action: 'request-changes' });
    setStatus('REVISION_REQUESTED');
    setTab('missing');
  };

  const clearActionMode = () => {
    const next = { ...searchParams } as Record<string, string>;
    delete next.action;
    setSearchParams(next);
  };

  const sendDocumentRequest = async () => {
    const selected = requestCatalog().filter((d) => d.enabled);
    if (selected.length === 0) { setActionMsg('Select at least one document to request.'); return; }
    const message = selected
      .map((d) => `${d.title} — ${d.reason}${d.note ? ': ' + d.note : ''}`)
      .join(' | ');
    setActionLoading(true);
    setActionMsg('');
    try {
      const res = await adminFetch(`/api/admin/verifications/${params.id}/request-documents`, {
        method: 'POST',
        body: JSON.stringify({ message }),
      });
      if (res.ok) {
        setStatus('DOCUMENTS_REQUESTED');
        setTab('requested');
        clearActionMode();
        setActivityNotes((prev) => [...prev, `Document request sent: ${message}`]);
        setActionMsg('Document request sent to applicant.');
      } else {
        const d = await res.json().catch(() => ({}));
        setActionMsg(d.error ?? 'Failed to send document request.');
      }
    } catch {
      setActionMsg('Network error. Please try again.');
    } finally {
      setActionLoading(false);
    }
  };

  const sendRevisionRequest = async () => {
    const message = revisionRows()
      .map((r) => `${r.field} (${r.reason}): ${r.instruction}`)
      .join(' | ');
    setActionLoading(true);
    setActionMsg('');
    try {
      const res = await adminFetch(`/api/admin/verifications/${params.id}/request-documents`, {
        method: 'POST',
        body: JSON.stringify({ message: `Revision required — ${message}` }),
      });
      if (res.ok) {
        setStatus('REVISION_REQUESTED');
        setTab('requested');
        clearActionMode();
        setActivityNotes((prev) => [...prev, 'Profile revision request sent to applicant.']);
        setActionMsg('Revision request sent to applicant.');
      } else {
        const d = await res.json().catch(() => ({}));
        setActionMsg(d.error ?? 'Failed to send revision request.');
      }
    } catch {
      setActionMsg('Network error. Please try again.');
    } finally {
      setActionLoading(false);
    }
  };

  const approveSubmission = async () => {
    setActionLoading(true);
    setActionMsg('');
    try {
      const res = await adminFetch(`/api/admin/verifications/${params.id}/approve`, {
        method: 'POST',
        body: JSON.stringify({ notes: reviewerNote() || undefined }),
      });
      if (res.ok) {
        setStatus('APPROVED');
        clearActionMode();
        setActivityNotes((prev) => [...prev, 'Verification approved. Role activated.']);
        setActionMsg('Approved. User role has been activated.');
      } else {
        const d = await res.json().catch(() => ({}));
        setActionMsg(d.error ?? 'Approval failed. Please try again.');
      }
    } catch {
      setActionMsg('Network error. Please try again.');
    } finally {
      setActionLoading(false);
    }
  };

  const addNote = async () => {
    const note = reviewerNote().trim();
    if (!note) return;
    setActionLoading(true);
    setActionMsg('');
    try {
      const res = await adminFetch(`/api/admin/verifications/${params.id}/notes`, {
        method: 'POST',
        body: JSON.stringify({ notes: note }),
      });
      if (res.ok) {
        setActivityNotes((prev) => [...prev, `Reviewer note: ${note}`]);
        setActionMsg('Note added.');
      } else {
        const d = await res.json().catch(() => ({}));
        setActionMsg(d.error ?? 'Failed to add note. Please try again.');
      }
    } catch {
      setActionMsg('Network error. Please try again.');
    } finally {
      setActionLoading(false);
    }
  };

  const rejectSubmission = async () => {
    if (!rejectReason().trim()) { setShowRejectInput(true); return; }
    setActionLoading(true);
    setActionMsg('');
    try {
      const res = await adminFetch(`/api/admin/verifications/${params.id}/reject`, {
        method: 'POST',
        body: JSON.stringify({ reason: rejectReason(), notes: rejectReason() }),
      });
      if (res.ok) {
        setStatus('REJECTED');
        setShowRejectInput(false);
        clearActionMode();
        setActivityNotes((prev) => [...prev, `Submission rejected: ${rejectReason()}`]);
        setActionMsg('Submission rejected. User has been notified.');
      } else {
        const d = await res.json().catch(() => ({}));
        setActionMsg(d.error ?? 'Rejection failed. Please try again.');
      }
    } catch {
      setActionMsg('Network error. Please try again.');
    } finally {
      setActionLoading(false);
    }
  };

  const addRevisionField = () => {
    const id = String(Date.now());
    setRevisionRows((prev) => [...prev, { id, field: 'New Field', currentValue: '"current value"', reason: 'Inconsistent', instruction: '' }]);
  };

  const tone = createMemo(() => statusTone(status()));
  const roleLabel = createMemo(() => String(searchParams.type || 'Portfolio Approval'));

  return (
      <div class="w-full pb-8">
        <A href="/admin/verification" style="display:inline-flex;align-items:center;gap:8px;margin-bottom:8px;color:#475569;font-size:13px;text-decoration:none">
          ← Back to Verification Management
        </A>

        <div style="display:flex;align-items:flex-start;justify-content:space-between;gap:12px;flex-wrap:wrap">
          <div>
            <h1 style="margin:0;font-size:42px;line-height:1.08;font-weight:800;color:#111827">Review Submission: #{verif()?.reference_number ?? params.id}</h1>
            <p style="margin:8px 0 0;font-size:14px;color:#6B7280">Applicant verification detail and action flow.</p>
          </div>

          <div style="display:flex;align-items:center;gap:8px;flex-wrap:wrap">
            <span style={`display:inline-flex;align-items:center;height:32px;padding:0 12px;border-radius:999px;border:1px solid ${tone().border};background:${tone().bg};color:${tone().text};font-size:12px;font-weight:700`}>
              {tone().label}
            </span>
            <button type="button" onClick={openRequestDocuments} disabled={actionLoading()} style="height:36px;border-radius:10px;border:1px solid #E5E7EB;background:white;padding:0 12px;font-size:13px;font-weight:700;color:#374151">Request Documents</button>
            <button type="button" onClick={openRequestChanges} disabled={actionLoading()} style="height:36px;border-radius:10px;border:1px solid #E5E7EB;background:white;padding:0 12px;font-size:13px;font-weight:700;color:#374151">Request Changes</button>
            <button type="button" onClick={rejectSubmission} disabled={actionLoading()} style="height:36px;border-radius:10px;border:1px solid #FECACA;background:white;padding:0 12px;font-size:13px;font-weight:700;color:#B91C1C">Reject</button>
            <button type="button" onClick={approveSubmission} disabled={actionLoading()} style={`height:36px;border-radius:10px;border:none;background:#0D0D2A;padding:0 14px;font-size:13px;font-weight:700;color:white;opacity:${actionLoading() ? '0.6' : '1'}`}>{actionLoading() ? 'Processing…' : 'Approve Submission'}</button>
          </div>
        </div>

        {/* ── Reject reason input ── */}
        <Show when={showRejectInput()}>
          <div style="margin-top:12px;background:#FEF2F2;border:1px solid #FECACA;border-radius:12px;padding:14px;display:flex;flex-direction:column;gap:10px">
            <p style="margin:0;font-size:14px;font-weight:700;color:#B91C1C">Enter Rejection Reason</p>
            <textarea
              rows={3}
              placeholder="Explain why this submission is being rejected…"
              value={rejectReason()}
              onInput={(e) => setRejectReason(e.currentTarget.value)}
              style="border:1px solid #FECACA;border-radius:8px;padding:8px 10px;resize:vertical;font-size:13px;color:#374151;background:white"
            />
            <div style="display:flex;gap:8px">
              <button type="button" onClick={rejectSubmission} disabled={actionLoading() || !rejectReason().trim()} style={`height:36px;border-radius:10px;border:none;background:#B91C1C;padding:0 14px;font-size:13px;font-weight:700;color:white;opacity:${!rejectReason().trim() ? '0.5' : '1'}`}>
                {actionLoading() ? 'Rejecting…' : 'Confirm Reject'}
              </button>
              <button type="button" onClick={() => setShowRejectInput(false)} style="height:36px;border-radius:10px;border:1px solid #E5E7EB;background:white;padding:0 12px;font-size:13px;font-weight:700;color:#374151">Cancel</button>
            </div>
          </div>
        </Show>

        {/* ── Action feedback ── */}
        <Show when={actionMsg()}>
          <div style={`margin-top:10px;padding:10px 14px;border-radius:10px;font-size:13px;font-weight:600;${actionMsg().includes('fail') || actionMsg().includes('error') || actionMsg().includes('Failed') || actionMsg().includes('Error') ? 'background:#FEF2F2;color:#B91C1C;border:1px solid #FECACA' : 'background:#ECFDF5;color:#065F46;border:1px solid #6EE7B7'}`}>
            {actionMsg()}
          </div>
        </Show>

        <div style="margin-top:14px;display:grid;grid-template-columns:2fr 1fr;gap:12px">
          <div style="border:1px solid #E5E7EB;background:white;border-radius:14px;padding:14px;display:grid;grid-template-columns:1fr 1fr 1fr;gap:14px">
            <div><p style="margin:0;font-size:11px;color:#9CA3AF;text-transform:uppercase;letter-spacing:0.04em">Applicant</p><p style="margin:6px 0 0;font-size:30px;font-weight:800;color:#111827;line-height:1.1">{(normalizedPayload() as any)?.first_name ?? (normalizedPayload() as any)?.company_name ?? '—'} {(normalizedPayload() as any)?.last_name ?? ''}</p></div>
            <div><p style="margin:0;font-size:11px;color:#9CA3AF;text-transform:uppercase;letter-spacing:0.04em">Role</p><p style="margin:6px 0 0;font-size:18px;font-weight:700;color:#111827">{verif()?.role_key ?? roleLabel()}</p></div>
            <div><p style="margin:0;font-size:11px;color:#9CA3AF;text-transform:uppercase;letter-spacing:0.04em">Submitted</p><p style="margin:6px 0 0;font-size:18px;font-weight:700;color:#111827">{verif()?.created_at ? new Date(verif().created_at).toLocaleDateString('en-IN') : '—'}</p></div>
          </div>

          <div style="border:1px solid #E5E7EB;background:white;border-radius:14px;padding:14px">
            <p style="margin:0;font-size:12px;font-weight:700;color:#64748B;letter-spacing:0.06em;text-transform:uppercase">Submission Summary</p>
            <div style="margin-top:10px;display:grid;grid-template-columns:1fr auto;gap:6px 12px;font-size:13px;color:#374151">
              <span>Sub ID</span><strong style="color:#111827">#{verif()?.reference_number ?? params.id}</strong>
              <span>Date Submitted</span><strong style="color:#111827">2026-04-01</strong>
              <span>Reviewer</span><strong style="color:#111827">Admin User</strong>
              <span>Pending Requests</span><strong style="color:#111827">{requestCount()}</strong>
            </div>
          </div>
        </div>

        <div style="margin-top:12px;display:flex;align-items:center;gap:20px;border-bottom:1px solid #E5E7EB;overflow:auto">
          <For each={[
            { key: 'overview', label: 'Overview' },
            { key: 'submitted', label: 'Submitted Details' },
            { key: 'documents', label: 'Documents' },
            { key: 'missing', label: 'Missing Information' },
            { key: 'requested', label: `Requested Actions (${requestCount()})` },
            { key: 'activity', label: 'Activity Log' },
          ] as const}>{(item) => (
            <button
              type="button"
              onClick={() => setTab(item.key)}
              style={`padding:0 0 10px;font-size:13px;font-weight:500;background:none;border:none;white-space:nowrap;cursor:pointer;${tab() === item.key ? 'color:#FF5E13;border-bottom:2px solid #FF5E13;margin-bottom:-1px' : 'color:#6B7280'}`}
            >
              {item.label}
            </button>
          )}</For>
        </div>

        <div style="margin-top:12px;display:grid;grid-template-columns:2fr 1fr;gap:12px;align-items:start">
          <div>
            <Show when={activeAction() === 'request-documents'}>
              <div class="table-card" style="border-radius:14px;padding:14px">
                <h3 style="margin:0;font-size:28px;font-weight:800;color:#111827">Request Documents</h3>
                <p style="margin:8px 0 12px;font-size:13px;color:#64748B">Select missing or invalid documents and send one clear request.</p>
                <div style="display:grid;gap:10px">
                  <For each={requestCatalog()}>
                    {(row) => (
                      <div style="border:1px solid #E5E7EB;border-radius:12px;background:#FAFAFA;padding:12px;display:grid;grid-template-columns:auto 1fr;gap:10px;align-items:flex-start">
                        <input type="checkbox" checked={row.enabled} onChange={(e) => updateDocRow(row.key, { enabled: e.currentTarget.checked })} style="margin-top:4px;width:16px;height:16px;accent-color:#FF5E13" />
                        <div>
                          <p style="margin:0;font-size:18px;font-weight:700;color:#111827">{row.title}</p>
                          <p style="margin:4px 0 8px;font-size:12px;color:#6B7280">{row.hint}</p>
                          <Show when={row.enabled}>
                            <div style="display:grid;grid-template-columns:1fr;gap:8px">
                              <select value={row.reason} onChange={(e) => updateDocRow(row.key, { reason: e.currentTarget.value })} style="height:36px;border:1px solid #E5E7EB;border-radius:8px;padding:0 10px;background:white;font-size:13px;color:#374151">
                                <option>Missing</option>
                                <option>Expired</option>
                                <option>Not Readable</option>
                                <option>Wrong Document</option>
                                <option>Insufficient</option>
                              </select>
                              <textarea value={row.note} onInput={(e) => updateDocRow(row.key, { note: e.currentTarget.value })} placeholder="Reviewer note" style="min-height:64px;border:1px solid #E5E7EB;border-radius:8px;padding:8px 10px;resize:vertical;background:white;font-size:13px;color:#374151" />
                            </div>
                          </Show>
                        </div>
                      </div>
                    )}
                  </For>
                </div>

                <div style="margin-top:12px;display:grid;grid-template-columns:1fr 1fr;gap:10px">
                  <div style="border:1px solid #E5E7EB;border-radius:10px;background:#FFFFFF;padding:10px">
                    <p style="margin:0 0 8px;font-size:12px;font-weight:700;color:#6B7280;text-transform:uppercase;letter-spacing:0.04em">Submission Deadline</p>
                    <input type="date" value={deadline()} onInput={(e) => setDeadline(e.currentTarget.value)} style="height:36px;width:100%;border:1px solid #E5E7EB;border-radius:8px;padding:0 10px;font-size:13px;color:#374151" />
                  </div>
                  <div style="border:1px solid #E5E7EB;border-radius:10px;background:#FFFFFF;padding:10px;display:grid;gap:8px">
                    <label style="display:flex;align-items:center;justify-content:space-between;gap:8px;font-size:13px;color:#374151;font-weight:600">
                      Notify user via email/SMS
                      <input type="checkbox" checked={notifyUser()} onChange={(e) => setNotifyUser(e.currentTarget.checked)} />
                    </label>
                    <label style="display:flex;align-items:center;justify-content:space-between;gap:8px;font-size:13px;color:#374151;font-weight:600">
                      Mark submission as action required
                      <input type="checkbox" checked={markActionRequired()} onChange={(e) => setMarkActionRequired(e.currentTarget.checked)} />
                    </label>
                  </div>
                </div>

                <div style="margin-top:12px;display:flex;justify-content:flex-end;gap:8px">
                  <button type="button" onClick={clearActionMode} style="height:36px;border-radius:10px;border:1px solid #E5E7EB;background:white;padding:0 12px;font-size:13px;font-weight:700;color:#475569">Cancel</button>
                  <button type="button" onClick={sendDocumentRequest} disabled={actionLoading()} style={`height:36px;border-radius:10px;border:none;background:#0D0D2A;padding:0 12px;font-size:13px;font-weight:700;color:white;opacity:${actionLoading() ? '0.6' : '1'}`}>{actionLoading() ? 'Sending…' : 'Send Request'}</button>
                </div>
              </div>
            </Show>

            <Show when={activeAction() === 'request-changes'}>
              <div class="table-card" style="border-radius:14px;padding:14px">
                <h3 style="margin:0;font-size:28px;font-weight:800;color:#111827">Request Information Changes</h3>
                <p style="margin:8px 0 12px;font-size:13px;color:#64748B">Detail profile fields that need correction or clarification.</p>
                <div style="display:grid;gap:10px">
                  <For each={revisionRows()}>
                    {(row) => (
                      <div style="border:1px solid #E5E7EB;border-radius:12px;background:#FAFAFA;padding:12px">
                        <div style="display:grid;grid-template-columns:1fr 1fr;gap:8px">
                          <div>
                            <p style="margin:0 0 6px;font-size:11px;color:#9CA3AF;text-transform:uppercase">Field Name</p>
                            <input value={row.field} onInput={(e) => setRevisionRows((prev) => prev.map((item) => item.id === row.id ? { ...item, field: e.currentTarget.value } : item))} style="height:36px;width:100%;border:1px solid #E5E7EB;border-radius:8px;padding:0 10px;background:white;font-size:13px;color:#374151" />
                          </div>
                          <div>
                            <p style="margin:0 0 6px;font-size:11px;color:#9CA3AF;text-transform:uppercase">Current Value</p>
                            <input value={row.currentValue} onInput={(e) => setRevisionRows((prev) => prev.map((item) => item.id === row.id ? { ...item, currentValue: e.currentTarget.value } : item))} style="height:36px;width:100%;border:1px solid #E5E7EB;border-radius:8px;padding:0 10px;background:white;font-size:13px;color:#374151" />
                          </div>
                          <div>
                            <p style="margin:0 0 6px;font-size:11px;color:#9CA3AF;text-transform:uppercase">Reason</p>
                            <select value={row.reason} onChange={(e) => setRevisionRows((prev) => prev.map((item) => item.id === row.id ? { ...item, reason: e.currentTarget.value } : item))} style="height:36px;width:100%;border:1px solid #E5E7EB;border-radius:8px;padding:0 10px;background:white;font-size:13px;color:#374151">
                              <option>Inconsistent</option>
                              <option>Vague</option>
                              <option>Mismatch</option>
                              <option>Incomplete</option>
                            </select>
                          </div>
                          <div>
                            <p style="margin:0 0 6px;font-size:11px;color:#9CA3AF;text-transform:uppercase">Reviewer Instruction</p>
                            <input value={row.instruction} onInput={(e) => setRevisionRows((prev) => prev.map((item) => item.id === row.id ? { ...item, instruction: e.currentTarget.value } : item))} style="height:36px;width:100%;border:1px solid #E5E7EB;border-radius:8px;padding:0 10px;background:white;font-size:13px;color:#374151" />
                          </div>
                        </div>
                      </div>
                    )}
                  </For>
                </div>

                <button type="button" onClick={addRevisionField} style="margin-top:10px;height:36px;border-radius:10px;border:1px dashed #FFD8C2;background:#FFFCFA;padding:0 12px;font-size:13px;font-weight:700;color:#C2410C">+ Add Another Field</button>

                <div style="margin-top:12px;display:flex;justify-content:flex-end;gap:8px">
                  <button type="button" onClick={clearActionMode} style="height:36px;border-radius:10px;border:1px solid #E5E7EB;background:white;padding:0 12px;font-size:13px;font-weight:700;color:#475569">Cancel</button>
                  <button type="button" onClick={sendRevisionRequest} disabled={actionLoading()} style={`height:36px;border-radius:10px;border:none;background:#0D0D2A;padding:0 12px;font-size:13px;font-weight:700;color:white;opacity:${actionLoading() ? '0.6' : '1'}`}>{actionLoading() ? 'Sending…' : 'Submit Revision Request'}</button>
                </div>
              </div>
            </Show>

            <Show when={activeAction() === 'none' && tab() === 'submitted'}>
              <div class="table-card" style="border-radius:14px;padding:14px">
                <h3 style="margin:0 0 10px;font-size:24px;font-weight:800;color:#111827">Profile Data</h3>
                <div style="display:grid;grid-template-columns:1fr 1fr;gap:12px">
                  <div><p style="margin:0;font-size:11px;color:#9CA3AF;letter-spacing:0.04em;text-transform:uppercase">Full Name</p><p style="margin:6px 0 0;font-size:18px;font-weight:700;color:#111827">{payloadFullName()}</p></div>
                  <div><p style="margin:0;font-size:11px;color:#9CA3AF;letter-spacing:0.04em;text-transform:uppercase">Role</p><p style="margin:6px 0 0;font-size:18px;font-weight:700;color:#111827">{verif()?.role_key ?? roleLabel()}</p></div>
                </div>
                <Show when={payloadEntries().length > 0} fallback={<p style="margin:14px 0 0;font-size:13px;color:#9CA3AF">No submitted profile data available.</p>}>
                  <div style="margin-top:14px;display:grid;grid-template-columns:1fr 1fr;gap:12px">
                    <For each={payloadEntries()}>
                      {([key, value]) => (
                        <div>
                          <p style="margin:0;font-size:11px;color:#9CA3AF;letter-spacing:0.04em;text-transform:uppercase">{formatFieldLabel(key)}</p>
                          <p style="margin:6px 0 0;font-size:13px;line-height:1.6;color:#374151">{String(value)}</p>
                        </div>
                      )}
                    </For>
                  </div>
                </Show>
              </div>
            </Show>

            <Show when={activeAction() === 'none' && tab() === 'documents'}>
              <div class="table-card" style="border-radius:14px;overflow:hidden">
                <table class="data-table w-full text-sm">
                  <thead><tr><For each={['Document', 'File', 'Status']}>{(h) => <th>{h}</th>}</For></tr></thead>
                  <tbody>
                    <Show when={uploadedDocs().length > 0} fallback={<tr><td colSpan={3} style="text-align:center;padding:24px;color:#94A3B8">No documents uploaded yet.</td></tr>}>
                      <For each={uploadedDocs()}>{(doc) => (
                        <tr>
                          <td><strong>{formatFieldLabel(doc.type)}</strong></td>
                          <td>
                            <Show when={doc.value} fallback={<span style="color:#9CA3AF">—</span>}>
                              <a href={doc.value} target="_blank" rel="noopener noreferrer" style="color:#2563EB;text-decoration:underline;font-size:13px">View Document</a>
                            </Show>
                          </td>
                          <td>{formatFieldLabel(doc.status)}</td>
                        </tr>
                      )}</For>
                    </Show>
                  </tbody>
                </table>
              </div>
            </Show>

            <Show when={activeAction() === 'none' && tab() === 'missing'}>
              <div class="table-card" style="border-radius:14px;padding:14px">
                <h3 style="margin:0 0 10px;font-size:22px;font-weight:800;color:#111827">Flagged Fields for Correction</h3>
                <div style="display:grid;gap:10px">
                  <For each={revisionRows()}>{(row) => (
                    <div style="border:1px solid #E5E7EB;border-radius:12px;background:#FAFAFA;padding:12px">
                      <p style="margin:0;font-size:14px;font-weight:700;color:#111827">{row.field}</p>
                      <p style="margin:4px 0 0;font-size:13px;color:#64748B">Current: {row.currentValue}</p>
                      <p style="margin:6px 0 0;font-size:13px;color:#374151">{row.instruction || 'Please update this field based on documents.'}</p>
                    </div>
                  )}</For>
                </div>
                <button type="button" onClick={openRequestChanges} style="margin-top:10px;height:36px;border-radius:10px;border:1px solid #E5E7EB;background:white;padding:0 12px;font-size:13px;font-weight:700;color:#374151">Request Changes</button>
              </div>
            </Show>

            <Show when={activeAction() === 'none' && tab() === 'requested'}>
              <div class="table-card" style="border-radius:14px;padding:14px">
                <h3 style="margin:0 0 10px;font-size:22px;font-weight:800;color:#111827">Pending Requests</h3>
                <div style="display:grid;gap:10px">
                  <div style="border:1px solid #E5E7EB;border-radius:12px;background:#FAFAFA;padding:12px">
                    <p style="margin:0;font-size:18px;font-weight:700;color:#111827">Update Bio - Incomplete</p>
                    <p style="margin:6px 0 0;font-size:13px;color:#64748B">The professional biography must include specific role experience and outcomes.</p>
                    <div style="margin-top:8px;display:flex;gap:8px">
                      <button type="button" style="height:32px;border-radius:10px;border:1px solid #E5E7EB;background:white;padding:0 12px;font-size:13px;font-weight:700;color:#475569">Resend Notification</button>
                      <button type="button" style="height:32px;border-radius:10px;border:none;background:#0D0D2A;padding:0 12px;font-size:13px;font-weight:700;color:white">Mark as Resolved</button>
                    </div>
                  </div>
                  <div style="border:1px solid #E5E7EB;border-radius:12px;background:#FAFAFA;padding:12px">
                    <p style="margin:0;font-size:18px;font-weight:700;color:#111827">Re-upload Identity Proof - Expired</p>
                    <p style="margin:6px 0 0;font-size:13px;color:#64748B">Submitted passport scan shows expired date. Upload current valid ID.</p>
                    <div style="margin-top:8px;display:flex;gap:8px">
                      <button type="button" style="height:32px;border-radius:10px;border:1px solid #E5E7EB;background:white;padding:0 12px;font-size:13px;font-weight:700;color:#475569">Resend Notification</button>
                      <button type="button" style="height:32px;border-radius:10px;border:none;background:#0D0D2A;padding:0 12px;font-size:13px;font-weight:700;color:white">Mark as Resolved</button>
                    </div>
                  </div>
                </div>
              </div>
            </Show>

            <Show when={activeAction() === 'none' && tab() === 'activity'}>
              <div class="table-card" style="border-radius:14px;padding:14px">
                <h3 style="margin:0 0 10px;font-size:22px;font-weight:800;color:#111827">Activity Log</h3>
                <div style="display:grid;gap:8px">
                  <For each={activityNotes()}>{(note) => (
                    <div style="border:1px solid #E5E7EB;border-radius:10px;background:#FAFAFA;padding:10px;font-size:13px;color:#374151">{note}</div>
                  )}</For>
                </div>
              </div>
            </Show>

            <Show when={activeAction() === 'none' && tab() === 'overview'}>
              <div class="table-card" style="border-radius:14px;padding:14px">
                <h3 style="margin:0 0 10px;font-size:22px;font-weight:800;color:#111827">Overview</h3>
                <p style="margin:0;font-size:13px;line-height:1.6;color:#374151">Review submission details, verify uploaded documents, request missing information when needed, then move eligible submissions to final approval management.</p>
              </div>
            </Show>
          </div>

          <div style="display:grid;gap:12px">
            <div class="table-card" style="border-radius:14px;padding:14px">
              <p style="margin:0;font-size:12px;font-weight:700;color:#64748B;letter-spacing:0.06em;text-transform:uppercase">Verification Checklist</p>
              <div style="margin-top:10px;display:grid;gap:8px;font-size:13px;color:#111827">
                <label style="display:flex;gap:8px;align-items:center"><input type="checkbox" checked /> Identity Verified</label>
                <label style="display:flex;gap:8px;align-items:center"><input type="checkbox" checked /> Contact Details Checked</label>
                <label style="display:flex;gap:8px;align-items:center"><input type="checkbox" /> Portfolio Quality Check</label>
                <label style="display:flex;gap:8px;align-items:center"><input type="checkbox" /> Social Media Verification</label>
              </div>
            </div>

            <div class="table-card" style="border-radius:14px;padding:14px">
              <p style="margin:0;font-size:12px;font-weight:700;color:#64748B;letter-spacing:0.06em;text-transform:uppercase">Reviewer Notes</p>
              <textarea value={reviewerNote()} onInput={(e) => setReviewerNote(e.currentTarget.value)} style="margin-top:8px;width:100%;min-height:110px;border:1px solid #E5E7EB;border-radius:10px;padding:10px;font-size:13px;color:#374151;resize:vertical" />
              <button type="button" onClick={addNote} disabled={actionLoading() || !reviewerNote().trim()} style="margin-top:8px;height:36px;width:100%;border-radius:10px;border:none;background:#0D0D2A;color:white;font-size:13px;font-weight:700">Add Note</button>
            </div>

            <A href="/admin/approval" style="height:36px;border-radius:10px;border:none;background:#0D0D2A;padding:0 12px;font-size:13px;font-weight:700;color:white;display:inline-flex;align-items:center;justify-content:center;text-decoration:none">
              Open Approval Management
            </A>
          </div>
        </div>
      </div>
  );
}
