'use client';

import clsx from 'clsx';

type Metrics = {
  total_planned?: number;
  total_delivered?: number;
  total_remaining?: number;
};

const formatNumber = (value?: number) => {
  if (value === undefined || value === null || Number.isNaN(value)) return '—';
  return Number(value).toLocaleString();
};

export function ExecutiveHero({ metrics, insight }: { metrics?: Metrics & { plan_period_label?: string } | null, insight?: string }) {
  const completionRate = metrics?.total_planned
    ? Math.min(100, (Number(metrics?.total_delivered ?? 0) / Number(metrics?.total_planned)) * 100)
    : 0;
  const remainingRate = Math.max(0, 100 - completionRate);

  return (
    <section className="relative overflow-hidden rounded-3xl bg-gradient-to-r from-brand to-emerald-900 p-8 text-white shadow-xl">
      {/* Background 3D Image Overlay */}
      <div className="absolute right-0 top-0 h-full w-1/2 opacity-20 mix-blend-overlay">
        <img
          src="/assets/admin_dashboard_hero_3d.png"
          alt="Supply Chain Visualization"
          className="h-full w-full object-cover"
        />
      </div>

      <div className="relative z-10 flex flex-col gap-6 md:flex-row md:items-center md:justify-between">
        <div>
          <p className="text-sm uppercase tracking-[0.25em] text-emerald-200">Executive Control Center</p>
          <h1 className="mt-3 text-3xl font-bold leading-tight md:text-4xl">Supply Intelligence at a Glance</h1>
          <p className="mt-4 max-w-2xl text-base text-emerald-50">
            Live telemetry blends plan fulfillment, delivery momentum, and smart alerts so you can steer large-scale operations
            with absolute confidence.
          </p>
          <div className="mt-6 flex flex-wrap gap-6 text-sm">
            <div>
              <p className="text-emerald-200">Completion</p>
              <p className="text-2xl font-semibold">{completionRate.toFixed(1)}%</p>
            </div>
            <div>
              <p className="text-emerald-200">Remaining runway</p>
              <p className="text-2xl font-semibold">{remainingRate.toFixed(1)}%</p>
            </div>
            <div>
              <p className="text-emerald-200">Active plan period</p>
              <p className="text-2xl font-semibold">{metrics?.plan_period_label || 'Loading...'}</p>
            </div>
          </div>
        </div>
        <div className="relative w-full max-w-md rounded-2xl bg-white/10 p-6 backdrop-blur">
          <p className="text-xs uppercase tracking-[0.3em] text-emerald-100">Mission Console</p>
          <div className="mt-4 grid grid-cols-2 gap-4 text-sm text-emerald-100">
            {[
              { label: 'Planned', value: formatNumber(metrics?.total_planned) },
              { label: 'Delivered', value: formatNumber(metrics?.total_delivered) },
              { label: 'Remaining', value: formatNumber(metrics?.total_remaining) },
              { label: 'Confidence', value: completionRate > 85 ? 'Very High' : completionRate > 60 ? 'Stable' : 'Watch' },
            ].map((item) => (
              <div key={item.label} className="rounded-xl border border-white/10 bg-white/5 p-3">
                <p className="text-[0.7rem] uppercase tracking-wide text-emerald-200">{item.label}</p>
                <p className="mt-1 text-xl font-semibold text-white">{item.value}</p>
              </div>
            ))}
          </div>
          <div className="mt-6 rounded-xl bg-white/10 p-4 text-xs text-emerald-100">
            <p className="font-semibold text-white">Predictive insight</p>
            <p className="mt-2">
              {insight || 'Gathering data for prediction...'}
            </p>
          </div>
        </div>
      </div>
    </section>
  );
}

export function IntelligenceStack({ tracks }: { tracks?: any[] }) {
  const defaultTracks = [
    {
      title: 'Fulfillment Guardrails',
      detail: 'Auto-detects variance beyond ±7% and flags the specific school + commodity pairings for review.',
      tag: 'Real-time',
    },
    {
      title: 'Delivery Momentum',
      detail: 'Highlights the three fastest improving districts plus the one that needs executive attention.',
      tag: 'Velocity',
    },
    {
      title: 'Supplier Reliability',
      detail: 'Scores every supplier using the last five deliveries and bubbles up the highest confidence source.',
      tag: 'Quality',
    },
  ];

  const displayTracks = tracks && tracks.length > 0 ? tracks.map(t => ({
    title: t.name,
    detail: t.signal,
    tag: t.severity === 'high' ? 'Critical' : t.severity === 'medium' ? 'Warning' : 'Stable'
  })).slice(0, 3) : defaultTracks;

  return (
    <section className="mt-10 grid gap-5 md:grid-cols-3">
      {displayTracks.map((track, i) => (
        <div key={i} className="rounded-2xl border border-slate-100 bg-white p-6 shadow-md">
          <p className="text-xs font-semibold uppercase tracking-[0.4em] text-brand">{track.tag}</p>
          <h3 className="mt-3 text-xl font-semibold text-slate-900">{track.title}</h3>
          <p className="mt-2 text-sm text-slate-500">{track.detail}</p>
          <button className="mt-4 text-sm font-semibold text-brand">View diagnostics →</button>
        </div>
      ))}
    </section>
  );
}

export function DeliveryMomentumPanel({ momentum }: { momentum?: any }) {
  const burnRate = momentum?.burnRate ?? 0;
  const efficiencyScore = momentum?.efficiencyScore ?? 0;
  const trendline = momentum?.trendline ?? [0, 0, 0, 0, 0, 0, 0, 0, 0, 0];

  return (
    <section className="relative mt-10 overflow-hidden rounded-3xl border border-slate-100 bg-white p-8 shadow-lg">
      {/* Background 3D Image Overlay */}
      <div className="absolute right-0 top-0 h-full w-1/3 opacity-10">
        <img
          src="/assets/admin_momentum_3d.png"
          alt="Momentum Visualization"
          className="h-full w-full object-cover"
        />
      </div>

      <div className="relative z-10 flex flex-col gap-6 md:flex-row md:items-center md:justify-between">
        <div>
          <p className="text-xs uppercase tracking-[0.4em] text-slate-500">Momentum Intelligence</p>
          <h2 className="mt-3 text-2xl font-bold text-slate-900">Delivery runway & acceleration</h2>
          <p className="mt-3 text-sm text-slate-500">
            We continuously benchmark throughput against plan to project the exact week each commodity will be fully served.
          </p>
          <div className="mt-6 grid gap-4 md:grid-cols-3">
            {[
              { label: 'Weekly Burn', value: `${(burnRate * 100).toFixed(1)}%` },
              { label: 'Efficiency Score', value: efficiencyScore },
              { label: 'Trend Status', value: burnRate > 0.5 ? 'Accelerating' : 'Steady' },
            ].map((item) => (
              <div key={item.label} className="rounded-2xl bg-slate-50 p-4">
                <p className="text-xs uppercase tracking-wide text-slate-500">{item.label}</p>
                <p className="mt-2 text-2xl font-semibold text-slate-900">{item.value}</p>
              </div>
            ))}
          </div>
        </div>
        <div className="w-full md:max-w-md">
          <div className="rounded-3xl border border-slate-100 bg-slate-50 p-6">
            <p className="text-xs font-semibold uppercase tracking-[0.4em] text-slate-500">Trendline</p>
            <svg viewBox="0 0 200 80" className="mt-6 h-32 w-full text-brand">
              <polyline
                fill="none"
                stroke="currentColor"
                strokeWidth="4"
                strokeLinecap="round"
                points={trendline
                  .map((value: number, index: number) => {
                    const x = (index / (trendline.length - 1)) * 200;
                    const y = 80 - (value / 100) * 80;
                    return `${x},${y}`;
                  })
                  .join(' ')}
              />
            </svg>
            <p className="mt-4 text-xs text-slate-500">
              Each node represents average fulfillment for the rolling 7-day window. Slope shifts trigger proactive alerts.
            </p>
          </div>
        </div>
      </div>
    </section>
  );
}

export function RiskAndConfidenceMatrix({ risks }: { risks?: any[] }) {
  const displayRisks = risks ?? [];
  return (
    <section className="mt-10 rounded-3xl border border-slate-100 bg-white p-8 shadow-lg">
      <div className="flex items-center justify-between">
        <div>
          <p className="text-xs uppercase tracking-[0.4em] text-slate-500">Risk Radar</p>
          <h2 className="mt-3 text-2xl font-bold text-slate-900">Confidence & exception management</h2>
        </div>
        <button className="rounded-full bg-brand/10 px-4 py-2 text-sm font-semibold text-brand">Download briefing</button>
      </div>
      <div className="mt-6 divide-y divide-slate-100">
        {displayRisks.length === 0 ? (
          <p className="py-4 text-sm text-slate-500">No active risks detected.</p>
        ) : (
          displayRisks.map((risk, i) => (
            <div key={i} className="flex flex-wrap items-center justify-between gap-4 py-4">
              <div>
                <p className="text-sm font-semibold text-slate-900">{risk.name}</p>
                <p className="text-xs text-slate-500">{risk.signal}</p>
              </div>
              <span
                className={clsx(
                  'rounded-full px-3 py-1 text-xs font-semibold',
                  risk.severity === 'high' && 'bg-rose-50 text-rose-600',
                  risk.severity === 'medium' && 'bg-amber-50 text-amber-600',
                  risk.severity === 'low' && 'bg-emerald-50 text-emerald-600'
                )}
              >
                {risk.status}
              </span>
            </div>
          ))
        )}
      </div>
    </section>
  );
}

export function StrategicActionGrid({ actions }: { actions?: any[] }) {
  const displayActions = actions ?? [];
  return (
    <section className="mt-10 grid gap-4 md:grid-cols-3">
      {displayActions.map((action, i) => (
        <div key={i} className="rounded-2xl border border-slate-100 bg-white p-5 shadow">
          <p className="text-[0.65rem] uppercase tracking-[0.4em] text-slate-400">Next Best Action</p>
          <h3 className="mt-2 text-lg font-semibold text-slate-900">{action.title}</h3>
          <p className="mt-2 text-sm text-slate-500">{action.description}</p>
          <p className="mt-4 text-xs font-semibold text-brand">{action.owner}</p>
        </div>
      ))}
    </section>
  );
}

export function ExecutiveNarratives({ narratives }: { narratives?: any[] }) {
  const displayNarratives = narratives ?? [];
  return (
    <section className="mt-10 rounded-3xl border border-slate-100 bg-white p-8 shadow-lg">
      <div className="grid gap-6 md:grid-cols-3">
        {displayNarratives.map((narrative, i) => (
          <div key={i}>
            <p className="text-xs uppercase tracking-[0.4em] text-slate-400">Briefing</p>
            <h3 className="mt-2 text-xl font-semibold text-slate-900">{narrative.title}</h3>
            <p className="mt-3 text-sm text-slate-500">{narrative.copy}</p>
          </div>
        ))}
      </div>
    </section>
  );
}
