import { For, Show, createMemo, createSignal, onMount } from 'solid-js';
import type { CrudRecord } from '~/lib/admin/types';

const API = '';
const APPROVAL_QUEUE_STORAGE_KEY = 'nxtgauge_admin_approval_queue';

type ApprovalSubmittedField = { label: string; value: string };
type ApprovalDocument = {
  id: string;
  title: string;
  type: 'IMAGE' | 'PDF';
  url: string;
  status: 'SUBMITTED' | 'MISSING' | 'INVALID';
};

type ApprovalRecord = CrudRecord & {
  applicantName?: string;
  approvalType: 'PROFILE' | 'BUSINESS' | 'JOB' | 'ORDER' | 'INVOICE' | 'COUPON' | 'DISCOUNT' | 'TAX' | 'ROLE' | 'REQUIREMENT' | 'PORTFOLIO';
  userType: 'CUSTOMER' | 'PROFESSIONAL' | 'COMPANY' | 'JOBSEEKER';
  roleTags?: string[];
  primaryService?: string;
  area?: string;
  submittedDate?: string;
  verificationStatus: 'PENDING' | 'VERIFIED' | 'FLAGGED';
  assignedApprover?: string;
  priority: 'LOW' | 'MEDIUM' | 'HIGH' | 'CRITICAL';
  status: 'PENDING' | 'IN_REVIEW' | 'APPROVED' | 'REJECTED' | 'ON_HOLD' | 'ESCALATED';
  sourceKey?: string;
  submittedFields?: ApprovalSubmittedField[];
  documents?: ApprovalDocument[];
  payload?: any;
};

type ApprovalQueueItem = {
  id: string;
  requestType:
  | 'Profile Approval'
  | 'Portfolio Approval'
  | 'Company Approval'
  | 'Job Seeker Approval'
  | 'Service Seeker Profile Approval'
  | 'Service Seeker Requirement'
  | 'Job Approval';
  applicantName: string;
  roleLabel: string;
  userType: 'PROFESSIONAL' | 'COMPANY' | 'JOBSEEKER' | 'CUSTOMER';
  roleKey: string;
  area: string;
  submittedOn: string;
  documents: ApprovalDocument[];
  submittedFields: ApprovalSubmittedField[];
};

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

const normalizeUserType = (value: unknown): ApprovalRecord['userType'] => {
  const key = String(value || '').toUpperCase();
  if (key.includes('COMPANY')) return 'COMPANY';
  if (key.includes('JOB_SEEKER') || key.includes('JOBSEEKER')) return 'JOBSEEKER';
  if (key.includes('CUSTOMER') || key.includes('SERVICE_SEEKER')) return 'CUSTOMER';
  return 'PROFESSIONAL';
};

function extractRoleTags(source: any): string[] {
  const values: string[] = [];
  const pushValue = (value: unknown) => {
    if (!value) return;
    if (Array.isArray(value)) {
      value.forEach((v) => pushValue(v));
      return;
    }
    const text = String(value || '').trim();
    if (!text) return;
    values.push(text);
  };
  pushValue(source?.role_key);
  pushValue(source?.roleKey);
  pushValue(source?.role_keys);
  pushValue(source?.roleKeys);
  pushValue(source?.roles);
  pushValue(source?.categories);
  pushValue(source?.category);
  pushValue(source?.service_category);
  pushValue(source?.serviceCategory);
  pushValue(source?.profession);
  pushValue(source?.service_type);
  return Array.from(new Set(values.map((v) => toTitle(v)))).slice(0, 4);
}

function extractSubmittedFields(source: any): ApprovalSubmittedField[] {
  const payload = source || {};
  const fullName = String(
    payload.full_name
      || payload.fullName
      || [payload.first_name || payload.firstName, payload.last_name || payload.lastName].filter(Boolean).join(' ')
      || payload.company_name
      || payload.title
      || '—',
  ).trim();

  const candidates: ApprovalSubmittedField[] = [
    { label: 'Name / Title', value: fullName || '—' },
    { label: 'Email', value: String(payload.email || payload.email_address || payload.emailAddress || '—') },
    { label: 'Mobile', value: String(payload.mobile || payload.mobile_number || payload.phone || payload.contact_number || '—') },
    { label: 'Role / Category', value: String(payload.role_key || payload.role || payload.category || payload.profession || payload.service_category || '—') },
    { label: 'Area', value: String(payload.area || payload.location || payload.city || 'Chennai') },
    { label: 'Place', value: String(payload.place || payload.locality || payload.city || 'Chennai') },
    { label: 'Description', value: String(payload.description || payload.about || payload.bio || '—') },
  ];

  return candidates.filter((item) => item.value && item.value !== '—');
}

function extractDocuments(source: any): ApprovalDocument[] {
  const raw = Array.isArray(source?.documents) ? source.documents : [];
  if (!raw.length) {
    const portfolioImages = Array.isArray(source?.portfolio_images)
      ? source.portfolio_images
      : Array.isArray(source?.images)
        ? source.images
        : Array.isArray(source?.gallery)
          ? source.gallery
          : [];
    if (!portfolioImages.length) return [];
    return portfolioImages.slice(0, 6).map((asset: any, idx: number) => ({
      id: String(asset.id || `portfolio-${idx + 1}`),
      title: String(asset.title || asset.name || `Portfolio Image ${idx + 1}`),
      type: 'IMAGE',
      url: String(asset.url || '/nxtgauge-logo.png'),
      status: 'SUBMITTED',
    }));
  }
  return raw.slice(0, 12).map((doc: any, idx: number) => {
    const statusRaw = String(doc.status || '').toUpperCase();
    return {
      id: String(doc.id || `doc-${idx + 1}`),
      title: String(doc.title || doc.name || `Document ${idx + 1}`),
      type: String(doc.type || '').toUpperCase().includes('PDF') ? 'PDF' : 'IMAGE',
      url: String(doc.url || '/nxtgauge-logo.png'),
      status: statusRaw === 'MISSING'
        ? 'MISSING'
        : statusRaw === 'INVALID'
          ? 'INVALID'
          : 'SUBMITTED',
    };
  });
}



function verificationToApprovalType(requestType: ApprovalQueueItem['requestType']): ApprovalRecord['approvalType'] {
  if (requestType === 'Portfolio Approval') return 'PORTFOLIO';
  if (requestType === 'Service Seeker Requirement') return 'REQUIREMENT';
  if (requestType === 'Job Approval') return 'JOB';
  if (requestType === 'Company Approval') return 'BUSINESS';
  return 'PROFILE';
}

function caseTypeToRequestType(value: unknown): ApprovalQueueItem['requestType'] {
  const raw = String(value || '').toUpperCase();
  if (raw.includes('JOB')) return 'Job Approval';
  if (raw.includes('REQUIREMENT')) return 'Service Seeker Requirement';
  if (raw.includes('PORTFOLIO')) return 'Portfolio Approval';
  return 'Profile Approval';
}

function mapQueueItemsToApprovals(items: ApprovalQueueItem[]): ApprovalRecord[] {
  return items.map((item) => ({
    id: String(item.id),
    name: `${item.requestType} - ${item.applicantName}`,
    applicantName: item.applicantName,
    approvalType: verificationToApprovalType(item.requestType),
    userType: normalizeUserType(item.userType),
    roleTags: [toTitle(item.roleLabel), toTitle(item.roleKey)].filter((v, i, arr) => v && arr.indexOf(v) === i),
    primaryService: toTitle(item.roleLabel || item.roleKey || item.requestType),
    area: item.area || 'Chennai',
    submittedDate: item.submittedOn || '',
    verificationStatus: 'VERIFIED',
    assignedApprover: 'Unassigned',
    priority: item.requestType === 'Portfolio Approval' || item.requestType === 'Job Approval' ? 'HIGH' : 'MEDIUM',
    status: 'PENDING',
    updatedAt: item.submittedOn || '',
    sourceKey: `verification:${item.id}`,
    submittedFields: Array.isArray(item.submittedFields) ? item.submittedFields : [],
    documents: Array.isArray(item.documents) ? item.documents : [],
    payload: { queueRequestType: item.requestType },
  }));
}

function StatusBadge(props: { status: string }) {
  const getColors = () => {
    switch (props.status) {
      case 'APPROVED': return { border: '#B7E4C7', bg: '#DEF7E8', text: '#0B8A4A', dot: '#0B8A4A' };
      case 'IN_REVIEW': return { border: '#F6D78F', bg: '#FFF3D6', text: '#B7791F', dot: '#B7791F' };
      case 'PENDING': return { border: '#D1D5DB', bg: '#F3F4F6', text: '#4B5563', dot: '#9CA3AF' };
      case 'ON_HOLD': return { border: '#FDE68A', bg: '#FEF3C7', text: '#D97706', dot: '#D97706' };
      case 'ESCALATED': return { border: '#FECACA', bg: '#FEF2F2', text: '#DC2626', dot: '#DC2626' };
      case 'REJECTED': return { border: '#FECACA', bg: '#FEF2F2', text: '#DC2626', dot: '#DC2626' };
      default: return { border: '#D1D5DB', bg: '#F3F4F6', text: '#4B5563', dot: '#9CA3AF' };
    }
  };
  const colors = getColors();
  const label = props.status.split('_').map(w => w.charAt(0) + w.slice(1).toLowerCase()).join(' ');

  return (
    <span style={`display:inline-flex;align-items:center;border-radius:9999px;border:1px solid ${colors.border};background:${colors.bg};color:${colors.text};padding:2px 10px;font-size:12px;font-weight:500`}>
      <span style={`display:inline-block;width:6px;height:6px;border-radius:50%;background:${colors.dot};margin-right:5px;flex-shrink:0`} />
      {label}
    </span>
  );
}

function PriorityBadge(props: { priority: string }) {
  const color = props.priority === 'CRITICAL' ? '#7F1D1D' : props.priority === 'HIGH' ? '#DC2626' : props.priority === 'MEDIUM' ? '#F59E0B' : '#16A34A';
  return (
    <span style={`display:inline-flex;align-items:center;gap:4px;font-size:12px;font-weight:600;color:${color}`}>
      <span style={`width:6px;height:6px;border-radius:50%;background:${color}`} />
      {props.priority}
    </span>
  );
}

function VerificationBadge(props: { status: ApprovalRecord['verificationStatus'] }) {
  const getColors = () => {
    if (props.status === 'VERIFIED') return { border: '#B7E4C7', bg: '#DEF7E8', text: '#0B8A4A', dot: '#0B8A4A' };
    if (props.status === 'FLAGGED') return { border: '#FECACA', bg: '#FEF2F2', text: '#DC2626', dot: '#DC2626' };
    return { border: '#F6D78F', bg: '#FFF3D6', text: '#B7791F', dot: '#B7791F' };
  };
  const colors = getColors();
  return (
    <span style={`display:inline-flex;align-items:center;border-radius:9999px;border:1px solid ${colors.border};background:${colors.bg};color:${colors.text};padding:2px 10px;font-size:12px;font-weight:500`}>
      <span style={`display:inline-block;width:6px;height:6px;border-radius:50%;background:${colors.dot};margin-right:5px;flex-shrink:0`} />
      {props.status}
    </span>
  );
}

export default function ApprovalManagementPage() {
  const [listTab, setListTab] = createSignal<'all' | 'view' | 'escalated'>('all');
  const [detailTab, setDetailTab] = createSignal<'overview' | 'verification' | 'checklist' | 'logs'>('overview');

  const [search, setSearch] = createSignal('');
  const [rows, setRows] = createSignal<ApprovalRecord[]>([]);
  const [viewingCase, setViewingCase] = createSignal<ApprovalRecord | null>(null);
  const [openMenuId, setOpenMenuId] = createSignal<string | null>(null);

  const [statusFilter, setStatusFilter] = createSignal<'all' | 'pending' | 'escalated'>('all');
  const [sortBy, setSortBy] = createSignal<'submitted_desc' | 'submitted_asc' | 'priority_desc' | 'priority_asc'>('submitted_desc');
  const [sortMenuOpen, setSortMenuOpen] = createSignal(false);
  const [filterMenuOpen, setFilterMenuOpen] = createSignal(false);
  const [error, setError] = createSignal('');
  const [isActing, setIsActing] = createSignal(false);
  const [decisionNote, setDecisionNote] = createSignal('');

  const selectedDocuments = createMemo<ApprovalDocument[]>(() => {
    const row = viewingCase();
    if (!row) return [];
    if (Array.isArray(row.documents) && row.documents.length) return row.documents;
    return extractDocuments(row.payload || {});
  });

  const selectedFields = createMemo<ApprovalSubmittedField[]>(() => {
    const row = viewingCase();
    if (!row) return [];
    if (Array.isArray(row.submittedFields) && row.submittedFields.length) return row.submittedFields;
    return extractSubmittedFields(row.payload || row);
  });

  const load = async () => {
    setError('');
    try {
      const accessToken = typeof sessionStorage !== 'undefined'
        ? sessionStorage.getItem('nxtgauge_admin_access_token') || ''
        : '';
      const res = await fetch(`${API}/api/admin/verifications?page=1&limit=100`, {
        headers: {
          Accept: 'application/json',
          ...(accessToken ? { Authorization: `Bearer ${accessToken}` } : {}),
        },
        credentials: 'include',
      });
      if (!res.ok) throw new Error(`Request failed (${res.status})`);
      const payload = await res.json().catch(() => ({} as any));
      const items = Array.isArray(payload?.items) ? payload.items : [];

      const mappedItems: ApprovalRecord[] = items
        .filter((v: any) => String(v?.status || '').toUpperCase() === 'APPROVED')
        .map((v: any) => {
        const p = v.payload || {};
        const requestType = caseTypeToRequestType(v.type || v.case_type);
        return {
          id: v.id,
          name: `${toTitle(v.type || v.case_type || 'approval')} - ${v.user_name || 'Applicant'}`,
          applicantName: v.user_name || 'Applicant',
          approvalType: verificationToApprovalType(requestType),
          userType: normalizeUserType(v.role_key),
          roleTags: [toTitle(v.role_key)],
          primaryService: toTitle(v.role_key || 'User'),
          area: p.city || p.area || 'Unknown',
          submittedDate: v.created_at,
          verificationStatus: 'VERIFIED',
          assignedApprover: 'Unassigned',
          priority: 'MEDIUM',
          status: 'PENDING',
          updatedAt: v.updated_at,
          sourceKey: `v:${v.id}`,
          submittedFields: extractSubmittedFields(p),
          documents: extractDocuments(p),
          payload: v,
        };
      });
      
      setRows(mappedItems);
    } catch (e: any) {
      setRows([]);
      setError(e?.message || 'Could not reach approvals API.');
    }
  };

  onMount(() => void load());

  const formatDate = (v?: string) => {
    const s = v || '';
    if (/^\d{4}-\d{2}-\d{2}$/.test(s)) return s;
    return s.slice(0, 10) || '—';
  };

  const filteredRows = createMemo(() => {
    let list = rows();
    const f = statusFilter();
    if (f === 'pending') list = list.filter((r) => r.status === 'PENDING' || r.status === 'IN_REVIEW');
    if (f === 'escalated') list = list.filter((r) => r.status === 'ESCALATED');

    const q = search().trim().toLowerCase();
    if (q) {
      list = list.filter((r) =>
        String(r.applicantName || '').toLowerCase().includes(q)
        || String(r.id || '').toLowerCase().includes(q)
        || String(r.approvalType || '').toLowerCase().includes(q)
      );
    }

    const sorted = [...list];
    const mode = sortBy();
    const priorityRank = (p: ApprovalRecord['priority']) => (p === 'CRITICAL' ? 4 : p === 'HIGH' ? 3 : p === 'MEDIUM' ? 2 : 1);
    sorted.sort((a, b) => {
      const ad = Date.parse(String(a.submittedDate || a.updatedAt || '')) || 0;
      const bd = Date.parse(String(b.submittedDate || b.updatedAt || '')) || 0;
      if (mode === 'submitted_asc') return ad - bd;
      if (mode === 'priority_desc') return priorityRank(b.priority) - priorityRank(a.priority);
      if (mode === 'priority_asc') return priorityRank(a.priority) - priorityRank(b.priority);
      return bd - ad;
    });
    return sorted;
  });

  const escalatedCount = createMemo(() => rows().filter((r) => r.status === 'ESCALATED').length);

  const exportCsv = () => {
    const headers = ['Approval ID', 'Applicant', 'Type', 'Verification', 'Priority', 'Status', 'Submitted Date'];
    const rowsData = filteredRows().map((row) => [
      row.id || '',
      row.applicantName || '',
      row.approvalType || '',
      row.verificationStatus || '',
      row.priority || '',
      row.status || '',
      formatDate(row.submittedDate || row.updatedAt),
    ]);
    const csv = [headers, ...rowsData]
      .map((line) => line.map((cell) => `"${String(cell).replace(/"/g, '""')}"`).join(','))
      .join('\n');
    const blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = `approval-management-${new Date().toISOString().slice(0, 10)}.csv`;
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    URL.revokeObjectURL(url);
  };

  const openView = (row: ApprovalRecord) => {
    setViewingCase(row);
    setDetailTab('overview');
    setListTab('view');
    setOpenMenuId(null);
  };

  const setLocalStatus = (row: ApprovalRecord, nextStatus: ApprovalRecord['status']) => {
    setRows((prev) => prev.map((item) => ((item.sourceKey || item.id) === (row.sourceKey || row.id) ? { ...item, status: nextStatus } : item)));
    setViewingCase((current) => {
      if (!current) return current;
      return (current.sourceKey || current.id) === (row.sourceKey || row.id) ? { ...current, status: nextStatus } : current;
    });
  };

  const runApprovalAction = async (row: ApprovalRecord, action: 'approve' | 'reject') => {
    const type = row.approvalType;
    const nextStatus: ApprovalRecord['status'] = action === 'approve' ? 'APPROVED' : 'REJECTED';

    const payload = row.payload || {};
    const verificationPayload = payload.payload || {};
    const verificationId = String(payload.id || row.id || '');
    const targetId = String(
      verificationPayload.entity_id
      || verificationPayload.job_id
      || verificationPayload.requirement_id
      || payload.entity_id
      || payload.job_id
      || payload.requirement_id
      || '',
    );

    setIsActing(true);
    setError('');
    try {
      const accessToken = typeof sessionStorage !== 'undefined'
        ? sessionStorage.getItem('nxtgauge_admin_access_token') || ''
        : '';
      let endpoint = '';
      if (type === 'JOB') {
        if (!targetId) {
          setError('Missing job id for final approval action.');
          return;
        }
        endpoint = `${API}/api/admin/approvals/jobs/${targetId}/${action}`;
      } else if (type === 'REQUIREMENT') {
        if (!targetId) {
          setError('Missing requirement id for final approval action.');
          return;
        }
        endpoint = `${API}/api/admin/approvals/requirements/${targetId}/${action}`;
      } else {
        if (!verificationId) {
          setError('Missing verification id for profile final approval action.');
          return;
        }
        endpoint = `${API}/api/admin/approvals/profiles/${verificationId}/${action}`;
      }
      const res = await fetch(endpoint, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          Accept: 'application/json',
          ...(accessToken ? { Authorization: `Bearer ${accessToken}` } : {}),
        },
        credentials: 'include',
        body: action === 'reject'
          ? JSON.stringify({ reason: decisionNote().trim() || 'Rejected by admin from approval management' })
          : JSON.stringify({}),
      });
      if (!res.ok) {
        const data = await res.json().catch(() => ({}));
        throw new Error((data as any).message || `Request failed (${res.status})`);
      }
      setLocalStatus(row, nextStatus);
      setViewingCase(null);
      setListTab('all');
      await load();
    } catch (e: any) {
      setError(e?.message || 'Approval action failed.');
    } finally {
      setIsActing(false);
    }
  };

  return (
      <div class="w-full space-y-6 pb-8">

        <div style="margin-bottom: 1.5rem">
          <h1 class="text-[28px] font-bold leading-tight text-[#111827]">Approval Management</h1>
          <p class="mt-1 text-[14px] text-[#6B7280]">Manage final approval decisions for all platform entities and requests</p>
        </div>
        <Show when={error()}>
          <div style="margin-bottom:10px;border-radius:10px;border:1px solid #FECACA;background:#FEF2F2;padding:12px 16px;font-size:13px;color:#B91C1C">
            {error()}
          </div>
        </Show>

        <Show when={true}>
          <div style="margin-top:24px;display:flex;align-items:center;gap:24px;min-height:44px;border-bottom:1px solid #E5E7EB">
            <For each={[
              { key: 'all', label: 'All Approvals', action: () => { setListTab('all'); setStatusFilter('all'); } },
              { key: 'escalated', label: `Escalated (${escalatedCount()})`, action: () => { setListTab('escalated'); setStatusFilter('escalated'); } },
              { key: 'view', label: 'View Approval', action: () => { setListTab('view'); } },
            ] as const}>{(tab) => (
              <button
                type="button"
                onClick={tab.action}
                style={`height:44px;padding:0 2px;font-size:14px;font-weight:500;background:none;border:none;cursor:pointer;${listTab() === tab.key ? 'color:#FF5E13;box-shadow:inset 0 -2px 0 #FF5E13' : 'color:#6B7280'}`}
              >
                {tab.label}
              </button>
            )}</For>
          </div>

          <Show when={listTab() === 'view'}>
            <Show when={!viewingCase()}>
              <div style="margin-top:24px;border-radius:16px;border:1px solid #E5E7EB;background:white;padding:48px 24px;text-align:center">
                <p style="font-size:15px;font-weight:600;color:#111827">No approval selected</p>
                <p style="margin-top:6px;font-size:13px;color:#6B7280">Click the <strong>⋮</strong> menu on any row and choose <strong>View Approval</strong>.</p>
              </div>
            </Show>
            <Show when={viewingCase()}>
              <div style="margin-top:24px;border-radius:16px;border:1px solid #E5E7EB;background:white;box-shadow:0 1px 4px rgba(0,0,0,0.06);overflow:hidden">
                <div style="padding:20px 24px;border-bottom:1px solid #E5E7EB;display:flex;align-items:center;justify-content:space-between">
                  <div>
                    <div style="display:flex;align-items:center;gap:12px">
                      <h2 style="font-size:18px;font-weight:700;color:#111827">{viewingCase()!.applicantName}</h2>
                      <StatusBadge status={viewingCase()!.status} />
                      <PriorityBadge priority={viewingCase()!.priority} />
                    </div>
                    <p style="margin-top:2px;font-size:13px;color:#6B7280">ID: {viewingCase()!.id} • {viewingCase()!.approvalType} • Submitted: {formatDate(viewingCase()!.submittedDate)}</p>
                  </div>
                  <div style="display:flex;gap:10px">
                    <button type="button" onClick={() => void runApprovalAction(viewingCase()!, 'approve')} disabled={isActing()} style={`height:36px;border-radius:8px;background:#0D0D2A;padding:0 16px;font-size:13px;font-weight:600;color:white;border:none;cursor:pointer;opacity:${isActing() ? 0.7 : 1}`}>Approve</button>
                    <button type="button" onClick={() => void runApprovalAction(viewingCase()!, 'reject')} disabled={isActing()} style={`height:36px;border-radius:8px;border:1px solid #E5E7EB;background:white;padding:0 16px;font-size:13px;font-weight:600;color:#374151;cursor:pointer;opacity:${isActing() ? 0.7 : 1}`}>Reject</button>
                  </div>
                </div>

                <div style="display:flex;align-items:center;gap:4px;min-height:44px;border-bottom:1px solid #E5E7EB;padding:0 24px;background:#FAFAFA">
                  <For each={['overview', 'verification', 'checklist', 'logs'] as const}>{(tab, getI) => {
                    const labels = ['Overview', 'Verification Summary', 'Approval Checklist', 'Activity Logs'];
                    const i = getI();
                    const active = () => detailTab() === tab;
                    return (
                      <button type="button" onClick={() => setDetailTab(tab)} style={`position:relative;padding:14px 12px;font-size:13px;font-weight:600;background:none;border:none;cursor:pointer;color:${active() ? '#FF5E13' : '#6B7280'}`}>
                        {labels[i]}
                        <Show when={active()}><span style="position:absolute;left:0;right:0;bottom:0;height:2px;background:#FF5E13;border-radius:2px 2px 0 0" /></Show>
                      </button>
                    );
                  }}</For>
                </div>

                <div style="padding:24px">
                  <Show when={detailTab() === 'overview'}>
                    <div style="display:grid;grid-template-columns:2fr 1fr;gap:24px">
                      <div style="display:flex;flex-direction:column;gap:24px">
                        <div style="border:1px solid #E5E7EB;border-radius:12px;padding:20px">
                          <h3 style="font-size:14px;font-weight:700;color:#111827;margin-bottom:16px">Approval Summary</h3>
                          <div style="display:grid;grid-template-columns:1fr 1fr;gap:16px">
                            <div><p style="font-size:11px;color:#9CA3AF">Entity Name</p><p style="font-size:14px;font-weight:600;color:#111827">{viewingCase()!.applicantName}</p></div>
                            <div><p style="font-size:11px;color:#9CA3AF">Approval Type</p><p style="font-size:14px;font-weight:600;color:#111827">{viewingCase()!.approvalType}</p></div>
                            <div><p style="font-size:11px;color:#9CA3AF">Primary Service</p><p style="font-size:14px;font-weight:600;color:#111827">{viewingCase()!.primaryService || '—'}</p></div>
                            <div><p style="font-size:11px;color:#9CA3AF">Area / Place</p><p style="font-size:14px;font-weight:600;color:#111827">{viewingCase()!.area || '—'}</p></div>
                            <div><p style="font-size:11px;color:#9CA3AF">Verification Status</p><VerificationBadge status={viewingCase()!.verificationStatus} /></div>
                            <div><p style="font-size:11px;color:#9CA3AF">Assigned Approver</p><p style="font-size:14px;font-weight:600;color:#111827">{viewingCase()!.assignedApprover}</p></div>
                          </div>
                          <Show when={viewingCase()!.roleTags?.length}>
                            <div style="margin-top:12px">
                              <p style="margin:0 0 8px;font-size:11px;color:#9CA3AF">Registered Roles / Services</p>
                              <div style="display:flex;flex-wrap:wrap;gap:6px">
                                <For each={viewingCase()!.roleTags || []}>
                                  {(tag) => (
                                    <span style="height:24px;padding:0 10px;border-radius:999px;border:1px solid #E5E7EB;background:#F9FAFB;display:inline-flex;align-items:center;font-size:11px;font-weight:600;color:#374151">{tag}</span>
                                  )}
                                </For>
                              </div>
                            </div>
                          </Show>
                        </div>

                        <Show when={selectedFields().length > 0}>
                          <div style="border:1px solid #E5E7EB;border-radius:12px;padding:20px">
                            <h3 style="font-size:14px;font-weight:700;color:#111827;margin-bottom:12px">Submitted Details</h3>
                            <div style="display:grid;grid-template-columns:1fr 1fr;gap:12px">
                              <For each={selectedFields()}>
                                {(field) => (
                                  <div style="border:1px solid #F3F4F6;border-radius:10px;padding:10px;background:#FAFAFA">
                                    <p style="font-size:11px;color:#9CA3AF">{field.label}</p>
                                    <p style="font-size:13px;font-weight:600;color:#111827;line-height:1.4;word-break:break-word">{field.value || '—'}</p>
                                  </div>
                                )}
                              </For>
                            </div>
                          </div>
                        </Show>
                      </div>

                      <div style="border:1px solid #E5E7EB;border-radius:12px;padding:20px;background:#F9FAFB">
                        <h3 style="font-size:14px;font-weight:700;color:#111827;margin-bottom:16px">Decision Notes</h3>
                        <textarea value={decisionNote()} onInput={(e) => setDecisionNote(e.currentTarget.value)} placeholder="Add decision note..." style="width:100%;height:100px;border-radius:8px;border:1px solid #E5E7EB;padding:10px;font-size:13px;resize:none;margin-bottom:12px" />
                        <p style="margin:0;font-size:12px;color:#6B7280">This note is included as the rejection reason when you reject below.</p>
                      </div>
                    </div>
                  </Show>

                  <Show when={detailTab() === 'verification'}>
                    <div style="border:1px solid #E5E7EB;border-radius:12px;padding:20px;background:#FAFAFA">
                      <h3 style="font-size:14px;font-weight:700;color:#111827;margin-bottom:16px">Submitted Documents</h3>
                      <Show when={selectedDocuments().length > 0} fallback={<p style="font-size:13px;color:#6B7280">No documents submitted for this request.</p>}>
                        <div style="display:flex;flex-direction:column;gap:8px">
                          <For each={selectedDocuments()}>
                            {(doc) => (
                              <div style="display:grid;grid-template-columns:1fr auto auto;gap:12px;align-items:center;padding:10px;border-radius:10px;border:1px solid #E5E7EB;background:white">
                                <div>
                                  <p style="font-size:13px;font-weight:600;color:#111827">{doc.title}</p>
                                  <p style="font-size:12px;color:#6B7280">{doc.type} • {doc.status}</p>
                                </div>
                                <a href={doc.url} target="_blank" rel="noreferrer" style="display:inline-flex;height:30px;align-items:center;justify-content:center;border-radius:8px;border:1px solid #E5E7EB;padding:0 12px;font-size:12px;font-weight:600;color:#374151;background:white;text-decoration:none">View</a>
                                <span style="font-size:12px;color:#6B7280">{doc.status}</span>
                              </div>
                            )}
                          </For>
                        </div>
                      </Show>
                    </div>
                  </Show>

                  <Show when={detailTab() === 'checklist'}>
                    <div style="display:flex;flex-direction:column;gap:12px">
                      <For each={[
                        'Verification report is complete and reviewed',
                        'All required entity data is present',
                        'No active risk flags on applicant',
                        'Applicant meets all policy requirements',
                        'Final approval readiness confirmed',
                      ]}>{(item) => (
                        <label style="display:flex;align-items:center;gap:12px;padding:12px;border:1px solid #E5E7EB;border-radius:10px;cursor:pointer">
                          <input type="checkbox" style="width:16px;height:16px;accent-color:#FF5E13" />
                          <span style="font-size:13px;color:#111827;font-weight:500">{item}</span>
                        </label>
                      )}</For>
                    </div>
                  </Show>

                  <Show when={detailTab() === 'logs'}>
                    <div style="display:flex;flex-direction:column;gap:16px">
                      <div style="display:flex;gap:12px">
                        <div style="width:8px;height:8px;border-radius:50%;background:#FF5E13;margin-top:4px" />
                        <div>
                          <p style="font-size:13px;font-weight:600;color:#111827">Approval Review Started</p>
                          <p style="font-size:12px;color:#6B7280">Approver started final review • 1 hour ago</p>
                        </div>
                      </div>
                      <div style="display:flex;gap:12px">
                        <div style="width:8px;height:8px;border-radius:50%;background:#E5E7EB;margin-top:4px" />
                        <div>
                          <p style="font-size:13px;font-weight:600;color:#111827">Verification Completed</p>
                          <p style="font-size:12px;color:#6B7280">Case handed over from verification team • 1 day ago</p>
                        </div>
                      </div>
                    </div>
                  </Show>
                </div>

                <div style="display:flex;align-items:center;gap:10px;padding:14px 24px;border-top:1px solid #E5E7EB">
                  <button type="button" onClick={() => { setViewingCase(null); setListTab('all'); }} style="height:36px;border-radius:8px;border:1px solid #E5E7EB;background:white;padding:0 16px;font-size:13px;font-weight:600;color:#374151;cursor:pointer">Back to List</button>
                </div>
              </div>
            </Show>
          </Show>

          <div style={`display:${listTab() === 'view' ? 'none' : 'block'}`}>
            <div style="margin-top:1.5rem;margin-left:-24px;margin-right:-24px;border-radius:0;border-left:none;border-right:none;overflow:hidden;border-top:1px solid #E5E7EB;border-bottom:1px solid #E5E7EB;background:white;box-shadow:0 1px 3px rgba(0,0,0,0.06)">
              <div style="display:flex;align-items:center;gap:8px;padding:14px 20px;border-bottom:1px solid #F3F4F6">
                <input
                  value={search()}
                  onInput={(e) => setSearch(e.currentTarget.value)}
                  placeholder="Search approvals..."
                  style="height:34px;flex:1;border-radius:8px;border:1px solid #E5E7EB;background:white;padding:0 12px;font-size:13px;color:#111827;outline:none"
                />
                <div style="position:relative">
                  <button
                    type="button"
                    onClick={() => { setSortMenuOpen((v) => !v); setFilterMenuOpen(false); }}
                    style="display:inline-flex;height:34px;align-items:center;gap:6px;border-radius:8px;border:1px solid #E5E7EB;background:white;padding:0 12px;font-size:12px;font-weight:500;color:#374151;cursor:pointer"
                  >
                    <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M7 4v13"/><path d="m3 13 4 4 4-4"/><path d="M17 20V7"/><path d="m21 11-4-4-4 4"/></svg>
                    Sort
                  </button>
                  <Show when={sortMenuOpen()}>
                    <div style="position:absolute;left:0;top:38px;z-index:30;min-width:220px;border-radius:12px;border:1px solid #E5E7EB;background:white;padding:6px;box-shadow:0 4px 16px rgba(0,0,0,0.1)">
                      <For each={['submitted_desc', 'submitted_asc', 'priority_desc', 'priority_asc'] as const}>{(s, getI) => {
                        const i = getI();
                        return (
                          <button type="button" onClick={() => { setSortBy(s); setSortMenuOpen(false); }} style={`display:block;width:100%;border-radius:8px;padding:8px 12px;text-align:left;font-size:13px;background:none;border:none;cursor:pointer;color:${sortBy() === s ? '#FF5E13' : '#374151'};background:${sortBy() === s ? '#FFF1EB' : 'transparent'}`}>
                            {['Submitted (Newest)', 'Submitted (Oldest)', 'Priority (High-Low)', 'Priority (Low-High)'][i]}
                          </button>
                        );
                      }}</For>
                    </div>
                  </Show>
                </div>
                <div style="position:relative">
                  <button
                    type="button"
                    onClick={() => { setFilterMenuOpen((v) => !v); setSortMenuOpen(false); }}
                    style="display:inline-flex;height:34px;align-items:center;gap:6px;border-radius:8px;border:1px solid #E5E7EB;background:white;padding:0 12px;font-size:12px;font-weight:500;color:#374151;cursor:pointer"
                  >
                    <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M3 5h18M6 12h12M10 19h4"/></svg>
                    Filters
                  </button>
                  <Show when={filterMenuOpen()}>
                    <div style="position:absolute;left:0;top:38px;z-index:30;min-width:200px;border-radius:12px;border:1px solid #E5E7EB;background:white;padding:6px;box-shadow:0 4px 16px rgba(0,0,0,0.1)">
                      <For each={['all', 'pending', 'escalated'] as const}>{(s) => (
                        <button type="button" onClick={() => { setStatusFilter(s); setFilterMenuOpen(false); }} style={`display:block;width:100%;border-radius:8px;padding:8px 12px;text-align:left;font-size:13px;background:none;border:none;cursor:pointer;color:${statusFilter() === s ? '#FF5E13' : '#374151'};background:${statusFilter() === s ? '#FFF1EB' : 'transparent'}`}>
                          {s === 'all' ? 'All Cases' : s === 'pending' ? 'Pending Decisions' : 'Escalated'}
                        </button>
                      )}</For>
                    </div>
                  </Show>
                </div>
                <button type="button" onClick={exportCsv} style="display:inline-flex;height:34px;align-items:center;gap:6px;border-radius:8px;background:#0D0D2A;padding:0 12px;font-size:12px;font-weight:600;color:white;border:none;cursor:pointer">
                  <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="7 10 12 15 17 10"/><line x1="12" y1="15" x2="12" y2="3"/></svg>
                  Export
                </button>
              </div>

              <div class="overflow-x-auto overflow-y-visible">
                <table class="min-w-full">
                  <thead>
                    <tr style="background:#0D0D2A;text-align:left">
                      <th style="padding:10px 20px;font-size:11px;font-weight:600;text-transform:uppercase;letter-spacing:0.05em;color:#FFFFFF;white-space:nowrap">Approval ID</th>
                      <th style="padding:10px 20px;font-size:11px;font-weight:600;text-transform:uppercase;letter-spacing:0.05em;color:#FFFFFF;white-space:nowrap">Applicant / Entity</th>
                      <th style="padding:10px 20px;font-size:11px;font-weight:600;text-transform:uppercase;letter-spacing:0.05em;color:#FFFFFF;white-space:nowrap">Type</th>
                      <th style="padding:10px 20px;font-size:11px;font-weight:600;text-transform:uppercase;letter-spacing:0.05em;color:#FFFFFF;white-space:nowrap">Verification</th>
                      <th style="padding:10px 20px;font-size:11px;font-weight:600;text-transform:uppercase;letter-spacing:0.05em;color:#FFFFFF;white-space:nowrap">Priority</th>
                      <th style="padding:10px 20px;font-size:11px;font-weight:600;text-transform:uppercase;letter-spacing:0.05em;color:#FFFFFF;white-space:nowrap">Status</th>
                      <th style="padding:10px 20px;font-size:11px;font-weight:600;text-transform:uppercase;letter-spacing:0.05em;color:#FFFFFF;white-space:nowrap">Submitted</th>
                      <th style="padding:10px 20px;font-size:11px;font-weight:600;text-transform:uppercase;letter-spacing:0.05em;color:#FFFFFF;white-space:nowrap">Actions</th>
                    </tr>
                  </thead>
                  <tbody>
                    <Show
                      when={filteredRows().length > 0}
                      fallback={
                        <tr>
                          <td colSpan={8} style="padding:32px;text-align:center">
                            <p style="font-size:15px;font-weight:600;color:#111827">No approvals found</p>
                            <p style="margin-top:6px;font-size:13px;color:#6B7280">Try changing filters or search.</p>
                          </td>
                        </tr>
                      }
                    >
                      <For each={filteredRows()}>
                        {(row) => (
                          <tr style="border-bottom:1px solid #F3F4F6" class="hover:bg-[#FAFAFA] transition-colors">
                            <td style="padding:12px 20px;font-size:12px;font-family:monospace;color:#6B7280">{row.id}</td>
                            <td style="padding:12px 20px">
                              <p style="font-size:14px;font-weight:600;color:#111827">{row.applicantName}</p>
                              <p style="font-size:11px;color:#6B7280">{row.userType}{row.area ? ` • ${row.area}` : ''}</p>
                              <Show when={row.roleTags?.length}>
                                <p style="margin-top:2px;font-size:11px;color:#9CA3AF">{(row.roleTags || []).join(', ')}</p>
                              </Show>
                            </td>
                            <td style="padding:12px 20px;font-size:13px;color:#6B7280">{row.approvalType}</td>
                            <td style="padding:12px 20px"><VerificationBadge status={row.verificationStatus} /></td>
                            <td style="padding:12px 20px"><PriorityBadge priority={row.priority} /></td>
                            <td style="padding:12px 20px"><StatusBadge status={row.status} /></td>
                            <td style="padding:12px 20px;font-size:13px;color:#6B7280">{formatDate(row.submittedDate || row.updatedAt)}</td>
                            <td style="padding:12px 20px;position:relative">
                              <button type="button" onClick={() => setOpenMenuId(openMenuId() === row.id ? null : row.id)} style="display:inline-flex;height:32px;width:32px;align-items:center;justify-content:center;border-radius:8px;color:#9CA3AF;background:none;border:none;cursor:pointer">
                                <svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor"><circle cx="12" cy="5" r="1.5"/><circle cx="12" cy="12" r="1.5"/><circle cx="12" cy="19" r="1.5"/></svg>
                              </button>
                              <Show when={openMenuId() === row.id}>
                                <div style="position:absolute;right:20px;top:44px;z-index:20;width:210px;border-radius:12px;border:1px solid #E5E7EB;background:white;padding:6px;box-shadow:0 4px 20px rgba(0,0,0,0.12)">
                                  <button type="button" onClick={() => openView(row)} style="display:flex;width:100%;align-items:center;gap:10px;border-radius:8px;padding:10px 12px;font-size:13px;color:#374151;background:none;border:none;cursor:pointer;text-align:left">
                                    <svg style="width:16px;height:16px;color:#FF5E13;flex-shrink:0" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/><circle cx="12" cy="12" r="3"/></svg>
                                    View Approval
                                  </button>
                                  <button type="button" onClick={() => void runApprovalAction(row, 'approve')} style="display:flex;width:100%;align-items:center;gap:10px;border-radius:8px;padding:10px 12px;font-size:13px;color:#374151;background:none;border:none;cursor:pointer;text-align:left">
                                    <svg style="width:16px;height:16px;color:#FF5E13;flex-shrink:0" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="10"/><path d="m8 12 2.5 2.5L16 9"/></svg>
                                    Approve
                                  </button>
                                  <button type="button" onClick={() => void runApprovalAction(row, 'reject')} style="display:flex;width:100%;align-items:center;gap:10px;border-radius:8px;padding:10px 12px;font-size:13px;color:#DC2626;background:none;border:none;cursor:pointer;text-align:left">
                                    <svg style="width:16px;height:16px;flex-shrink:0" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="10"/><path d="m15 9-6 6"/><path d="m9 9 6 6"/></svg>
                                    Reject
                                  </button>
                                </div>
                              </Show>
                            </td>
                          </tr>
                        )}
                      </For>
                    </Show>
                  </tbody>
                </table>
              </div>

              <Show when={filteredRows().length > 0}>
                <div style="display:flex;align-items:center;justify-content:space-between;border-top:1px solid #F3F4F6;padding:12px 20px">
                  <p style="font-size:13px;color:#6B7280">
                    Showing <strong style="font-weight:600;color:#111827">1–{filteredRows().length}</strong> of <strong style="font-weight:600;color:#111827">{filteredRows().length}</strong> approvals
                  </p>
                  <div style="display:flex;align-items:center;gap:4px">
                    <button type="button" style="display:inline-flex;width:30px;height:30px;align-items:center;justify-content:center;border-radius:7px;border:1px solid #E5E7EB;background:white;color:#6B7280;cursor:pointer;font-size:15px">‹</button>
                    <button type="button" style="display:inline-flex;width:30px;height:30px;align-items:center;justify-content:center;border-radius:7px;background:#FF5E13;color:white;font-size:13px;font-weight:600;border:none;cursor:pointer">1</button>
                    <button type="button" style="display:inline-flex;width:30px;height:30px;align-items:center;justify-content:center;border-radius:7px;border:1px solid #E5E7EB;background:white;color:#374151;font-size:13px;font-weight:500;cursor:pointer">2</button>
                    <button type="button" style="display:inline-flex;width:30px;height:30px;align-items:center;justify-content:center;border-radius:7px;border:1px solid #E5E7EB;background:white;color:#374151;font-size:13px;font-weight:500;cursor:pointer">3</button>
                    <button type="button" style="display:inline-flex;width:30px;height:30px;align-items:center;justify-content:center;border-radius:7px;border:1px solid #E5E7EB;background:white;color:#6B7280;cursor:pointer;font-size:15px">›</button>
                  </div>
                </div>
              </Show>
            </div>
          </div>
        </Show>

      </div>
  );
}
