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

const API = '/api/gateway';

interface Company {
  id: string;
  company_name?: string;
  companyName?: string;
  name?: string;
  industry?: string;
  city?: string;
  email?: string;
  status: 'ACTIVE' | 'INACTIVE' | 'PENDING' | 'SUSPENDED' | 'REJECTED';
  created_at?: string;
  createdAt?: string;
}

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

function StatusBadge(props: { status: string }) {
  if (props.status === 'ACTIVE') {
    return <span class="status-chip active">ACTIVE</span>;
  }
  if (props.status === 'PENDING') {
    return <span class="status-chip" style="background:#f59e0b;color:#fff">PENDING</span>;
  }
  return <span class="status-chip">{props.status}</span>;
}

export default function CompanyPage() {
  const [companies, { refetch }] = createResource(fetchCompanies);
  const [search, setSearch] = createSignal('');
  const [deleting, setDeleting] = createSignal('');
  const [actionError, setActionError] = createSignal('');

  const filtered = createMemo(() => {
    const list = companies() ?? [];
    const q = search().toLowerCase();
    if (!q) return list;
    return list.filter((c) => {
      const name = (c.company_name || c.companyName || c.name || '').toLowerCase();
      const email = (c.email || '').toLowerCase();
      return name.includes(q) || email.includes(q);
    });
  });

  const handleDelete = async (id: string, name: string) => {
    if (!confirm(`Delete ${name}?`)) return;
    try {
      setDeleting(id);
      setActionError('');
      const res = await fetch(`${API}/api/admin/companies/${id}`, { method: 'DELETE' });
      if (!res.ok) throw new Error('Failed to delete');
      refetch();
    } catch (err: any) {
      setActionError(err.message || 'Failed to delete company');
    } finally {
      setDeleting('');
    }
  };

  return (
    <AdminShell>
      <div class="page-actions">
        <div>
          <h1 class="page-title">Company Management</h1>
          <p class="page-subtitle">Manage all company accounts on the platform.</p>
        </div>
        <A class="btn navy" href="/admin/company/create">Create Company</A>
      </div>

      <Show when={actionError()}>
        <div class="error-box">{actionError()}</div>
      </Show>

      {/* Search */}
      <div class="card" style="margin-bottom:16px;display:flex;gap:12px;flex-wrap:wrap;align-items:center;">
        <input
          type="text"
          placeholder="Search by name or email..."
          value={search()}
          onInput={(e) => setSearch(e.currentTarget.value)}
          style="border:1px solid #cbd5e1;border-radius:6px;padding:7px 12px;font-size:14px;width:260px;outline:none;"
        />
      </div>

      <section class="card" style="padding: 0; overflow: hidden;">
        <div class="table-wrap">
          <table class="list-table">
            <thead>
              <tr>
                <th>Company Name</th>
                <th>Industry</th>
                <th>City</th>
                <th>Email</th>
                <th>Status</th>
                <th class="align-right">Actions</th>
              </tr>
            </thead>
            <tbody>
              <Show when={companies.loading}>
                <tr><td colspan="6" style="text-align:center;padding:32px;color:#64748b">Loading...</td></tr>
              </Show>
              <Show when={!companies.loading && companies.error}>
                <tr><td colspan="6" style="text-align:center;padding:32px;color:#b91c1c">Failed to load. Is the backend running?</td></tr>
              </Show>
              <Show when={!companies.loading && !companies.error && filtered().length === 0}>
                <tr><td colspan="6" style="text-align:center;padding:32px;color:#94a3b8">No companies found.</td></tr>
              </Show>
              <Show when={!companies.loading && !companies.error && filtered().length > 0}>
                <For each={filtered()}>
                  {(item) => {
                    const displayName = item.company_name || item.companyName || item.name || '—';
                    return (
                      <tr>
                        <td style="font-weight:600;color:#0f172a">{displayName}</td>
                        <td style="color:#475569">{item.industry || '—'}</td>
                        <td style="color:#475569">{item.city || '—'}</td>
                        <td style="color:#475569">{item.email || '—'}</td>
                        <td>
                          <StatusBadge status={item.status} />
                        </td>
                        <td>
                          <div class="table-actions">
                            <A class="btn" href={`/admin/company/${item.id}`}>View</A>
                            <button
                              class="btn danger"
                              disabled={deleting() === item.id}
                              onClick={() => handleDelete(item.id, displayName)}
                            >
                              {deleting() === item.id ? '...' : 'Delete'}
                            </button>
                          </div>
                        </td>
                      </tr>
                    );
                  }}
                </For>
              </Show>
            </tbody>
          </table>
        </div>
      </section>
    </AdminShell>
  );
}
