import { A, useNavigate } from '@solidjs/router';
import { createSignal, Show } from 'solid-js';

const API = '/api/gateway';

export default function CreateCompanyPage() {
  const navigate = useNavigate();
  const [saving, setSaving] = createSignal(false);
  const [error, setError] = createSignal('');
  const [form, setForm] = createSignal({
    companyName: '',
    companyId: '',
    address: '',
    email: '',
    phone: '',
    industry: 'TECHNOLOGY',
    description: '',
    websiteUrl: '',
  });

  const setField = (k: keyof ReturnType<typeof form>, v: string) => {
    setForm((prev) => ({ ...prev, [k]: v }));
  };

  const submit = async (e: Event) => {
    e.preventDefault();
    const f = form();
    if (!f.companyName.trim() || !f.companyId.trim() || !f.address.trim() || !f.email.trim() || !f.phone.trim()) {
      setError('Please fill all required fields.');
      return;
    }
    try {
      setSaving(true);
      setError('');
      const res = await fetch(`${API}/api/admin/companies`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(f),
      });
      if (!res.ok) {
        const payload = await res.json().catch(() => ({}));
        throw new Error(payload.message || 'Failed to create company');
      }
      navigate('/admin/company');
    } catch (err: any) {
      setError(err.message || 'Failed to create company');
    } finally {
      setSaving(false);
    }
  };

  const inputCls = 'w-full rounded-lg border border-gray-200 px-3 py-2 text-sm outline-none focus:border-[#0a1d37] focus:ring-1 focus:ring-[#0a1d37]';
  const labelCls = 'mb-1.5 block text-sm font-medium text-gray-700';

  return (
      <div class="flex flex-col -mx-6 -mt-6 min-h-full">

        {/* ── Page header ── */}
        <div class="bg-white border-b border-gray-200 px-6 py-4 flex items-center justify-between">
          <div>
            <h1 class="text-xl font-semibold text-gray-900">Create Company</h1>
            <p class="text-sm text-gray-500 mt-0.5">Add a new organization profile to the admin company catalog.</p>
          </div>
          <A class="rounded-lg border border-gray-200 px-4 py-2 text-sm font-medium text-gray-700 hover:bg-gray-50 transition-colors" href="/admin/company">
            Back to Companies
          </A>
        </div>

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

          <form class="rounded-xl border border-gray-200 bg-white shadow-sm p-6" onSubmit={submit}>
            <div class="grid grid-cols-1 gap-5 sm:grid-cols-2">
              <div>
                <label class={labelCls}>Company Name *</label>
                <input class={inputCls} value={form().companyName} onInput={(e) => setField('companyName', e.currentTarget.value)} />
              </div>
              <div>
                <label class={labelCls}>Company ID *</label>
                <input class={inputCls} value={form().companyId} onInput={(e) => setField('companyId', e.currentTarget.value)} />
              </div>
              <div>
                <label class={labelCls}>Industry</label>
                <input class={inputCls} value={form().industry} onInput={(e) => setField('industry', e.currentTarget.value)} />
              </div>
              <div>
                <label class={labelCls}>Website</label>
                <input class={inputCls} value={form().websiteUrl} onInput={(e) => setField('websiteUrl', e.currentTarget.value)} />
              </div>
              <div>
                <label class={labelCls}>Email *</label>
                <input type="email" class={inputCls} value={form().email} onInput={(e) => setField('email', e.currentTarget.value)} />
              </div>
              <div>
                <label class={labelCls}>Phone *</label>
                <input class={inputCls} value={form().phone} onInput={(e) => setField('phone', e.currentTarget.value)} />
              </div>
              <div class="sm:col-span-2">
                <label class={labelCls}>Address *</label>
                <input class={inputCls} value={form().address} onInput={(e) => setField('address', e.currentTarget.value)} />
              </div>
              <div class="sm:col-span-2">
                <label class={labelCls}>Description</label>
                <textarea rows={3} class={inputCls} value={form().description} onInput={(e) => setField('description', e.currentTarget.value)} />
              </div>
            </div>
            <div class="mt-6 flex justify-end gap-3 border-t border-gray-100 pt-5">
              <A class="rounded-lg border border-gray-200 px-4 py-2 text-sm font-medium text-gray-700 hover:bg-gray-50 transition-colors" href="/admin/company">Cancel</A>
              <button class="btn-primary" type="submit" disabled={saving()}>
                {saving() ? 'Creating…' : 'Create Company'}
              </button>
            </div>
          </form>
        </div>
      </div>
  );
}
