const { useEffect, useRef } = React;

function FundingOutlookChart({ funding }) {
  const canvasRef = useRef(null);
  const chartRef = useRef(null);

  useEffect(() => {
    if (!funding || !window.Chart) return undefined;
    const ctx = canvasRef.current?.getContext("2d");
    if (!ctx) return undefined;

    const buildChart = window.ConstructProChartPlugins?.buildFundingStackedBarChart;
    chartRef.current?.destroy();
    chartRef.current = buildChart
      ? buildChart(ctx, { chartMonths: funding.chartMonths || [], isPhone: false, showYTitle: false })
      : null;

    return () => {
      chartRef.current?.destroy();
      chartRef.current = null;
    };
  }, [funding]);

  return (
    <div className="h-56 w-full">
      <canvas ref={canvasRef} aria-label="Dashboard funding outlook chart" />
    </div>
  );
}

function Dashboard({ snapshot, onNav }) {
  const { project, rollups, fundFlow } = snapshot;
  const activeAlerts = (snapshot.alerts || []).filter((alert) => ["active", "submitted", "escalated"].includes(alert.status));
  const recentWork = (snapshot.workItems || []).filter((item) => item.type !== "phase").slice(0, 5);
  const ff = window.ConstructProData.formatCurrency;
  const completionRate = rollups.total ? Math.round((rollups.completed / rollups.total) * 100) : 0;
  const hasActiveProject = Boolean(project?.id);
  const funding = fundFlow?.fundingForecast;
  const nextMonthNeed = funding?.windows?.nextMonth?.planned || 0;
  const sixMonthNeed = funding?.windows?.next6Months?.planned || 0;

  return (
    <div className="fade-in">
      <div className="mb-6 grid grid-cols-1 gap-4 md:grid-cols-2 xl:grid-cols-4">
        <StatCard title="Projects" value={snapshot.projects.length} trend={project.id ? `${project.code} active` : "Create a project"} icon={<Icons.project/>}/>
        <StatCard title="Work Progress" value={`${rollups.progressPct}%`} trend={`${rollups.total} work items`} icon={<Icons.schedule/>} tone="info"/>
        <StatCard title="Planned Budget" value={ff(rollups.budgetPlanned || fundFlow.summary.totalPlanned)} trend={`${ff(rollups.budgetActual)} actual`} icon={<Icons.finance/>} tone="success"/>
        <StatCard title="Open Alerts" value={activeAlerts.length} trend="Field requests" icon={<Icons.bell/>} tone={activeAlerts.length ? "warning" : "success"}/>
      </div>

      <div className="grid grid-cols-1 items-start gap-6 xl:grid-cols-[1.2fr_.8fr]">
        <Card className="self-start overflow-hidden border-primary/15 bg-gradient-to-br from-white via-surface-container-low to-primary-fixed/30">
          <div className="mb-4 flex items-start justify-between gap-3">
            <div>
              <h2 className="text-lg font-bold text-text-primary">{project.name}</h2>
              <p className="text-sm text-text-muted">{project.type} · {project.location}</p>
            </div>
            <Badge tone="orange">{rollups.progressPct}% rolled up</Badge>
          </div>
          <ProgressBar value={rollups.progressPct}/>
          <div className="mt-5 grid grid-cols-2 gap-3 md:grid-cols-4">
            <MetricTile label="Budget" value={ff(rollups.budgetPlanned || project.budgetTotal)}/>
            <MetricTile label="Actual" value={ff(rollups.budgetActual || project.budgetUsed)}/>
            <MetricTile label="Open" value={rollups.open}/>
            <MetricTile label="At Risk" value={rollups.risk}/>
          </div>
          <div className="mt-5 flex flex-wrap gap-2">
            <Badge tone="success">{completionRate}% completed</Badge>
            <Badge tone="info">{rollups.completed} finished items</Badge>
            {window.countAssignedTeam?.(project.teamAssignments) > 0 ? (
              <Badge tone="neutral">{window.countAssignedTeam(project.teamAssignments)} team members</Badge>
            ) : null}
            <Badge tone={activeAlerts.length ? "warning" : "success"}>
              {activeAlerts.length ? `${activeAlerts.length} active alerts` : "No active alerts"}
            </Badge>
          </div>
          <div className="mt-5 grid grid-cols-1 gap-2 sm:grid-cols-2 sm:flex sm:flex-wrap">
            <button type="button" onClick={() => onNav("workItems")} className="min-h-[44px] rounded-lg border border-border-light bg-white px-4 py-3 text-sm font-bold text-text-primary transition-colors hover:border-cta/50 hover:bg-cta/5 md:min-h-0 md:px-3 md:py-2 md:text-xs">
              Open Work Items
            </button>
            <button type="button" onClick={() => onNav("schedule")} className="min-h-[44px] rounded-lg border border-border-light bg-white px-4 py-3 text-sm font-bold text-text-primary transition-colors hover:border-cta/50 hover:bg-cta/5 md:min-h-0 md:px-3 md:py-2 md:text-xs">
              View Programme
            </button>
          </div>
        </Card>

        <Card className="self-start border-border-light/70 bg-white/95">
          <SectionTitle title="Recent Work" subtitle="Live tasks, subtasks, QC checks, and punch items." />
          <div className="space-y-3">
            {recentWork.map((item) => (
              <div key={item.id} className="rounded-lg border border-border-light bg-surface-container-low/45 p-3">
                <div className="mb-2 flex items-center justify-between gap-3">
                  <p className="font-semibold">{item.title}</p>
                  <Badge tone={item.status === "done" || item.status === "approved" ? "success" : item.status === "blocked" ? "danger" : "warning"}>{item.status}</Badge>
                </div>
                <ProgressBar value={item.progressPct} tone={item.status === "blocked" ? "danger" : "orange"}/>
              </div>
            ))}
            {!recentWork.length && <p className="text-sm text-text-muted">No work items yet. Add tasks and subtasks from Work Management.</p>}
          </div>
        </Card>
      </div>

      {hasActiveProject && funding ? (
        <Card className="border-primary/15 bg-gradient-to-br from-white via-surface-container-low to-primary-fixed/20">
          <div className="mb-4 flex flex-wrap items-start justify-between gap-3">
            <div>
              <SectionTitle
                title="Future funding outlook"
                subtitle={`Treasury planning from ${funding.nextMonthLabel} · peak ${funding.peakMonth ? `${funding.peakMonth.label} (${ff(funding.peakMonth.planned)})` : "—"}`}
              />
            </div>
            <button
              type="button"
              onClick={() => onNav("finance")}
              className="min-h-[44px] rounded-lg border border-primary/25 bg-white px-4 py-3 text-sm font-bold text-primary transition-colors hover:bg-primary/5 md:min-h-0 md:py-2 md:text-xs"
            >
              Open Finance →
            </button>
          </div>

          <FundingOutlookChart funding={funding} />

          <div className="mt-4 grid grid-cols-1 gap-3 sm:grid-cols-3">
            <MetricTile label="Next Month Need" value={ff(nextMonthNeed)} />
            <MetricTile label="Next 6 Months" value={ff(sixMonthNeed)} />
            <MetricTile label="Through Completion" value={ff(funding.windows?.throughCompletion?.planned || 0)} />
          </div>
        </Card>
      ) : null}

      <div className="mt-6 grid grid-cols-1 gap-6 xl:grid-cols-[.85fr_1.15fr]">
        <AlertLauncher compact/>
        <AlertPanel snapshot={snapshot}/>
      </div>
    </div>
  );
}

function MetricTile({ label, value }) {
  return (
    <div className="rounded-lg bg-gray-50 p-3">
      <p className="text-xs font-bold uppercase text-text-muted">{label}</p>
      <p className="mt-1 font-bold">{value}</p>
    </div>
  );
}

Object.assign(window, { Dashboard });
