import { Link } from 'react-router-dom';

import { useCentralBank } from './useCentralBank';

import ChainMatrixPanel from './ChainMatrixPanel';

import FineractLedgerBanner from '../omnl-dashboard/FineractLedgerBanner';

import DashboardStatCard from '../omnl-dashboard/DashboardStatCard';

import DashboardSection from '../omnl-dashboard/DashboardSection';

import QuickPortalLinks from '../omnl-dashboard/QuickPortalLinks';

import NasaPageHeader from '../omnl-dashboard/NasaPageHeader';

import NasaIcon from '../../components/icons/NasaIcon';

import { formatUsd } from '../../utils/formatMoney';



export default function CentralBankDashboard() {

  const cb = useCentralBank();

  const office = cb.office as {

    officeId?: number;

    name?: string;

    externalId?: string;

    settlement?: { moneyLayers?: string[]; glM0?: string; glM1?: string; glM2?: string };

  } | null;



  return (

    <div className="dash-page cb-page max-w-[1400px] mx-auto px-4 py-6">

      <NasaPageHeader

        icon="central-bank"

        missionId="CB-138"

        title="Central Bank Operations"

        subtitle={`Live money supply for ${office?.name ?? 'HOSPITALLERS — Zardasht (Iraq / Iran Operations)'} (Office ${office?.officeId ?? 24}) · settlement · SWIFT · HYBX · Chain 138`}

        badges={

          <>

            <span className="nasa-badge nasa-badge--telemetry">OMNL Central Bank</span>

            <span className="nasa-badge nasa-badge--nominal">Production</span>

            <span className="nasa-badge nasa-badge--caution">128 chains</span>

          </>

        }

      />



      <QuickPortalLinks />



      {cb.error && (

        <div className="dash-banner dash-banner--error mb-6">

          <NasaIcon name="x" size={18} className="nasa-icon--critical shrink-0 mt-0.5" />

          <div>

            <p className="dash-banner__title">Failed to load dashboard</p>

            <p className="dash-banner__detail">{cb.error}</p>

          </div>

        </div>

      )}



      <FineractLedgerBanner

        moneySupply={cb.moneySupply}

        loading={cb.loading}

        officeName={office?.name}

      />



      <h2 className="dash-section-title mb-1 flex items-center gap-2">

        <NasaIcon name="money" size={14} className="nasa-icon--telemetry" />

        Money supply

      </h2>

      <p className="dash-section-subtitle mb-4">Meta-fiat layers from Fineract general ledger · USD</p>



      <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4 mb-8">

        <DashboardStatCard label="M0 reserve" value={formatUsd(cb.moneySupply?.M0?.gl1050)} hint={`GL 1050 · ${cb.moneySupply?.M0?.backingRatio ?? 1.2}× backing policy`} accent="blue" icon="ledger" />

        <DashboardStatCard label="M1 circulating" value={formatUsd(cb.moneySupply?.M1?.circulating)} hint="GL 2100 · narrow money / eMoney" accent="green" icon="money" />

        <DashboardStatCard label="M2 broad money" value={formatUsd(cb.moneySupply?.M2?.broadMoney)} hint="GL 2200 · token-load source" accent="gold" icon="rocket" />

        <DashboardStatCard label="Due from head office" value={formatUsd(cb.moneySupply?.interoffice?.dueFromHeadOffice)} hint="GL 1410 · inter-office receivable" accent="blue" icon="rail" />

      </div>



      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">

        <DashboardSection

          title="Settlement service"

          subtitle="Middleware health and refresh"

          icon="satellite"

          action={

            <button type="button" className="dash-btn !w-auto px-4 flex items-center gap-1" onClick={() => cb.refresh()} disabled={cb.loading}>

              <NasaIcon name="refresh" size={12} className={cb.loading ? 'nasa-icon--spin' : ''} />

              {cb.loading ? 'Refreshing…' : 'Refresh'}

            </button>

          }

        >

          <dl>

            <div className="dash-kv">

              <dt>Status</dt>

              <dd className="dash-kv-value--ok">{(cb.health as { status?: string })?.status ?? '—'}</dd>

            </div>

            <div className="dash-kv">

              <dt>Office</dt>

              <dd>{office?.officeId ?? 24} · {office?.externalId ?? 'HOSPITALLERS-ZARDASHT-IRAQ-IRAN'}</dd>

            </div>

            <div className="dash-kv">

              <dt>M2 tokens registered</dt>

              <dd>{cb.tokenCount}</dd>

            </div>

            <div className="dash-kv">

              <dt>Active chains</dt>

              <dd>

                {(cb.health as { chainSupport?: { active?: number; total?: number } })?.chainSupport?.active ?? '—'}

                {' / '}

                {(cb.health as { chainSupport?: { active?: number; total?: number } })?.chainSupport?.total ?? 128}

              </dd>

            </div>

          </dl>

        </DashboardSection>



        <DashboardSection title="General ledger map" subtitle={`Money layers · Office ${office?.officeId ?? 24}`} icon="ledger">

          <div className="flex flex-wrap gap-2 mb-4">

            {(office?.settlement?.moneyLayers ?? ['M0', 'M1', 'M2']).map((layer) => (

              <span key={layer} className="nasa-badge nasa-badge--caution">{layer}</span>

            ))}

          </div>

          <dl>

            <div className="dash-kv"><dt>M0 reserve</dt><dd>GL {office?.settlement?.glM0 ?? '1050'}</dd></div>

            <div className="dash-kv"><dt>M1 liability</dt><dd>GL {office?.settlement?.glM1 ?? '2100'}</dd></div>

            <div className="dash-kv"><dt>M2 broad</dt><dd>GL {office?.settlement?.glM2 ?? '2200'}</dd></div>

            <div className="dash-kv"><dt>Inter-office (HO)</dt><dd>GL 1410</dd></div>

          </dl>

          <p className="dash-section-subtitle mt-4 flex flex-wrap gap-3">

            <Link to="/office-24" className="text-[#00d4ff] hover:underline inline-flex items-center gap-1">

              <NasaIcon name="office" size={12} /> Office 24 dashboard

            </Link>

            <Link to="/trade" className="text-[#00d4ff] hover:underline inline-flex items-center gap-1">

              <NasaIcon name="trade" size={12} /> DBIS Trade

            </Link>

          </p>

        </DashboardSection>



        <DashboardSection title="Recent exchange activity" subtitle="Last 8 swaps on DBIS Exchange" icon="chart" className="lg:col-span-2">

          <ul className="space-y-0 text-sm">

            {((cb.monitor as { swaps?: { status: string; tokenIn: string; createdAt: string }[] })?.swaps ?? [])

              .slice(0, 8)

              .map((s, i) => (

                <li key={i} className="flex justify-between gap-3 py-2.5 border-b border-[rgba(30,74,138,0.35)] last:border-0 text-sm font-mono">

                  <span className="text-[#7a9bb8] shrink-0">{s.status}</span>

                  <span className="text-[#e8f4ff] text-xs truncate">{s.tokenIn?.slice(0, 12)}…</span>

                  <span className="text-[#7a9bb8] text-xs shrink-0">{s.createdAt?.slice(0, 16)}</span>

                </li>

              ))}

            {!((cb.monitor as { swaps?: unknown[] })?.swaps?.length) && (

              <li className="text-[#7a9bb8] py-3">No swaps recorded yet</li>

            )}

          </ul>

        </DashboardSection>



        <ChainMatrixPanel />

      </div>

    </div>

  );

}

