import Link from 'next/link'
import { notFound } from 'next/navigation'
import { ShopBillingForm } from '@/components/shop-billing-form'
import { StatusBadge } from '@/components/status-badge'
import { requireAdminPage } from '@/lib/admin-auth'
import { getShopDetail } from '@/lib/admin-data'
import { compact, formatCurrencyFcfa, formatDateTime } from '@/lib/utils'

export const dynamic = 'force-dynamic'

type Props = {
  params: Promise<{ shopId: string }>
}

export default async function ShopDetailPage({ params }: Props) {
  await requireAdminPage()
  const { shopId } = await params
  const detail = await getShopDetail(shopId)

  if (!detail.shop) {
    notFound()
  }

  return (
    <div className="container-stack">
      <div className="topbar">
        <div>
          <h1>{detail.shop.shop_name}</h1>
          <p>Détail boutique, billing, membres et dernières demandes.</p>
        </div>
        <div className="actions">
          <Link href="/dashboard/settings" className="btn-ghost">Configuration globale</Link>
          <Link href="/dashboard/shops" className="btn-secondary">Retour</Link>
        </div>
      </div>

      <section className="detail-grid">
        <article className="card container-stack">
          <h2>Résumé boutique</h2>
          <div className="kv">
            <div>Shop ID</div><div>{detail.shop.shop_id}</div>
            <div>Téléphone</div><div>{compact(detail.shop.shop_phone)}</div>
            <div>Plan</div><div><StatusBadge value={detail.shop.plan || 'unknown'} /></div>
            <div>Actif</div><div><StatusBadge value={detail.shop.is_active ? 'active' : 'inactive'} /></div>
            <div>Expiration</div><div>{formatDateTime(detail.shop.expires_at)}</div>
            <div>Entitlement MAJ</div><div>{formatDateTime(detail.shop.entitlement_updated_at)}</div>
          </div>
        </article>

        <article className="card container-stack">
          <h2>Entitlement effectif</h2>
          {detail.effectiveEntitlement ? (
            <div className="kv">
              <div>Actif effectif</div><div><StatusBadge value={detail.effectiveEntitlement.is_effective_active ? 'active' : 'expired'} /></div>
              <div>Days left</div><div>{detail.effectiveEntitlement.days_left ?? '—'}</div>
              <div>Max clients</div><div>{detail.effectiveEntitlement.max_customers}</div>
              <div>Max dettes</div><div>{detail.effectiveEntitlement.max_debts}</div>
              <div>Expiration</div><div>{formatDateTime(detail.effectiveEntitlement.expires_at)}</div>
            </div>
          ) : (
            <div className="muted">Aucun entitlement trouvé.</div>
          )}
        </article>
      </section>

      <section className="detail-grid">
        <article className="card container-stack">
          <h2>Billing settings</h2>
          {detail.billingSettings ? (
            <div className="kv">
              <div>Prix</div><div>{formatCurrencyFcfa(detail.billingSettings.price_fcfa)}</div>
              <div>Wave</div><div>{compact(detail.billingSettings.wave_number)}</div>
              <div>Orange Money</div><div>{compact(detail.billingSettings.orange_money_number)}</div>
              <div>Support phone</div><div>{compact(detail.billingSettings.support_phone)}</div>
              <div>Support WhatsApp</div><div>{compact(detail.billingSettings.support_whatsapp)}</div>
              <div>MAJ</div><div>{formatDateTime(detail.billingSettings.updated_at)}</div>
            </div>
          ) : (
            <div className="muted">Aucun paramétrage billing trouvé.</div>
          )}

          <div className="notice">
            Tu peux surcharger ici le prix et les numéros de cette boutique uniquement, sans toucher à la configuration globale SenKredi.
          </div>

          <ShopBillingForm shopId={shopId} initial={detail.billingSettings} />
        </article>

        <article className="card container-stack">
          <h2>Membres</h2>
          <div className="table-wrap">
            <table className="table">
              <thead>
                <tr>
                  <th>Utilisateur</th>
                  <th>Rôle</th>
                  <th>Téléphone</th>
                  <th>Ajouté le</th>
                </tr>
              </thead>
              <tbody>
                {detail.memberships.map((member) => (
                  <tr key={member.user_id}>
                    <td>
                      <strong>{member.profile?.full_name || member.user_id}</strong>
                      <span className="muted">{member.user_id}</span>
                    </td>
                    <td><StatusBadge value={member.role} /></td>
                    <td>{compact(member.profile?.phone)}</td>
                    <td>{formatDateTime(member.created_at)}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </article>
      </section>

      <section className="card container-stack">
        <h2>Dernières demandes</h2>
        <div className="table-wrap">
          <table className="table">
            <thead>
              <tr>
                <th>ID</th>
                <th>Demandeur</th>
                <th>Montant</th>
                <th>Méthode</th>
                <th>Statut</th>
                <th>Créée le</th>
                <th>Décision</th>
              </tr>
            </thead>
            <tbody>
              {detail.recentRequests.map((row) => (
                <tr key={row.id}>
                  <td>#{row.id}</td>
                  <td>
                    <strong>{row.requesterProfile?.full_name || row.user_id}</strong>
                    <span className="muted">{compact(row.requesterProfile?.phone || row.payer_phone)}</span>
                  </td>
                  <td>{formatCurrencyFcfa(row.amount_fcfa)}</td>
                  <td>{row.method}</td>
                  <td><StatusBadge value={row.status} /></td>
                  <td>{formatDateTime(row.created_at)}</td>
                  <td>
                    {row.decided_at ? (
                      <>
                        <strong>{formatDateTime(row.decided_at)}</strong>
                        <span className="muted">{row.decidedByProfile?.full_name || row.decided_by || '—'}</span>
                      </>
                    ) : '—'}
                  </td>
                </tr>
              ))}
              {detail.recentRequests.length === 0 ? (
                <tr>
                  <td colSpan={7} className="muted">Aucune demande pour cette boutique.</td>
                </tr>
              ) : null}
            </tbody>
          </table>
        </div>
      </section>
    </div>
  )
}
