import { A, useParams } from '@solidjs/router';
import { createMemo, createResource, Show } from 'solid-js';

const API = '';

type CompanyCore = {
  id: string;
  company_name?: string;
  companyName?: string;
  company_id?: string;
  companyId?: string;
  industry?: string;
  email?: string;
  phone?: string;
  website_url?: string;
  websiteUrl?: string;
  city?: string;
  state?: string;
  address?: string;
  description?: string;
  status?: string;
  is_verified?: boolean;
  isVerified?: boolean;
  pan?: string;
  gst?: string;
  tan?: string;
  strength?: number;
  gstVerified?: boolean;
  mcaVerified?: boolean;
  createdAt?: string;
  updatedAt?: string;
  updatedBy?: string;
};

type CompanyContact = {
  city?: string;
  state?: string;
  pinCode?: string;
  linkedin?: string;
  instagram?: string;
  twitter?: string;
};

type CompanyBanking = {
  bankName?: string;
  accountNumber?: string;
  ifscCode?: string;
  branchName?: string;
  accountHolderName?: string;
  isVerified?: boolean;
};

type CompanyBundle = {
  company: CompanyCore;
  contact: CompanyContact | null;
  banking: CompanyBanking | null;
};

async function fetchCompanyBundle(id: string): Promise<CompanyBundle | null> {
  try {
    const res = await fetch(`${API}/api/admin/companies/${id}`);
    if (!res.ok) return null;
    const data = await res.json();

    if (data.company) {
      return {
        company: data.company,
        contact: data.contact || null,
        banking: data.banking || null,
      };
    }

    return {
      company: data,
      contact: null,
      banking: null,
    };
  } catch {
    return null;
  }
}

export default function CompanyDetailPage() {
  const params = useParams();
  const [bundle] = createResource(() => params.id, fetchCompanyBundle);

  const company = createMemo(() => bundle()?.company || null);
  const contact = createMemo(() => bundle()?.contact || null);
  const banking = createMemo(() => bundle()?.banking || null);

  const name = createMemo(() => company()?.company_name || company()?.companyName || 'Company');
  const companyId = createMemo(() => company()?.company_id || company()?.companyId || company()?.id || '—');
  const website = createMemo(() => company()?.website_url || company()?.websiteUrl || '');
  const isVerified = createMemo(() => Boolean(company()?.is_verified ?? company()?.isVerified));

  return (
      <div class="flex flex-col -mx-6 -mt-6 min-h-full">
      <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">{name()}</h1>
          <p class="text-sm text-gray-500 mt-0.5">{companyId()}</p>
        </div>
        <div class="flex items-center gap-2">
          <span class={`inline-flex rounded-full px-2.5 py-0.5 text-xs font-medium ${isVerified() ? 'bg-green-100 text-green-800' : 'bg-yellow-100 text-yellow-800'}`}>
            {isVerified() ? 'Verified - Can Post Jobs' : 'Not Verified'}
          </span>
          <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>
          <A class="btn-primary" href="/admin/approval">Open Approval Management</A>
        </div>
      </div>
      <div class="p-6 flex-1">

      <Show when={bundle.loading}>
        <div class="rounded-xl border border-gray-200 bg-white shadow-sm"><p class="notice">Loading company...</p></div>
      </Show>
      <Show when={!bundle.loading && !company()}>
        <div class="rounded-xl border border-gray-200 bg-white shadow-sm"><p class="notice">Company not found.</p></div>
      </Show>

      <Show when={company()}>
        <>
          <div class="mt-4 grid grid-cols-1 gap-4 sm:grid-cols-2" style="margin-bottom:16px">
            <div class="rounded-xl border border-gray-200 bg-white shadow-sm">
              <p class="kv-label">Email</p>
              <p class="kv-value">{company()!.email || '—'}</p>
            </div>
            <div class="rounded-xl border border-gray-200 bg-white shadow-sm">
              <p class="kv-label">Phone</p>
              <p class="kv-value">{company()!.phone || '—'}</p>
            </div>
            <div class="rounded-xl border border-gray-200 bg-white shadow-sm" style="grid-column:1 / -1">
              <p class="kv-label">Website</p>
              <p class="kv-value">
                <Show when={website()} fallback={'—'}>
                  <a href={website()} target="_blank" rel="noreferrer">{website()}</a>
                </Show>
              </p>
            </div>
          </div>

          <div class="detail-layout">
            <div style="display:flex;flex-direction:column;gap:16px">
              <section class="rounded-xl border border-gray-200 bg-white shadow-sm">
                <h2 style="margin-bottom:8px">Company Information</h2>
                <div class="mt-4 grid grid-cols-1 gap-4 sm:grid-cols-2">
                  <div class="kv-item">
                    <p class="kv-label">Company Name</p>
                    <p class="kv-value">{name()}</p>
                  </div>
                  <div class="kv-item">
                    <p class="kv-label">Company ID</p>
                    <p class="kv-value">{companyId()}</p>
                  </div>
                  <div class="kv-item">
                    <p class="kv-label">Industry</p>
                    <p class="kv-value">{company()!.industry || '—'}</p>
                  </div>
                  <div class="kv-item">
                    <p class="kv-label">Company Size</p>
                    <p class="kv-value">{company()!.strength ? `${company()!.strength} employees` : '—'}</p>
                  </div>
                  <div class="kv-item">
                    <p class="kv-label">PAN</p>
                    <p class="kv-value">{company()!.pan || '—'}</p>
                  </div>
                  <div class="kv-item">
                    <p class="kv-label">GST</p>
                    <p class="kv-value">{company()!.gst || '—'}</p>
                  </div>
                  <div class="kv-item">
                    <p class="kv-label">TAN</p>
                    <p class="kv-value">{company()!.tan || '—'}</p>
                  </div>
                  <div class="kv-item">
                    <p class="kv-label">Status</p>
                    <p class="kv-value">{company()!.status || 'UNKNOWN'}</p>
                  </div>
                  <div class="kv-item" style="grid-column:1 / -1">
                    <p class="kv-label">Address</p>
                    <p class="kv-value">{company()!.address || '—'}</p>
                  </div>
                  <div class="kv-item" style="grid-column:1 / -1">
                    <p class="kv-label">Description</p>
                    <p class="kv-value">{company()!.description || '—'}</p>
                  </div>
                </div>
              </section>

              <section class="rounded-xl border border-gray-200 bg-white shadow-sm">
                <h2 style="margin-bottom:8px">Contact Details</h2>
                <div class="mt-4 grid grid-cols-1 gap-4 sm:grid-cols-2">
                  <div class="kv-item">
                    <p class="kv-label">City</p>
                    <p class="kv-value">{contact()?.city || company()!.city || '—'}</p>
                  </div>
                  <div class="kv-item">
                    <p class="kv-label">State</p>
                    <p class="kv-value">{contact()?.state || company()!.state || '—'}</p>
                  </div>
                  <div class="kv-item">
                    <p class="kv-label">PIN Code</p>
                    <p class="kv-value">{contact()?.pinCode || '—'}</p>
                  </div>
                  <div class="kv-item">
                    <p class="kv-label">LinkedIn</p>
                    <p class="kv-value">{contact()?.linkedin || '—'}</p>
                  </div>
                  <div class="kv-item">
                    <p class="kv-label">Instagram</p>
                    <p class="kv-value">{contact()?.instagram || '—'}</p>
                  </div>
                  <div class="kv-item">
                    <p class="kv-label">Twitter</p>
                    <p class="kv-value">{contact()?.twitter || '—'}</p>
                  </div>
                </div>
              </section>

              <section class="rounded-xl border border-gray-200 bg-white shadow-sm">
                <h2 style="margin-bottom:8px">Banking Details</h2>
                <div class="mt-4 grid grid-cols-1 gap-4 sm:grid-cols-2">
                  <div class="kv-item">
                    <p class="kv-label">Account Holder</p>
                    <p class="kv-value">{banking()?.accountHolderName || '—'}</p>
                  </div>
                  <div class="kv-item">
                    <p class="kv-label">Account Number</p>
                    <p class="kv-value">{banking()?.accountNumber || '—'}</p>
                  </div>
                  <div class="kv-item">
                    <p class="kv-label">Bank Name</p>
                    <p class="kv-value">{banking()?.bankName || '—'}</p>
                  </div>
                  <div class="kv-item">
                    <p class="kv-label">Branch</p>
                    <p class="kv-value">{banking()?.branchName || '—'}</p>
                  </div>
                  <div class="kv-item">
                    <p class="kv-label">IFSC Code</p>
                    <p class="kv-value">{banking()?.ifscCode || '—'}</p>
                  </div>
                  <div class="kv-item">
                    <p class="kv-label">Banking Verification</p>
                    <p class="kv-value">{banking()?.isVerified ? 'Verified' : 'Not Verified'}</p>
                  </div>
                </div>
              </section>
            </div>

            <div style="display:flex;flex-direction:column;gap:16px">
              <section class="rounded-xl border border-gray-200 bg-white shadow-sm">
                <h2 style="margin-bottom:8px">Verification Status</h2>
                <div class={`sub-card ${isVerified() ? 'sub-card-success' : 'sub-card-warning'}`} style="margin-top:0">
                  <p class="kv-label">Overall Status</p>
                  <p class="kv-value" style="font-size:18px">{isVerified() ? 'Company Verified' : 'Pending Verification'}</p>
                  <p class="notice" style="margin:8px 0 0">
                    {isVerified() ? 'This company can post job listings.' : 'Company cannot post jobs until verified.'}
                  </p>
                </div>
                <div class="sub-card">
                  <div class="kv-item">
                    <p class="kv-label">GST Verification</p>
                    <p class="kv-value">{company()!.gstVerified ? 'Verified' : 'Not Verified'}</p>
                  </div>
                  <div class="kv-item">
                    <p class="kv-label">MCA Verification</p>
                    <p class="kv-value">{company()!.mcaVerified ? 'Verified' : 'Not Verified'}</p>
                  </div>
                  <div class="kv-item">
                    <p class="kv-label">Banking Verification</p>
                    <p class="kv-value">{banking()?.isVerified ? 'Verified' : 'Not Verified'}</p>
                  </div>
                </div>
              </section>

              <section class="rounded-xl border border-gray-200 bg-white shadow-sm">
                <h2 style="margin-bottom:8px">Metadata</h2>
                <div class="kv-item">
                  <p class="kv-label">Created At</p>
                  <p class="kv-value">{company()!.createdAt ? new Date(company()!.createdAt!).toLocaleString() : '—'}</p>
                </div>
                <div class="kv-item">
                  <p class="kv-label">Last Updated</p>
                  <p class="kv-value">{company()!.updatedAt ? new Date(company()!.updatedAt!).toLocaleString() : '—'}</p>
                </div>
                <Show when={company()!.updatedBy}>
                  <div class="kv-item">
                    <p class="kv-label">Updated By</p>
                    <p class="kv-value">{company()!.updatedBy}</p>
                  </div>
                </Show>
              </section>
            </div>
          </div>
        </>
      </Show>
      </div>
      </div>
  );
}
