'use client';

import Link from 'next/link';
import { useEffect, useState } from 'react';
import { CustomSelect } from '@/components/crm/CustomSelect';
import { getWorkflowOverview } from '@/features/reports/api.client';
import { count } from '@/features/reports/format';
import {
  ColumnChart,
  LineChart,
  ReportBody,
  useReport,
  type ReportState,
} from '@/features/reports/ui/shared';
import type { WorkflowHomeRange, WorkflowOverview } from '@/features/reports/types';
import { useCurrentUser } from '@/features/auth/CurrentUser';
import { sequenceCount } from '@/features/sequences/api.client';
import { WORKFLOW_OBJECTS } from '@/features/workflows/types';
import { useCustomWorkflowObjects } from '@/features/workflows/useCustomWorkflowObjects';
import type { WorkflowStats } from '@/features/workflows/useWorkflowStats';
import { cn } from '@/lib/utils/cn';
import { OBJECT_LABELS, actionLabel, formatWhen } from './shared';

/**
 * Overview tab of /workflows (design: workflows.php?tab=overview): start a workflow, what needs
 * review, recent changes, and how automation is used. The numbers come from the automation
 * overview report (GET /reports/workflows/overview, for the range picked); the per-object counts from
 * the workflow list. The design's marketplace and AI cards are left out.
 */

/** HUB-258 (QA #596): the "Monitor automations" date range, as in the design's dropdown. */
const RANGE_OPTIONS: { value: WorkflowHomeRange; label: string }[] = [
  { value: 'today', label: 'Today' },
  { value: '7', label: 'Last 7 days' },
  { value: '30', label: 'Last 30 days' },
  { value: '90', label: 'Last 90 days' },
  { value: '180', label: 'Last 180 days' },
  { value: 'ytd', label: 'Year to date' },
  { value: 'all', label: 'All time' },
];
const DEFAULT_RANGE: WorkflowHomeRange = '30';
const RANGE_KEY = 'crm.workflows.overview.range';

function readRange(): WorkflowHomeRange {
  try {
    const saved = window.localStorage.getItem(RANGE_KEY);
    return RANGE_OPTIONS.find((o) => o.value === saved)?.value ?? DEFAULT_RANGE;
  } catch {
    return DEFAULT_RANGE;
  }
}

/** Up to 90 days the chart shows each day; longer ranges add the days up per month. */
const byDayRanges = new Set<WorkflowHomeRange>(['today', '7', '30', '90']);

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

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

/** The report's days added up per month (YYYY-MM), oldest first. */
function enrollmentsByMonth(report: WorkflowOverview): { month: string; count: number }[] {
  const totals = new Map<string, number>();
  for (const d of report.enrollments) {
    const month = d.day.slice(0, 7);
    totals.set(month, (totals.get(month) ?? 0) + d.count);
  }
  return [...totals].map(([month, n]) => ({ month, count: n }));
}

/**
 * Sequences that are not archived, from GET /sequences/count: the same number as the Sequences
 * page's "N of 5,000 created" header (QA #351: this used to count archived sequences too).
 */
async function countSequences(): Promise<number> {
  const result = await sequenceCount();
  return result.created;
}

function StatusDot({ status }: { status: string }) {
  const on = status === 'on';
  return (
    <span className={cn('wf-dot', on ? 'is-on' : 'is-off')}>
      {on ? 'On' : status === 'draft' ? 'Draft' : 'Off'}
    </span>
  );
}

function Stat({ label, value }: { label: string; value: number | null }) {
  return (
    <div className="wf-stat">
      <span className="wf-stat__label">{label}</span>
      <span className="wf-stat__value">{value === null ? '…' : count(value)}</span>
    </div>
  );
}

export function OverviewTab({
  stats,
  issueCount,
}: {
  stats: ReportState<WorkflowStats>;
  /** New automation issues (A-07: the same count as the header dot and the Issues page). */
  issueCount: ReportState<number>;
}) {
  const me = useCurrentUser();
  const customObjects = useCustomWorkflowObjects();
  const timeZone = me.business.timezone;
  const [range, setRange] = useState<WorkflowHomeRange>(DEFAULT_RANGE);
  // The last range picked is kept per browser (read after mount: no storage on the server).
  useEffect(() => setRange(readRange()), []);
  const pickRange = (value: string) => {
    const next = RANGE_OPTIONS.find((o) => o.value === value)?.value ?? DEFAULT_RANGE;
    setRange(next);
    try {
      window.localStorage.setItem(RANGE_KEY, next);
    } catch {
      // Not kept; the pick still applies.
    }
  };
  const rangeLabel = RANGE_OPTIONS.find((o) => o.value === range)?.label ?? '';

  const overview = useReport(`workflow-overview-${range}`, (signal) =>
    getWorkflowOverview(range, { signal }),
  );
  const sequences = useReport('sequence-count', countSequences);

  const report = overview.data;
  const totals = report?.totals ?? null;
  const recent = report?.recentlyEdited ?? [];
  const data = stats.data;
  const byObject = (type: string) =>
    data ? data.all.filter((wf) => wf.objectType === type).length : null;

  return (
    <section className="wf-overview" aria-label="Overview">
      <div className="wf-grid-3">
        {/* Go-live 945: describing a workflow to AI isn't built, so it says so and takes no
            text it would throw away. */}
        <section className="card wf-card wf-pad">
          <h2 className="wf-card__title crm-mb-3">
            What do you want to automate? <span className="wfc-soon">Coming soon</span>
          </h2>
          <div className="wf-prompt">
            <textarea
              className="wf-prompt__input"
              placeholder="Soon you will be able to describe a workflow and have it drafted for you. For now, use Create workflow."
              aria-label="Describe a workflow to AI (coming soon)"
              disabled
            />
          </div>
        </section>

        <section className="card wf-card wf-pad wf-issues">
          <h2 className="wf-card__title">Automation issues to review</h2>
          <div className="wf-issues__total" title="Automation issues that need review">
            <span className="wf-stat__label">Total</span>
            <span className="wf-issues__value">
              {issueCount.error || issueCount.forbidden
                ? '–'
                : issueCount.data !== null
                  ? count(issueCount.data)
                  : '…'}
            </span>
          </div>
          <Link className="link crm-fs-7 crm-fw-semibold" href="/workflows/issues">
            Review issues
          </Link>
        </section>

        <section className="card wf-card wf-pad">
          <div className="crm-d-flex crm-justify-content-between crm-align-items-center crm-mb-3">
            <h2 className="wf-card__title">Pick up where you left off</h2>
            <Link className="link crm-fs-7 crm-fw-semibold" href="/workflows?tab=workflows">
              View all
            </Link>
          </div>
          {overview.error ? (
            <p className="crm-text-danger crm-fs-7">{overview.error}</p>
          ) : overview.loading && !report ? (
            <p className="crm-text-muted crm-fs-7">Loading…</p>
          ) : recent.length === 0 ? (
            <p className="crm-text-muted crm-fs-7">No workflows yet.</p>
          ) : (
            <div className="wf-recent" role="list">
              {recent.map((wf) => (
                <Link
                  key={wf.id}
                  href={`/workflows/${wf.id}`}
                  className="wf-recent__card"
                  role="listitem"
                >
                  <span className="wf-recent__name">{wf.name}</span>
                  <span className="wf-recent__meta">
                    Edited {formatWhen(wf.updatedAt, timeZone)}
                    {wf.updatedByName ? ` by ${wf.updatedByName}` : ''}
                  </span>
                  <StatusDot status={wf.status} />
                </Link>
              ))}
            </div>
          )}
        </section>
      </div>

      <div className="wf-section-head">
        <h2 className="wf-section-title">Monitor automations</h2>
        <CustomSelect
          className="wf-range-select"
          placeholder="Date range"
          value={range}
          options={RANGE_OPTIONS}
          searchable={false}
          onChange={pickRange}
        />
      </div>
      <div className="wf-grid-3">
        <section className="card wf-card wf-pad">
          <h3 className="wf-card__title crm-mb-3">Automations by object</h3>
          <div className="wf-stats">
            <Stat label="Workflows" value={totals ? totals.workflows : null} />
            <Stat
              label="Sequences"
              value={sequences.error || sequences.forbidden ? 0 : sequences.data}
            />
            {[...WORKFLOW_OBJECTS, ...customObjects.map((o) => o.key)].map((type) => (
              <Stat
                key={type}
                label={`${OBJECT_LABELS[type]?.one ?? type} workflows`}
                value={byObject(type)}
              />
            ))}
            <Stat label="Turned on" value={totals ? totals.on : null} />
            <Stat label="Unused (90 days)" value={totals ? totals.unused : null} />
          </div>
        </section>

        <section className="card wf-card">
          <div className="wf-card__head">
            <div>
              <h3 className="wf-card__title">Workflow enrollments</h3>
              <span className="wf-range">Date range: {rangeLabel}</span>
            </div>
          </div>
          <div className="wf-chart">
            <ReportBody state={overview} isEmpty={() => false}>
              {(r) => {
                const byDay = byDayRanges.has(range);
                const points = byDay
                  ? r.enrollments.map((d) => ({ label: dayName(d.day), count: d.count }))
                  : enrollmentsByMonth(r).map((m) => ({
                      label: monthName(m.month),
                      count: m.count,
                    }));
                return (
                  <LineChart
                    ariaLabel={`Workflow enrollments per ${byDay ? 'day' : 'month'}`}
                    labels={points.map((p) => p.label)}
                    series={[
                      {
                        key: 'enrolled',
                        label: 'Enrollments',
                        color: '#f28f23',
                        values: points.map((p) => p.count),
                      },
                    ]}
                  />
                );
              }}
            </ReportBody>
          </div>
        </section>

        <section className="card wf-card">
          <div className="wf-card__head">
            <div>
              <h3 className="wf-card__title">Most used workflow actions</h3>
              <span className="wf-range">Date range: {rangeLabel}</span>
            </div>
          </div>
          <div className="wf-chart wf-chart--accent">
            <ReportBody
              state={overview}
              isEmpty={(r) => r.topActions.length === 0}
              empty="No workflow action ran in this range."
            >
              {(r) => (
                <ColumnChart
                  ariaLabel="Workflow actions run, most used first"
                  height={150}
                  rows={r.topActions.slice(0, 6).map((a) => ({
                    key: a.actionType,
                    label: actionLabel(a.actionType),
                    value: a.runs,
                    display: count(a.runs),
                    hint: `${actionLabel(a.actionType)}: ${count(a.runs)} run${a.runs === 1 ? '' : 's'} in ${count(a.workflows)} workflow${a.workflows === 1 ? '' : 's'}`,
                  }))}
                />
              )}
            </ReportBody>
          </div>
        </section>
      </div>
    </section>
  );
}
