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="inline-flex items-center rounded-full bg-green-100 px-2.5 py-0.5 text-xs font-medium text-green-700">ACTIVE</span>;
  }
  if (props.status === 'PENDING') {
    return <span class="inline-flex items-center rounded-full bg-gray-100 px-2.5 py-0.5 text-xs font-medium text-gray-600" style="background:#f59e0b;color:#fff">PENDING</span>;
  }
  return <span class="inline-flex items-center rounded-full bg-gray-100 px-2.5 py-0.5 text-xs font-medium text-gray-600">{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="mb-6 flex items-start justify-between gap-4">
        <div>
          <h1 class="text-2xl font-bold text-gray-900">Company Management</h1>
          <p class="mt-1 text-sm text-gray-500">Manage all company accounts on the platform.</p>
        </div>
        <A class="inline-flex items-center rounded-lg bg-[#fd6216] px-4 py-2 text-sm font-semibold text-white hover:bg-orange-600 transition-colors" href="/admin/company/create">Create Company</A>
      </div>

      <Show when={actionError()}>
        <div class="mb-4 rounded-lg border border-red-200 bg-red-50 px-4 py-3 text-sm text-red-700">{actionError()}</div>
      </Show>

      {/* Search */}
      <div class="rounded-xl border border-gray-200 bg-white shadow-sm" 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="rounded-xl border border-gray-200 bg-white shadow-sm" style="padding: 0; overflow: hidden;">
        <div class="overflow-x-auto">
          <table class="w-full text-sm">
            <thead>
              <tr>
                <th>Company Name</th>
                <th>Industry</th>
                <th>City</th>
                <th>Email</th>
                <th>Status</th>
                <th class="text-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="flex items-center justify-end gap-1">
                            <A class="inline-flex items-center rounded-lg border border-gray-200 bg-white px-4 py-2 text-sm font-medium text-gray-700 hover:bg-gray-50 transition-colors" href={`/admin/company/${item.id}`}>View</A>
                            <button
                              class="inline-flex items-center rounded-lg border border-red-200 bg-red-50 px-4 py-2 text-sm font-medium text-red-600 hover:bg-red-100 transition-colors"
                              disabled={deleting() === item.id}
                              onClick={() => handleDelete(item.id, displayName)}
                            >
                              {deleting() === item.id ? '...' : 'Delete'}
                            </button>
                          </div>
                        </td>
                      </tr>
                    );
                  }}
                </For>
              </Show>
            </tbody>
          </table>
        </div>
      </section>
    </AdminShell>
  );
}
