import { createMemo, createResource, createSignal, For, Show } from 'solid-js';
import AdminShell from '~/components/AdminShell';

const API = '/api/gateway';

interface Approval {
  id: string;
  requestType?: string;
  type?: string;
  requestStatus?: string;
  status?: string;
  priority?: number;
  createdAt?: string;
  created_at?: string;
  requester?: { name?: string; email?: string };
  requesterName?: string;
  requesterEmail?: string;
  requester_name?: string;
  requester_email?: string;
}

interface ApprovalRule {
  id: string;
  entityType: string;
  entity_type?: string;
  approverType: string;
  approver_type?: string;
  priority?: number;
}

const ENTITY_TYPE_OPTIONS = ['JOB_POST', 'COMPANY', 'LEAD', 'INVOICE'];
const APPROVER_TYPE_OPTIONS = ['USER', 'ROLE'];
const REQUEST_FILTERS = ['ALL', 'PROFILE', 'JOB', 'REQUIREMENT'];

type StatusTab = 'PENDING' | 'APPROVED' | 'REJECTED' | 'CHANGES_REQUESTED' | 'CANCELLED' | 'rules';
type PanelTab = 'list' | 'view';

const STATUS_TABS: { key: StatusTab; label: string }[] = [
  { key: 'PENDING', label: 'Pending' },
  { key: 'APPROVED', label: 'Approved' },
  { key: 'REJECTED', label: 'Rejected' },
  { key: 'CHANGES_REQUESTED', label: 'Changes Requested' },
  { key: 'CANCELLED', label: 'Cancelled' },
  { key: 'rules', label: 'Rules' },
];

async function fetchApprovals(): Promise<Approval[]> {
  try {
    const res = await fetch(`${API}/api/admin/approvals`);
    if (!res.ok) throw new Error('Failed to load approvals');
    const data = await res.json();
    return Array.isArray(data) ? data : (data.approvals || []);
  } catch {
    return [];
  }
}

async function fetchRules(): Promise<ApprovalRule[]> {
  try {
    const res = await fetch(`${API}/api/admin/approval-rules`);
    if (!res.ok) throw new Error('Failed to load rules');
    const data = await res.json();
    return Array.isArray(data) ? data : (data.rules || []);
  } catch {
    return [];
  }
}

function statusValue(item: Approval) {
  return (item.requestStatus || item.status || 'PENDING').toUpperCase();
}

function requestTypeValue(item: Approval) {
  return (item.requestType || item.type || 'OTHER').toUpperCase();
}

function requestClass(item: Approval): 'PROFILE' | 'JOB' | 'REQUIREMENT' | 'OTHER' {
  const t = requestTypeValue(item);
  if (t.includes('JOB')) return 'JOB';
  if (t.includes('LEAD') || t.includes('REQUIREMENT')) return 'REQUIREMENT';
  if (t.includes('PROFILE') || t.includes('USER') || t.includes('COMPANY') || t.includes('PROFESSIONAL') || t.includes('CUSTOMER')) return 'PROFILE';
  return 'OTHER';
}

function StatusBadge(props: { status: string }) {
  const s = props.status.toUpperCase();
  if (s === 'APPROVED') return <span class="status-chip active">APPROVED</span>;
  if (s === 'REJECTED') return <span class="status-chip" style="background:#ef4444;color:#fff;border-color:#ef4444">REJECTED</span>;
  if (s === 'CHANGES_REQUESTED') return <span class="status-chip" style="background:#3b82f6;color:#fff;border-color:#3b82f6">CHANGES REQUESTED</span>;
  if (s === 'CANCELLED') return <span class="status-chip" style="background:#94a3b8;color:#fff;border-color:#94a3b8">CANCELLED</span>;
  return <span class="status-chip" style="background:#f59e0b;color:#fff;border-color:#f59e0b">{s}</span>;
}

export default function ApprovalPage() {
  const [activeTab, setActiveTab] = createSignal<StatusTab>('PENDING');
  const [panelTab, setPanelTab] = createSignal<PanelTab>('list');
  const [selectedApproval, setSelectedApproval] = createSignal<Approval | null>(null);

  const [search, setSearch] = createSignal('');
  const [requestFilter, setRequestFilter] = createSignal('ALL');
  const [currentPage, setCurrentPage] = createSignal(1);
  const perPage = 10;

  const [approvals, { refetch: refetchApprovals }] = createResource(fetchApprovals);
  const [acting, setActing] = createSignal('');
  const [approvalError, setApprovalError] = createSignal('');

  const [rules, { refetch: refetchRules }] = createResource(fetchRules);
  const [showAddRule, setShowAddRule] = createSignal(false);
  const [newEntityType, setNewEntityType] = createSignal('JOB_POST');
  const [newApproverType, setNewApproverType] = createSignal('USER');
  const [newPriority, setNewPriority] = createSignal(1);
  const [ruleError, setRuleError] = createSignal('');
  const [deletingRule, setDeletingRule] = createSignal('');
  const [submittingRule, setSubmittingRule] = createSignal(false);

  const filteredApprovals = createMemo(() => {
    const tab = activeTab();
    const q = search().trim().toLowerCase();
    const rf = requestFilter();
    const list = approvals() ?? [];

    if (tab === 'rules') return [] as Approval[];

    return list.filter((a) => {
      const matchesStatus = statusValue(a) === tab;
      if (!matchesStatus) return false;

      const cls = requestClass(a);
      const matchesType = rf === 'ALL' || cls === rf;
      if (!matchesType) return false;

      if (!q) return true;

      const requesterName = (a.requester?.name || a.requesterName || a.requester_name || '').toLowerCase();
      const requesterEmail = (a.requester?.email || a.requesterEmail || a.requester_email || '').toLowerCase();
      const requestType = requestTypeValue(a).toLowerCase();

      return requesterName.includes(q) || requesterEmail.includes(q) || requestType.includes(q) || a.id.toLowerCase().includes(q);
    });
  });

  const totalPages = createMemo(() => Math.max(1, Math.ceil(filteredApprovals().length / perPage)));

  const paginatedApprovals = createMemo(() => {
    const start = (currentPage() - 1) * perPage;
    return filteredApprovals().slice(start, start + perPage);
  });

  const countFor = (status: string) => {
    const list = approvals() ?? [];
    if (status === 'rules') return (rules() ?? []).length;
    return list.filter((a) => statusValue(a) === status).length;
  };

  const selectApproval = (approval: Approval) => {
    setSelectedApproval(approval);
    setPanelTab('view');
  };

  const handleAction = async (id: string, newStatus: 'APPROVED' | 'REJECTED' | 'CHANGES_REQUESTED' | 'CANCELLED') => {
    try {
      setActing(`${id}-${newStatus}`);
      setApprovalError('');
      const res = await fetch(`${API}/api/admin/approvals/${id}`, {
        method: 'PATCH',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ status: newStatus }),
      });
      if (!res.ok) throw new Error(`Failed to ${newStatus.toLowerCase()} approval`);
      refetchApprovals();

      if (selectedApproval()?.id === id) {
        setSelectedApproval((prev) => (prev ? { ...prev, status: newStatus, requestStatus: newStatus } : prev));
      }
    } catch (err: any) {
      setApprovalError(err.message || 'Action failed');
    } finally {
      setActing('');
    }
  };

  const handleAddRule = async () => {
    try {
      setSubmittingRule(true);
      setRuleError('');
      const res = await fetch(`${API}/api/admin/approval-rules`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          entityType: newEntityType(),
          approverType: newApproverType(),
          priority: newPriority(),
        }),
      });
      if (!res.ok) throw new Error('Failed to create rule');
      setShowAddRule(false);
      setNewEntityType('JOB_POST');
      setNewApproverType('USER');
      setNewPriority(1);
      refetchRules();
    } catch (err: any) {
      setRuleError(err.message || 'Failed to create rule');
    } finally {
      setSubmittingRule(false);
    }
  };

  const handleDeleteRule = async (id: string) => {
    if (!confirm('Delete this approval rule?')) return;
    try {
      setDeletingRule(id);
      setRuleError('');
      const res = await fetch(`${API}/api/admin/approval-rules/${id}`, { method: 'DELETE' });
      if (!res.ok) throw new Error('Failed to delete rule');
      refetchRules();
    } catch (err: any) {
      setRuleError(err.message || 'Failed to delete rule');
    } finally {
      setDeletingRule('');
    }
  };

  return (
    <AdminShell>
      <div class="page-actions">
        <div>
          <h1 class="page-title">Approval Management</h1>
          <p class="page-subtitle">Review and manage approvals and approval rules.</p>
        </div>
      </div>

      <div style="display:flex;border-bottom:2px solid #e2e8f0;margin-bottom:16px;gap:0;overflow-x:auto;">
        {STATUS_TABS.map((t) => {
          const count = countFor(t.key);
          return (
            <button
              type="button"
              class={`admin-tab${activeTab() === t.key ? ' active' : ''}`}
              onClick={() => {
                setActiveTab(t.key);
                setPanelTab('list');
                setCurrentPage(1);
              }}
              style="white-space:nowrap;display:flex;align-items:center;gap:6px"
            >
              {t.label}
              {!approvals.loading && count > 0 && (
                <span style={`display:inline-flex;align-items:center;justify-content:center;min-width:18px;height:18px;border-radius:999px;font-size:10px;font-weight:700;padding:0 5px;background:${activeTab() === t.key ? 'var(--brand-orange)' : '#e2e8f0'};color:${activeTab() === t.key ? '#fff' : '#64748b'}`}>
                  {count}
                </span>
              )}
            </button>
          );
        })}
      </div>

      <Show when={activeTab() !== 'rules'}>
        <div class="admin-segmented" style="margin-top:0; margin-bottom:12px;">
          <button class={`admin-segment ${panelTab() === 'list' ? 'active' : ''}`} type="button" onClick={() => setPanelTab('list')}>
            Approval List
          </button>
          <button class={`admin-segment ${panelTab() === 'view' ? 'active' : ''}`} type="button" disabled={!selectedApproval()} onClick={() => setPanelTab('view')}>
            Approval Detail
          </button>
        </div>

        <Show when={approvalError()}>
          <div class="error-box" style="margin-bottom:12px">{approvalError()}</div>
        </Show>

        <Show when={panelTab() === 'list'}>
          <div class="card" style="margin-bottom:12px;display:flex;gap:10px;flex-wrap:wrap;align-items:center;">
            <input
              type="text"
              placeholder="Search by requester, email, type, or ID..."
              value={search()}
              onInput={(e) => {
                setSearch(e.currentTarget.value);
                setCurrentPage(1);
              }}
              style="border:1px solid #cbd5e1;border-radius:6px;padding:7px 12px;font-size:14px;width:300px;outline:none;"
            />
            <select
              value={requestFilter()}
              onChange={(e) => {
                setRequestFilter(e.currentTarget.value);
                setCurrentPage(1);
              }}
              style="border:1px solid #cbd5e1;border-radius:6px;padding:7px 12px;font-size:14px;background:#fff;outline:none;"
            >
              <For each={REQUEST_FILTERS}>{(r) => <option value={r}>{r}</option>}</For>
            </select>
            <span style="font-size:12px;color:#64748b;margin-left:auto;">{filteredApprovals().length} records</span>
          </div>

          <section class="card" style="padding: 0; overflow: hidden;">
            <div class="table-wrap">
              <table class="list-table">
                <thead>
                  <tr>
                    <th>Approval ID</th>
                    <th>Requester</th>
                    <th>Request Type</th>
                    <th>Status</th>
                    <th>Priority</th>
                    <th>Submitted At</th>
                    <th class="align-right">Actions</th>
                  </tr>
                </thead>
                <tbody>
                  <Show when={approvals.loading}>
                    <tr><td colspan="7" style="text-align:center;padding:32px;color:#64748b">Loading...</td></tr>
                  </Show>
                  <Show when={!approvals.loading && approvals.error}>
                    <tr><td colspan="7" style="text-align:center;padding:32px;color:#b91c1c">Failed to load approvals.</td></tr>
                  </Show>
                  <Show when={!approvals.loading && !approvals.error && paginatedApprovals().length === 0}>
                    <tr><td colspan="7" style="text-align:center;padding:32px;color:#94a3b8">No matching approvals.</td></tr>
                  </Show>
                  <Show when={!approvals.loading && !approvals.error && paginatedApprovals().length > 0}>
                    <For each={paginatedApprovals()}>
                      {(item) => {
                        const requesterName = item.requester?.name || item.requesterName || item.requester_name || '—';
                        const requesterEmail = item.requester?.email || item.requesterEmail || item.requester_email || '';
                        const status = statusValue(item);
                        const requestType = requestTypeValue(item);
                        const submittedAt = item.createdAt || item.created_at;
                        return (
                          <tr>
                            <td style="font-family:ui-monospace,SFMono-Regular,Menlo,monospace;color:#64748b">{item.id.slice(0, 8)}...</td>
                            <td>
                              <div style="font-weight:600;color:#0f172a">{requesterName}</div>
                              <Show when={requesterEmail}>
                                <div style="font-size:12px;color:#64748b">{requesterEmail}</div>
                              </Show>
                            </td>
                            <td style="color:#475569">{requestType}</td>
                            <td><StatusBadge status={status} /></td>
                            <td style="color:#475569">{item.priority ?? '—'}</td>
                            <td style="color:#475569">{submittedAt ? new Date(submittedAt).toLocaleString() : '—'}</td>
                            <td>
                              <div class="table-actions">
                                <button class="action-icon-btn" type="button" onClick={() => selectApproval(item)} title="View Detail">👁</button>
                                <Show when={status !== 'APPROVED'}>
                                  <button class="action-icon-btn" type="button" disabled={!!acting()} onClick={() => handleAction(item.id, 'APPROVED')} title="Approve">✓</button>
                                </Show>
                                <Show when={status === 'PENDING'}>
                                  <button class="action-icon-btn" type="button" disabled={!!acting()} onClick={() => handleAction(item.id, 'CHANGES_REQUESTED')} title="Request Changes">↺</button>
                                </Show>
                                <Show when={status !== 'REJECTED' && status !== 'CANCELLED'}>
                                  <button class="action-icon-btn danger" type="button" disabled={!!acting()} onClick={() => handleAction(item.id, 'REJECTED')} title="Reject">✕</button>
                                </Show>
                              </div>
                            </td>
                          </tr>
                        );
                      }}
                    </For>
                  </Show>
                </tbody>
              </table>
            </div>
            <div class="admin-pagination">
              <button class="btn" type="button" disabled={currentPage() <= 1} onClick={() => setCurrentPage((p) => Math.max(1, p - 1))}>Previous</button>
              <span>Page {currentPage()} of {totalPages()}</span>
              <button class="btn" type="button" disabled={currentPage() >= totalPages()} onClick={() => setCurrentPage((p) => Math.min(totalPages(), p + 1))}>Next</button>
            </div>
          </section>
        </Show>

        <Show when={panelTab() === 'view'}>
          <section class="card">
            <Show when={selectedApproval()} fallback={<p class="notice">Select an approval from list to view details.</p>}>
              <div class="list-header">
                <h2>Approval Details</h2>
                <button class="btn" type="button" onClick={() => setPanelTab('list')}>Back To List</button>
              </div>
              <div class="grid" style="margin-top:0;">
                <div class="list-item">
                  <h3>Request Summary</h3>
                  <p><strong>Approval ID:</strong> {selectedApproval()!.id}</p>
                  <p><strong>Type:</strong> {requestTypeValue(selectedApproval()!)}</p>
                  <p><strong>Status:</strong> {statusValue(selectedApproval()!)}</p>
                  <p><strong>Priority:</strong> {selectedApproval()!.priority ?? '—'}</p>
                  <p><strong>Submitted:</strong> {(selectedApproval()!.createdAt || selectedApproval()!.created_at) ? new Date((selectedApproval()!.createdAt || selectedApproval()!.created_at)!).toLocaleString() : '—'}</p>
                </div>
                <div class="list-item">
                  <h3>Requester</h3>
                  <p><strong>Name:</strong> {selectedApproval()!.requester?.name || selectedApproval()!.requesterName || selectedApproval()!.requester_name || '—'}</p>
                  <p><strong>Email:</strong> {selectedApproval()!.requester?.email || selectedApproval()!.requesterEmail || selectedApproval()!.requester_email || '—'}</p>
                  <p><strong>Class:</strong> {requestClass(selectedApproval()!)}</p>
                  <div class="actions">
                    <button class="btn navy" type="button" disabled={!!acting()} onClick={() => handleAction(selectedApproval()!.id, 'APPROVED')}>Approve</button>
                    <button class="btn" type="button" disabled={!!acting()} onClick={() => handleAction(selectedApproval()!.id, 'CHANGES_REQUESTED')}>Request Changes</button>
                    <button class="btn danger" type="button" disabled={!!acting()} onClick={() => handleAction(selectedApproval()!.id, 'REJECTED')}>Reject</button>
                  </div>
                </div>
              </div>
            </Show>
          </section>
        </Show>
      </Show>

      <Show when={activeTab() === 'rules'}>
        <Show when={ruleError()}>
          <div class="error-box" style="margin-bottom:12px">{ruleError()}</div>
        </Show>

        <div class="page-actions" style="margin-bottom:16px;">
          <div />
          <button class="btn navy" onClick={() => setShowAddRule((v) => !v)}>
            {showAddRule() ? 'Cancel' : '+ Add Rule'}
          </button>
        </div>

        <Show when={showAddRule()}>
          <div class="card" style="margin-bottom:16px;">
            <h3 style="font-size:15px;font-weight:600;color:#0f172a;margin:0 0 14px 0;">New Approval Rule</h3>
            <div class="field-grid-2">
              <div class="field">
                <label>Entity Type</label>
                <select value={newEntityType()} onChange={(e) => setNewEntityType(e.currentTarget.value)}>
                  <For each={ENTITY_TYPE_OPTIONS}>{(et) => <option value={et}>{et}</option>}</For>
                </select>
              </div>
              <div class="field">
                <label>Approver Type</label>
                <select value={newApproverType()} onChange={(e) => setNewApproverType(e.currentTarget.value)}>
                  <For each={APPROVER_TYPE_OPTIONS}>{(at) => <option value={at}>{at}</option>}</For>
                </select>
              </div>
              <div class="field">
                <label>Priority</label>
                <input type="number" min="1" value={newPriority()} onInput={(e) => setNewPriority(parseInt(e.currentTarget.value, 10) || 1)} />
              </div>
            </div>
            <div class="actions" style="margin-top:14px;">
              <button class="btn navy" disabled={submittingRule()} onClick={handleAddRule}>
                {submittingRule() ? 'Saving...' : 'Save Rule'}
              </button>
              <button class="btn" onClick={() => setShowAddRule(false)}>Cancel</button>
            </div>
          </div>
        </Show>

        <section class="card" style="padding: 0; overflow: hidden;">
          <div class="table-wrap">
            <table class="list-table">
              <thead>
                <tr>
                  <th>Entity Type</th>
                  <th>Approver Type</th>
                  <th>Priority</th>
                  <th class="align-right">Actions</th>
                </tr>
              </thead>
              <tbody>
                <Show when={rules.loading}>
                  <tr><td colspan="4" style="text-align:center;padding:32px;color:#64748b">Loading...</td></tr>
                </Show>
                <Show when={!rules.loading && rules.error}>
                  <tr><td colspan="4" style="text-align:center;padding:32px;color:#b91c1c">Failed to load rules.</td></tr>
                </Show>
                <Show when={!rules.loading && !rules.error && (rules()?.length ?? 0) === 0}>
                  <tr><td colspan="4" style="text-align:center;padding:32px;color:#94a3b8">No approval rules found.</td></tr>
                </Show>
                <Show when={!rules.loading && !rules.error && (rules()?.length ?? 0) > 0}>
                  <For each={rules()!}>
                    {(rule) => (
                      <tr>
                        <td style="font-weight:600;color:#0f172a">{rule.entityType || rule.entity_type || '—'}</td>
                        <td style="color:#475569">{rule.approverType || rule.approver_type || '—'}</td>
                        <td style="color:#475569">{rule.priority ?? '—'}</td>
                        <td>
                          <div class="table-actions">
                            <button class="btn danger" disabled={deletingRule() === rule.id} onClick={() => handleDeleteRule(rule.id)}>
                              {deletingRule() === rule.id ? '...' : 'Delete'}
                            </button>
                          </div>
                        </td>
                      </tr>
                    )}
                  </For>
                </Show>
              </tbody>
            </table>
          </div>
        </section>
      </Show>
    </AdminShell>
  );
}
