'use client';

import Link from 'next/link';
import { getWorkflowHealth } from '@/features/reports/api.client';
import { count } from '@/features/reports/format';
import {
  LineChart,
  ReportBody,
  StateMessage,
  useReport,
  type ReportState,
} from '@/features/reports/ui/shared';
import type { DayCount } from '@/features/reports/types';
import { useCurrentUser } from '@/features/auth/CurrentUser';
import { attentionList, type WorkflowStats } from '@/features/workflows/useWorkflowStats';
import { cn } from '@/lib/utils/cn';
import { formatWhen } from './shared';

/**
 * Health tab of /workflows (design: workflows.php?tab=health), from the automation health report
 * (GET /reports/workflows/health, last 180 days): steps that failed per day, and workflows with no
 * enrollment in the 90 days before each day. The table lists the workflows that need attention
 * now (failing, then unused), from the workflow list.
 */

const RANGE = '180' as const;
const WEEK = 7;

/** One point a week, ending on the last day: the days' sum (`sum`) or the week's last value. */
function weekly(days: DayCount[], mode: 'sum' | 'last'): { day: string; value: number }[] {
  const out: { day: string; value: number }[] = [];
  for (let end = days.length; end > 0; end -= WEEK) {
    const week = days.slice(Math.max(0, end - WEEK), end);
    out.unshift({
      day: week.at(-1)!.day,
      value: mode === 'sum' ? week.reduce((n, d) => n + d.count, 0) : week.at(-1)!.count,
    });
  }
  return out;
}

const sumLast = (days: DayCount[], n: number) =>
  days.slice(-n).reduce((total, d) => total + d.count, 0);

/** The value `daysAgo` days before the last day (the first day when the range is shorter). */
const valueAgo = (days: DayCount[], daysAgo: number) =>
  days[Math.max(0, days.length - 1 - daysAgo)]?.count ?? 0;

function shortDay(day: string): string {
  return new Date(`${day}T00:00:00Z`).toLocaleString('en-US', {
    month: 'short',
    day: '2-digit',
    timeZone: 'UTC',
  });
}

function Kpi({ value, label, sub }: { value: number | null; label: string; sub: string }) {
  return (
    <div className="wf-kpi wf-kpi--center">
      <span className="wf-kpi__value">{value === null ? '…' : count(value)}</span>
      <span className="wf-kpi__label">{label}</span>
      <span className="wf-kpi__sub">{sub}</span>
    </div>
  );
}

export function HealthTab({ stats }: { stats: ReportState<WorkflowStats> }) {
  const me = useCurrentUser();
  const timeZone = me.business.timezone;
  const health = useReport(`workflow-health-${RANGE}`, (signal) =>
    getWorkflowHealth(RANGE, { signal }),
  );
  const report = health.data;
  const data = stats.data;

  const attention = data ? attentionList(data) : [];
  const failingIds = new Set(data?.needsReview.map((wf) => wf.id));

  return (
    <section className="wf-panel" aria-label="Health">
      <h2 className="wf-page-title">Workflows health reports</h2>

      <div className="wf-grid-2 crm-mb-4">
        <div className="card wf-card wf-kpis wf-kpis--grid">
          <Kpi
            value={report ? report.issuesNow : null}
            label="Open issues"
            sub="Failed enrollments today"
          />
          <Kpi
            value={report ? sumLast(report.issues, 30) : null}
            label="Failed steps"
            sub="Last 30 days"
          />
          <Kpi
            value={report ? sumLast(report.issues, report.issues.length) : null}
            label="Failed steps"
            sub="Last 180 days"
          />
        </div>
        <div className="card wf-card wf-kpis wf-kpis--grid">
          <Kpi
            value={report ? report.unusedNow : null}
            label="Unused workflows"
            sub="As of today"
          />
          <Kpi
            value={report ? valueAgo(report.unused, 30) : null}
            label="Unused workflows"
            sub="30 days ago"
          />
          <Kpi
            value={report ? valueAgo(report.unused, report.unused.length - 1) : null}
            label="Unused workflows"
            sub="180 days ago"
          />
        </div>
      </div>

      <div className="wf-grid-2 crm-mb-4">
        <section className="card wf-card">
          <div className="wf-card__head">
            <div>
              <h3 className="wf-card__title">Opportunities to review workflows with issues</h3>
              <p className="wf-card__sub">Workflow steps that failed, per week</p>
            </div>
          </div>
          <div className="wf-chart">
            <ReportBody state={health} isEmpty={() => false}>
              {(r) => {
                const points = weekly(r.issues, 'sum');
                return (
                  <LineChart
                    ariaLabel="Failed workflow steps per week over the past 180 days"
                    labels={points.map((p) => shortDay(p.day))}
                    series={[
                      {
                        key: 'issues',
                        label: 'Failed steps',
                        color: '#c11574',
                        values: points.map((p) => p.value),
                      },
                    ]}
                  />
                );
              }}
            </ReportBody>
          </div>
          <p className="wf-card__foot">
            <Link className="link" href="/workflows?tab=workflows&view=needs_review">
              View workflows with issues
            </Link>
          </p>
        </section>

        <section className="card wf-card">
          <div className="wf-card__head">
            <div>
              <h3 className="wf-card__title">Opportunities to delete unused workflows</h3>
              <p className="wf-card__sub">
                The line shows, at each date, how many workflows had no enrollments for at least 90
                days
              </p>
            </div>
          </div>
          <div className="wf-chart">
            <ReportBody state={health} isEmpty={() => false}>
              {(r) => {
                const points = weekly(r.unused, 'last');
                return (
                  <LineChart
                    ariaLabel="Unused workflows over the past 180 days"
                    labels={points.map((p) => shortDay(p.day))}
                    series={[
                      {
                        key: 'unused',
                        label: 'Unused workflows',
                        color: '#444ce7',
                        values: points.map((p) => p.value),
                      },
                    ]}
                  />
                );
              }}
            </ReportBody>
          </div>
          <p className="wf-card__foot">
            View workflows in the group:{' '}
            <Link className="link" href="/workflows?tab=workflows&view=unused">
              Unused
            </Link>
          </p>
        </section>
      </div>

      <section className="card wf-card">
        <div className="wf-card__head crm-mb-3">
          <h3 className="wf-card__title">Workflows that need attention</h3>
        </div>
        {stats.error ? (
          <StateMessage tone="danger" title="Could not load workflows">
            {stats.error}
          </StateMessage>
        ) : !data ? (
          <StateMessage>Loading…</StateMessage>
        ) : attention.length === 0 ? (
          <StateMessage>
            Every workflow is healthy: nothing failed and nothing is unused.
          </StateMessage>
        ) : (
          <div className="table-wrap crm-table-wrap">
            <table className="crm-table table">
              <thead>
                <tr>
                  <th scope="col">Workflow</th>
                  <th scope="col">Status</th>
                  <th scope="col">Issues</th>
                  <th scope="col" className="crm-text-end crm-text-nowrap">
                    Enrolled Last 7 Days
                  </th>
                  <th scope="col" className="crm-text-nowrap">
                    Last Updated
                  </th>
                </tr>
              </thead>
              <tbody>
                {attention.map((wf) => {
                  const failing = failingIds.has(wf.id);
                  return (
                    <tr key={wf.id}>
                      <td data-label="Workflow">
                        <Link
                          className="rec-link crm-fw-semibold"
                          href={failing ? `/workflows/${wf.id}?tab=errors` : `/workflows/${wf.id}`}
                        >
                          {wf.name}
                        </Link>
                      </td>
                      <td data-label="Status" className="crm-text-nowrap">
                        <span
                          className={cn(
                            'sync-status crm-fw-normal',
                            wf.status !== 'on' && 'crm-text-muted',
                          )}
                        >
                          {wf.currentVersionId ? 'Published' : 'Unpublished'}
                        </span>
                      </td>
                      <td data-label="Issues">
                        {failing ? (
                          <span className="badge badge--danger" title="As on the Issues page">
                            {wf.errorCount > 0 ? `${wf.errorCount} failed` : 'Setup problem'}
                          </span>
                        ) : (
                          <span className="badge" title="No enrollments in the last 90 days">
                            Unused
                          </span>
                        )}
                      </td>
                      <td data-label="Enrolled Last 7 Days" className="crm-text-end">
                        {wf.enrolledLast7Days > 0 ? count(wf.enrolledLast7Days) : '--'}
                      </td>
                      <td data-label="Last Updated" className="crm-text-nowrap">
                        {formatWhen(wf.updatedAt, timeZone)}
                      </td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </div>
        )}
      </section>
    </section>
  );
}
