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-amber-500 px-2.5 py-0.5 text-xs font-medium text-white">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="flex flex-col -mx-6 -mt-6 min-h-full">
        {/* White page header */}
        <div class="bg-white border-b border-gray-200 px-6 py-4">
          <div class="flex items-center justify-between">
            <div>
              <h1 class="text-xl font-semibold text-gray-900">Company Management</h1>
              <p class="text-sm text-gray-500 mt-0.5">Manage all company accounts on the platform.</p>
            </div>
            <A class="btn-primary" href="/admin/company/create">Create Company</A>
          </div>
        </div>

        {/* Content */}
        <div class="flex-1 p-6">
          <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="mb-4 flex flex-wrap items-center gap-3">
            <input
              type="text"
              placeholder="Search by name or email..."
              value={search()}
              onInput={(e) => setSearch(e.currentTarget.value)}
              class="rounded-lg border border-gray-200 px-3 py-2 text-sm outline-none focus:border-[#0a1d37] w-64"
            />
          </div>

          <div class="table-card">
            <div class="overflow-x-auto">
              <table class="data-table 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" class="text-center py-8 text-slate-500">Loading...</td></tr>
                  </Show>
                  <Show when={!companies.loading && companies.error}>
                    <tr><td colspan="6" class="text-center py-8 text-red-700">Failed to load. Is the backend running?</td></tr>
                  </Show>
                  <Show when={!companies.loading && !companies.error && filtered().length === 0}>
                    <tr><td colspan="6" class="text-center py-8 text-slate-400">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 class="hover:bg-slate-50">
                            <td class="font-semibold text-slate-900">{displayName}</td>
                            <td class="text-slate-500">{item.industry || '—'}</td>
                            <td class="text-slate-500">{item.city || '—'}</td>
                            <td class="text-slate-500">{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>
          </div>
        </div>
      </div>
    </AdminShell>
  );
}
