'use client';

import { labelledPoints, tickText, valueTicks } from '../chartAxis';
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { CustomSelect, type CustomSelectOption } from '@/components/crm/CustomSelect';
import { useCurrentUser } from '@/features/auth/CurrentUser';
import { ownerDisplayName } from '@/features/owners/labels';
import { useOwners } from '@/features/owners/useOwners';
import { errorText, isApiError } from '@/lib/api/errors';
import { cn } from '@/lib/utils/cn';
import { rangeError, resolveDateRange, todayIn } from '../format';
import { DASHBOARD_DATE_RANGES, DATE_RANGE_LABEL, type DashboardDateRange } from '../types';

// --- Loading a report ----------------------------------------------------------------------------

export interface ReportState<T> {
  data: T | null;
  loading: boolean;
  error: string | null;
  /** 403: the caller lacks the permission this report needs. */
  forbidden: boolean;
  reload: () => void;
}

/**
 * Runs `fetcher` whenever `key` changes (and on `reload`), aborting the previous request.
 * `key` null: nothing to load yet (e.g. a filter is still missing or invalid).
 */
export function useReport<T>(
  key: string | null,
  fetcher: (signal: AbortSignal) => Promise<T>,
): ReportState<T> {
  const fetcherRef = useRef(fetcher);
  fetcherRef.current = fetcher;
  const [data, setData] = useState<T | null>(null);
  const [loading, setLoading] = useState(key !== null);
  const [error, setError] = useState<string | null>(null);
  const [forbidden, setForbidden] = useState(false);
  const [nonce, setNonce] = useState(0);

  useEffect(() => {
    if (key === null) {
      setLoading(false);
      return;
    }
    const controller = new AbortController();
    setLoading(true);
    setError(null);
    fetcherRef.current(controller.signal).then(
      (result) => {
        if (controller.signal.aborted) return;
        setData(result);
        setForbidden(false);
        setLoading(false);
      },
      (err: unknown) => {
        if (controller.signal.aborted) return;
        const denied = isApiError(err) && err.isForbidden;
        setForbidden(denied);
        setError(denied ? null : errorText(err));
        setData(null);
        setLoading(false);
      },
    );
    return () => controller.abort();
  }, [key, nonce]);

  const reload = useCallback(() => setNonce((n) => n + 1), []);
  return { data, loading, error, forbidden, reload };
}

// --- Card + states -------------------------------------------------------------------------------

export function ReportCard({
  title,
  subtitle,
  actions,
  children,
  className,
}: {
  title: React.ReactNode;
  subtitle?: React.ReactNode;
  actions?: React.ReactNode;
  children: React.ReactNode;
  className?: string;
}) {
  return (
    <section className={cn('card list-card', className)}>
      <header className="list-card__head crm-flex-wrap">
        <div style={{ minWidth: 0 }}>
          <h2 className="list-card__title">{title}</h2>
          {subtitle ? <p className="crm-fs-8 crm-text-muted crm-mt-1">{subtitle}</p> : null}
        </div>
        {actions ? <div className="crm-d-flex crm-gap-2 crm-flex-wrap">{actions}</div> : null}
      </header>
      <div>{children}</div>
    </section>
  );
}

export function StateMessage({
  tone = 'muted',
  title,
  children,
}: {
  tone?: 'muted' | 'danger';
  title?: string;
  children?: React.ReactNode;
}) {
  return (
    <div className="crm-p-5 crm-text-center" role={tone === 'danger' ? 'alert' : 'status'}>
      {title ? (
        <p className={cn('crm-fw-semibold crm-mb-1', tone === 'danger' && 'crm-text-danger')}>
          {title}
        </p>
      ) : null}
      {children ? <p className="crm-text-muted crm-fs-7">{children}</p> : null}
    </div>
  );
}

/**
 * Loading / forbidden / error / empty for a report body; renders `children(data)` otherwise.
 * `isEmpty` decides when loaded data has nothing to show.
 */
export function ReportBody<T>({
  state,
  isEmpty,
  empty = 'No data for these filters.',
  forbiddenText = 'You do not have permission to see this report.',
  children,
}: {
  state: ReportState<T>;
  isEmpty: (data: T) => boolean;
  empty?: string;
  forbiddenText?: string;
  children: (data: T) => React.ReactNode;
}) {
  if (state.forbidden) return <StateMessage title="No access">{forbiddenText}</StateMessage>;
  if (state.error) {
    return (
      <StateMessage tone="danger" title="Could not load this report">
        {state.error}{' '}
        <button type="button" className="btn-crm btn-crm--ghost btn-crm--sm" onClick={state.reload}>
          Try again
        </button>
      </StateMessage>
    );
  }
  if (state.data === null) return <StateMessage>{state.loading ? 'Loading…' : empty}</StateMessage>;
  if (isEmpty(state.data)) return <StateMessage>{empty}</StateMessage>;
  return (
    <div
      aria-busy={state.loading}
      style={{ opacity: state.loading ? 0.6 : 1, transition: 'opacity .15s' }}
    >
      {children(state.data)}
    </div>
  );
}

// --- Charts (plain CSS, no chart library) --------------------------------------------------------

export interface BarDatum {
  key: string;
  label: React.ReactNode;
  value: number;
  /** Shown at the end of the row (and in the tooltip). */
  display: string;
  hint?: string;
}

/** Horizontal bars on the design's `.progress` rows (one series, scaled to the largest). */
export function BarRows({ rows, ariaLabel }: { rows: BarDatum[]; ariaLabel: string }) {
  const max = Math.max(0, ...rows.map((r) => r.value));
  return (
    <ul className="progress-list" aria-label={ariaLabel}>
      {rows.map((row) => {
        const percent = max > 0 ? Math.max(row.value > 0 ? 1 : 0, (row.value / max) * 100) : 0;
        return (
          <li className="progress-row" key={row.key} title={row.hint ?? row.display}>
            <div className="progress-row__head">
              <span className="progress-row__label">{row.label}</span>
              <span className="progress-row__amount">{row.display}</span>
            </div>
            <div className="progress" aria-hidden>
              <span
                className="progress__bar is-in"
                style={{ '--p': `${percent}%` } as React.CSSProperties}
              />
            </div>
          </li>
        );
      })}
    </ul>
  );
}

export type LineSeries = {
  key: string;
  label: string;
  color: string;
  /** One y per shared x (same length/order as `labels`). */
  values: number[];
};

/**
 * Multi-series line chart (Analyze view enrollments over time). Drawn at the width it has, so
 * text isn't stretched: round numbers up the side, and only as many dates as fit underneath
 * (Automation go-live 953).
 */
export function LineChart({
  labels,
  series,
  ariaLabel,
  height = 200,
  variant = 'line',
  showValues = false,
}: {
  labels: string[];
  series: LineSeries[];
  ariaLabel: string;
  height?: number;
  /** `bar`: the series side by side as columns on the same axes. */
  variant?: 'line' | 'bar';
  /** Each non-zero point's number above it. */
  showValues?: boolean;
}) {
  const box = useRef<HTMLDivElement>(null);
  const [width, setWidth] = useState(480);
  useEffect(() => {
    const element = box.current;
    if (!element || typeof ResizeObserver === 'undefined') return;
    const observer = new ResizeObserver(([entry]) => {
      const next = Math.floor(entry?.contentRect.width ?? 0);
      if (next > 0) setWidth(next);
    });
    observer.observe(element);
    return () => observer.disconnect();
  }, []);

  const ticks = valueTicks(Math.max(0, ...series.flatMap((s) => s.values)));
  const top = ticks.at(-1)!;
  const widest = Math.max(...ticks.map((t) => tickText(t).length));
  const pad = {
    top: showValues ? 20 : 12,
    right: 24,
    bottom: 28,
    left: Math.max(28, widest * 7 + 12),
  };
  const innerW = Math.max(1, width - pad.left - pad.right);
  const innerH = height - pad.top - pad.bottom;
  const n = Math.max(1, labels.length - 1);
  const bars = variant === 'bar';
  // Columns stand in the middle of equal slots; a line runs from one edge to the other.
  const slot = innerW / Math.max(1, labels.length);
  const barWidth = (slot * 0.8) / Math.max(1, series.length);
  const xAt = (i: number) =>
    pad.left + (bars ? slot * (i + 0.5) : labels.length <= 1 ? innerW / 2 : (i / n) * innerW);
  const yAt = (v: number) => pad.top + innerH - (v / top) * innerH;
  const dated = labelledPoints(labels.length, innerW);

  return (
    <div className="wf-line" role="img" aria-label={ariaLabel} ref={box}>
      <svg viewBox={`0 0 ${width} ${height}`} width="100%" height={height}>
        {ticks.map((t) => (
          <g key={t}>
            <line
              x1={pad.left}
              x2={width - pad.right}
              y1={yAt(t)}
              y2={yAt(t)}
              stroke="var(--border)"
              strokeWidth={1}
            />
            <text
              x={pad.left - 8}
              y={yAt(t) + 3.5}
              textAnchor="end"
              className="wf-line__tick wf-line__tick--y"
            >
              {tickText(t)}
            </text>
          </g>
        ))}
        {series.map((s, si) => {
          // Where series `si` stands at point `i`: its own column, or the line's point.
          const at = (i: number) => (bars ? xAt(i) - slot * 0.4 + barWidth * (si + 0.5) : xAt(i));
          const numbers = showValues
            ? s.values.map((v, i) =>
                v > 0 ? (
                  <text
                    key={`${s.key}-n${i}`}
                    x={at(i)}
                    y={yAt(v) - 6}
                    textAnchor="middle"
                    className="wf-line__value"
                  >
                    {tickText(v)}
                  </text>
                ) : null,
              )
            : null;
          if (bars) {
            return (
              <g key={s.key}>
                {s.values.map((v, i) => (
                  <rect
                    key={`${s.key}-${i}`}
                    x={at(i) - barWidth / 2}
                    y={yAt(v)}
                    width={Math.max(1, barWidth - 1)}
                    height={Math.max(0, yAt(0) - yAt(v))}
                    fill={s.color}
                  >
                    <title>
                      {s.label}: {labels[i]} — {v.toLocaleString()}
                    </title>
                  </rect>
                ))}
                {numbers}
              </g>
            );
          }
          const pts = s.values.map((v, i) => `${xAt(i).toFixed(1)},${yAt(v).toFixed(1)}`).join(' ');
          return (
            <g key={s.key}>
              <polyline
                fill="none"
                stroke={s.color}
                strokeWidth={2}
                strokeLinejoin="round"
                strokeLinecap="round"
                points={pts}
              />
              {s.values.map((v, i) => (
                <circle key={`${s.key}-${i}`} cx={xAt(i)} cy={yAt(v)} r={3} fill={s.color}>
                  <title>
                    {s.label}: {labels[i]} — {v.toLocaleString()}
                  </title>
                </circle>
              ))}
              {numbers}
            </g>
          );
        })}
        {dated.map((i) => (
          <text
            key={i}
            x={xAt(i)}
            y={height - 8}
            // The ends' dates stay inside the picture.
            textAnchor={
              !bars && labels.length > 1 && i === 0
                ? 'start'
                : !bars && labels.length > 1 && i === labels.length - 1
                  ? 'end'
                  : 'middle'
            }
            className="wf-line__tick"
          >
            {labels[i]}
          </text>
        ))}
      </svg>
      {series.length > 0 ? (
        <ul className="wf-line__legend">
          {series.map((s) => (
            <li key={s.key}>
              <span className="wf-line__swatch" style={{ background: s.color }} />
              {s.label}
            </li>
          ))}
        </ul>
      ) : null}
    </div>
  );
}

/** Vertical columns (one series), e.g. one per month. Hover a column for its value. */
export function ColumnChart({
  rows,
  ariaLabel,
  height = 180,
}: {
  rows: BarDatum[];
  ariaLabel: string;
  height?: number;
}) {
  const max = Math.max(0, ...rows.map((r) => r.value));
  return (
    <div role="img" aria-label={ariaLabel} className="crm-p-4" style={{ overflowX: 'auto' }}>
      <div
        style={{
          display: 'flex',
          alignItems: 'flex-end',
          gap: 6,
          height,
          minWidth: rows.length * 36,
          borderBottom: '1px solid var(--border)',
        }}
      >
        {rows.map((row) => {
          const h = max > 0 ? (row.value / max) * 100 : 0;
          return (
            <div
              key={row.key}
              title={row.hint ?? row.display}
              style={{
                flex: '1 1 0',
                height: '100%',
                display: 'flex',
                flexDirection: 'column',
                justifyContent: 'flex-end',
                alignItems: 'center',
                minWidth: 30,
              }}
            >
              <span className="crm-fs-8 crm-text-muted crm-text-nowrap" style={{ marginBottom: 4 }}>
                {row.value > 0 ? row.display : ''}
              </span>
              <span
                style={{
                  display: 'block',
                  width: '70%',
                  maxWidth: 40,
                  height: `${row.value > 0 ? Math.max(h, 1.5) : 0}%`,
                  background: 'var(--brand)',
                  borderRadius: '4px 4px 0 0',
                  transition: 'height .4s ease',
                }}
              />
            </div>
          );
        })}
      </div>
      <div style={{ display: 'flex', gap: 6, minWidth: rows.length * 36, marginTop: 6 }}>
        {rows.map((row) => (
          // QA #580: in a narrow (half-width) widget "Oct '25" wraps onto two lines instead of
          // being cut to "Oc…"; anything longer stops at two lines.
          <span
            key={row.key}
            className="crm-fs-8 crm-text-muted crm-text-center"
            title={typeof row.label === 'string' ? row.label : undefined}
            style={{
              flex: '1 1 0',
              minWidth: 30,
              lineHeight: 1.2,
              overflow: 'hidden',
              display: '-webkit-box',
              WebkitLineClamp: 2,
              WebkitBoxOrient: 'vertical',
            }}
          >
            {row.label}
          </span>
        ))}
      </div>
    </div>
  );
}

/** Pills to pick one currency: amounts in different currencies are never added together. */
export function CurrencyTabs({
  currencies,
  value,
  onChange,
}: {
  currencies: string[];
  value: string;
  onChange: (currency: string) => void;
}) {
  if (currencies.length < 2) return null;
  return (
    <div className="crm-d-flex crm-gap-1" role="group" aria-label="Currency">
      {currencies.map((c) => (
        <button
          key={c}
          type="button"
          className={cn(
            'btn-crm btn-crm--sm',
            c === value ? 'btn-crm--primary' : 'btn-crm--outline',
          )}
          aria-pressed={c === value}
          onClick={() => onChange(c)}
        >
          {c}
        </button>
      ))}
    </div>
  );
}

/** The selected currency, kept valid as the list of currencies changes. */
export function useCurrency(currencies: string[]): [string, (c: string) => void] {
  const [picked, setPicked] = useState('');
  const current = currencies.includes(picked) ? picked : (currencies[0] ?? '');
  return [current, setPicked];
}

// --- Filters -------------------------------------------------------------------------------------

export type RangeChoice = DashboardDateRange | 'custom';

export interface DateRangeValue {
  choice: RangeChoice;
  from: string;
  to: string;
}

const RANGE_OPTIONS: CustomSelectOption[] = [
  ...DASHBOARD_DATE_RANGES.map((r) => ({ value: r, label: DATE_RANGE_LABEL[r] })),
  { value: 'custom', label: 'Custom range' },
];

/** Date range state on the business clock, starting from a preset. */
export function useDateRange(initial: DashboardDateRange): {
  value: DateRangeValue;
  setValue: (v: DateRangeValue) => void;
  /** The range to send, or null while a custom range is invalid. */
  range: { from: string; to: string } | null;
  error: string | null;
} {
  const me = useCurrentUser();
  const today = todayIn(me.business.timezone);
  const [value, setValue] = useState<DateRangeValue>(() => ({
    choice: initial,
    ...resolveDateRange(initial, today),
  }));
  const error = value.choice === 'custom' ? rangeError(value.from, value.to) : null;
  const range = useMemo(
    () => (error ? null : { from: value.from, to: value.to }),
    [error, value.from, value.to],
  );
  return { value, setValue, range, error };
}

export function DateRangeFilter({
  value,
  onChange,
  error,
  maxDaysNote = true,
}: {
  value: DateRangeValue;
  onChange: (v: DateRangeValue) => void;
  error?: string | null;
  maxDaysNote?: boolean;
}) {
  const me = useCurrentUser();
  return (
    <>
      <CustomSelect
        placeholder="Date range"
        value={value.choice}
        options={RANGE_OPTIONS}
        searchable={false}
        onChange={(v) => {
          const choice = (v || 'this_month') as RangeChoice;
          if (choice === 'custom') onChange({ ...value, choice });
          else onChange({ choice, ...resolveDateRange(choice, todayIn(me.business.timezone)) });
        }}
        menuMinWidth={180}
      />
      {value.choice === 'custom' ? (
        <span className="crm-d-inline-flex crm-align-items-center crm-gap-1">
          <input
            className="input"
            type="date"
            aria-label="From"
            value={value.from}
            max={value.to || undefined}
            onChange={(e) => onChange({ ...value, from: e.target.value })}
            style={{ width: 'auto' }}
          />
          <span className="crm-text-muted">–</span>
          <input
            className="input"
            type="date"
            aria-label="To"
            value={value.to}
            min={value.from || undefined}
            onChange={(e) => onChange({ ...value, to: e.target.value })}
            style={{ width: 'auto' }}
          />
        </span>
      ) : null}
      {error ? (
        <span className="crm-fs-8 crm-text-danger" role="alert">
          {error}
        </span>
      ) : value.choice === 'custom' && maxDaysNote ? (
        <span className="crm-fs-8 crm-text-muted">At most 366 days</span>
      ) : null}
    </>
  );
}

/** Which object permission gates the owner filter (own-only users must not pick colleagues). */
export type OwnerFilterScope = 'deal' | 'activity';

function mayPickAnyOwner(
  scope: OwnerFilterScope | undefined,
  me: ReturnType<typeof useCurrentUser>,
) {
  if (!scope) return true;
  if (scope === 'deal') return me.permissionSet.rules.objects.deal.view === 'all';
  const activity = me.permissionSet.rules.objects.activity.view;
  const task = me.permissionSet.rules.objects.task.view;
  return activity === 'all' || task === 'all';
}

/**
 * Owner filter options (includes deactivated as "Name (deactivated)"). `/owners` is available
 * to every member; when the list fails or is empty the picker is hidden.
 */
export function useOwnerOptions(
  allLabel = 'All owners',
  scope?: OwnerFilterScope,
): CustomSelectOption[] | null {
  const me = useCurrentUser();
  const { owners, error } = useOwners(true, true);
  return useMemo(() => {
    if (!mayPickAnyOwner(scope, me)) return null;
    if (error || owners.length === 0) return null;
    return [
      { value: '', label: allLabel },
      ...owners.map((o) => ({ value: o.userId, label: ownerDisplayName(o) })),
    ];
  }, [owners, error, allLabel, scope, me]);
}

/**
 * Team / all-scope check for report owner pickers. Users with `view: 'own'` only see their own
 * numbers on the API, so the owner filter would be misleading.
 */
export type ReportOwnerTeamAccess = 'deal' | 'activity' | 'sequences' | 'workflows' | false;

function canFilterReportOwners(
  me: ReturnType<typeof useCurrentUser>,
  access: ReportOwnerTeamAccess,
): boolean {
  if (access === false) return true;
  if (access === 'sequences') return Boolean(me.permissionSet.rules.app.manage_sequences);
  if (access === 'workflows') return Boolean(me.permissionSet.rules.app.manage_workflows);
  return me.permissionSet.rules.objects[access].view === 'all';
}

export function OwnerFilter({
  options,
  value,
  onChange,
  placeholder = 'Owner: All',
  /** Scope that must be team/all; `false` when the parent already gates (e.g. Targets). */
  teamAccess = 'deal',
}: {
  options: CustomSelectOption[] | null;
  value: string;
  onChange: (v: string) => void;
  placeholder?: string;
  teamAccess?: ReportOwnerTeamAccess;
}) {
  const me = useCurrentUser();
  if (!canFilterReportOwners(me, teamAccess)) return null;
  if (!options) return null;
  return (
    <CustomSelect
      placeholder={placeholder}
      value={value}
      options={options.filter((o) => o.value !== '')}
      onChange={onChange}
      menuMinWidth={220}
    />
  );
}

/**
 * A simple data table in the design's table styles. On narrow screens tables turn into cards
 * that hide the header row and label each value from its cell's `data-label`; report rows are
 * built by many views, so the labels are copied from the header here (QA 16 Oct #21). Report
 * tables have no checkbox column (the "plain" card layout).
 */
export function ReportTable({
  head,
  children,
  label,
}: {
  head: React.ReactNode;
  children: React.ReactNode;
  label: string;
}) {
  const ref = useRef<HTMLTableElement>(null);
  useEffect(() => {
    const table = ref.current;
    if (!table) return;
    const headRow = table.tHead?.rows[table.tHead.rows.length - 1];
    if (!headRow) return;
    // Header texts by column, a colspan taking several columns.
    const labels: string[] = [];
    for (const th of Array.from(headRow.cells)) {
      const text = th.textContent?.trim() ?? '';
      for (let i = 0; i < th.colSpan; i += 1) labels.push(text);
    }
    for (const body of Array.from(table.tBodies)) {
      for (const row of Array.from(body.rows)) {
        let col = 0;
        for (const cell of Array.from(row.cells)) {
          if (!cell.hasAttribute('data-label') && labels[col]) {
            cell.setAttribute('data-label', labels[col]!);
          }
          col += cell.colSpan;
        }
      }
    }
  });
  return (
    <div className="table-wrap crm-table-wrap sales-scroll">
      <table ref={ref} className="crm-table crm-table--plain table" aria-label={label}>
        <thead>{head}</thead>
        <tbody>{children}</tbody>
      </table>
    </div>
  );
}
