'use client';

import Link from 'next/link';
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { useToast } from '@/components/crm/ToastProvider';
import { useConfirm } from '@/components/crm/useConfirm';
import { errorText } from '@/lib/api/errors';
import { cn } from '@/lib/utils/cn';
import { formatFigure, periodRange } from '@/features/sales-analytics/format';
import {
  analyzeTargetAccounts,
  getTargetAccountMetrics,
  listTargetAccounts,
  markTargetAccounts,
  targetAccountsExportUrl,
  type TargetAccountAnalyze,
  type TargetAccountList,
  type TargetAccountMetrics,
  type TargetAccountView,
} from '../api.client';
import { ChooseTargetAccountsDialog } from './ChooseTargetAccountsDialog';

/**
 * Sales › Target Accounts (HUB-711, 13 Nov design target-accounts.php): account-based selling on
 * the companies flagged as target accounts. Manage: default views, metric cards and the table;
 * Analyze: activity, pipeline, closed deals and the accounts by industry, tier and rep.
 * "Choose target accounts" marks companies; ticked rows can be removed from the list.
 */

/** The table's optional columns (Edit columns); Name is always shown. */
const COLUMNS = [
  { key: 'tier', label: 'Ideal Customer Profile Tier' },
  { key: 'stage', label: 'Lifecycle stage' },
  { key: 'roles', label: 'Contacts with Buying Roles' },
  { key: 'deals', label: 'Open Deals' },
  { key: 'value', label: 'Open deal value' },
  { key: 'owner', label: 'Company owner' },
  { key: 'last', label: 'Last engagement' },
  { key: 'next', label: 'Next activity' },
] as const;
type ColumnKey = (typeof COLUMNS)[number]['key'];
const DEFAULT_COLUMNS: ColumnKey[] = ['tier', 'stage', 'roles', 'deals', 'owner', 'last', 'next'];
const COLUMNS_KEY = 'crm.targetAccounts.columns';

function savedColumns(): ColumnKey[] {
  try {
    const raw = JSON.parse(window.localStorage.getItem(COLUMNS_KEY) ?? 'null') as unknown;
    if (Array.isArray(raw)) {
      const known = new Set<string>(COLUMNS.map((c) => c.key));
      return raw.filter((k): k is ColumnKey => typeof k === 'string' && known.has(k));
    }
  } catch {
    // Storage blocked or bad JSON: the default columns.
  }
  return DEFAULT_COLUMNS;
}

function until(iso: string | null, now: number, timeZone?: string): string {
  if (!iso) return '-';
  // Calendar days in the viewer's zone, so a task due tomorrow morning reads "Tomorrow".
  const day = (ms: number) =>
    Date.parse(new Date(ms).toLocaleDateString('en-CA', { ...(timeZone && { timeZone }) }));
  const days = Math.round((day(Date.parse(iso)) - day(now)) / 86_400_000);
  const date = new Date(iso).toLocaleDateString('en-US', {
    month: 'short',
    day: 'numeric',
    ...(timeZone && { timeZone }),
  });
  if (days < 1) return `Today (${date})`;
  if (days < 2) return `Tomorrow (${date})`;
  return `In ${days} days (${date})`;
}

const VIEWS: { key: TargetAccountView; label: string }[] = [
  { key: 'all', label: 'All target accounts' },
  { key: 'no_decision_maker', label: 'No decision maker' },
  { key: 'no_activities', label: 'No activities' },
  { key: 'no_open_deals', label: 'No open deals' },
];
const PAGE_SIZE = 25;

const words = (value: string | null) =>
  value
    ? value
        .replace(/[_-]+/g, ' ')
        .toLowerCase()
        .replace(/^./, (c) => c.toUpperCase())
    : '-';

function ago(iso: string | null, now: number): string {
  if (!iso) return '-';
  const days = Math.floor((now - Date.parse(iso)) / 86_400_000);
  if (days < 1) return 'Today';
  if (days < 30) return `${days} day${days === 1 ? '' : 's'} ago`;
  const months = Math.floor(days / 30);
  if (months < 12) return `${months} month${months === 1 ? '' : 's'} ago`;
  const years = Math.floor(months / 12);
  return `${years} year${years === 1 ? '' : 's'} ago`;
}

export function TargetAccountsView() {
  const [tab, setTab] = useState<'manage' | 'analyze'>('manage');
  const [choosing, setChoosing] = useState(false);
  const [version, setVersion] = useState(0);
  return (
    <div className="ta-page">
      <header className="ta-head">
        <h1 className="ta-title">Target Accounts</h1>
        <button
          type="button"
          className="btn-crm btn-crm--outline"
          onClick={() => setChoosing(true)}
        >
          Choose target accounts
        </button>
      </header>
      <ChooseTargetAccountsDialog
        open={choosing}
        onClose={() => setChoosing(false)}
        onSaved={() => {
          setVersion((v) => v + 1);
          setTab('manage');
        }}
      />
      <nav className="tabs ta-tabs" aria-label="Target accounts">
        {(['manage', 'analyze'] as const).map((t) => (
          <button
            type="button"
            key={t}
            className={cn('tab', tab === t && 'active')}
            aria-current={tab === t ? 'page' : undefined}
            onClick={() => setTab(t)}
          >
            <span className="tab-text">{t === 'manage' ? 'Manage' : 'Analyze'}</span>
          </button>
        ))}
      </nav>
      {tab === 'manage' ? (
        <ManageTab version={version} onChange={() => setVersion((v) => v + 1)} />
      ) : (
        <AnalyzeTab />
      )}
    </div>
  );
}

function ManageTab({ version, onChange }: { version: number; onChange: () => void }) {
  const toast = useToast();
  const { confirm, dialog } = useConfirm();
  const [selected, setSelected] = useState<Set<string>>(new Set());
  const [columns, setColumns] = useState<ColumnKey[]>(DEFAULT_COLUMNS);
  const [editColumns, setEditColumns] = useState(false);
  const columnsMenu = useRef<HTMLSpanElement>(null);
  useEffect(() => setColumns(savedColumns()), []);
  useEffect(() => {
    if (!editColumns) return;
    const onKey = (e: KeyboardEvent) => e.key === 'Escape' && setEditColumns(false);
    const onDown = (e: MouseEvent) =>
      !columnsMenu.current?.contains(e.target as Node) && setEditColumns(false);
    document.addEventListener('keydown', onKey);
    document.addEventListener('mousedown', onDown);
    return () => {
      document.removeEventListener('keydown', onKey);
      document.removeEventListener('mousedown', onDown);
    };
  }, [editColumns]);
  const show = useCallback((k: ColumnKey) => columns.includes(k), [columns]);
  const toggleColumn = (k: ColumnKey) =>
    setColumns((prev) => {
      const next = prev.includes(k) ? prev.filter((c) => c !== k) : [...prev, k];
      try {
        window.localStorage.setItem(COLUMNS_KEY, JSON.stringify(next));
      } catch {
        // Not saved: the choice lasts for this visit.
      }
      return next;
    });
  const [view, setView] = useState<TargetAccountView>('all');
  const [q, setQ] = useState('');
  const [query, setQuery] = useState('');
  const [page, setPage] = useState(1);
  const [metrics, setMetrics] = useState<TargetAccountMetrics | null>(null);
  const [showMetrics, setShowMetrics] = useState(true);
  const [list, setList] = useState<TargetAccountList | null>(null);
  const [error, setError] = useState<string | null>(null);
  const now = useMemo(() => Date.now(), []);

  useEffect(() => {
    getTargetAccountMetrics().then(setMetrics, () => setMetrics(null));
  }, [version]);
  useEffect(() => {
    const t = window.setTimeout(() => setQuery(q), 250);
    return () => window.clearTimeout(t);
  }, [q]);
  useEffect(() => {
    let alive = true;
    setList(null);
    setSelected(new Set());
    listTargetAccounts({ view, q: query, page, limit: PAGE_SIZE }).then(
      (res) => {
        if (!alive) return;
        setList(res);
        setError(null);
      },
      (err: unknown) => alive && setError(errorText(err)),
    );
    return () => {
      alive = false;
    };
  }, [view, query, page, version]);

  const remove = async () => {
    const ids = [...selected];
    const ok = await confirm({
      title: 'Remove target accounts',
      message: `Remove ${ids.length} compan${ids.length === 1 ? 'y' : 'ies'} from target accounts? The companies themselves are kept.`,
      confirmLabel: 'Remove',
      danger: true,
    });
    if (!ok) return;
    try {
      const res = await markTargetAccounts(ids, false);
      toast(
        res.failed.length
          ? `${res.updated} removed, ${res.failed.length} could not be changed: ${res.failed[0]!.message}`
          : `${res.updated} removed from target accounts`,
        res.failed.length ? 'danger' : undefined,
      );
      onChange();
    } catch (err) {
      toast(errorText(err), 'danger');
    }
  };
  const rowsOnPage = list?.data ?? [];
  const allTicked = rowsOnPage.length > 0 && rowsOnPage.every((r) => selected.has(r.id));
  const colSpan = 1 + 1 + columns.length;

  const pages = list ? Math.max(1, Math.ceil(list.total / PAGE_SIZE)) : 1;
  const money = (v: number) => formatFigure(v, 'currency', metrics?.currency ?? 'USD');

  return (
    <>
      <div className="ta-views">
        {VIEWS.map((v) => (
          <button
            type="button"
            key={v.key}
            className={cn('ta-view', view === v.key && 'is-active')}
            onClick={() => {
              setView(v.key);
              setPage(1);
            }}
          >
            {v.label}
          </button>
        ))}
        <button
          type="button"
          className="link ta-views__toggle"
          onClick={() => setShowMetrics((s) => !s)}
        >
          {showMetrics ? 'Hide metrics' : 'Show metrics'}
        </button>
      </div>

      {showMetrics ? (
        <div className="ta-metrics">
          {[
            ['Target accounts', metrics?.targetAccounts],
            ['Accounts missing decision makers', metrics?.missingDecisionMakers],
            ['Accounts with open deals', metrics?.withOpenDeals],
            ['Open deal value', metrics ? money(metrics.openDealValue) : undefined],
            ['Missing any buying role', metrics?.missingBuyingRoles],
          ].map(([label, value]) => (
            <div className="ta-metric" key={String(label)}>
              <span className="ta-metric__label">{label}</span>
              <span className="ta-metric__value">
                {value === undefined
                  ? '—'
                  : typeof value === 'number'
                    ? value.toLocaleString()
                    : value}
              </span>
            </div>
          ))}
        </div>
      ) : null}

      {dialog}
      <div className="ta-toolbar">
        <input
          type="search"
          className="ta-search"
          placeholder="Search companies"
          value={q}
          onChange={(e) => {
            setQ(e.target.value);
            setPage(1);
          }}
        />
        <span className="ta-toolbar__spacer" />
        {selected.size ? (
          <button type="button" className="btn-crm btn-crm--outline" onClick={() => void remove()}>
            Remove {selected.size} from target accounts
          </button>
        ) : null}
        <span className="ta-cols" ref={columnsMenu}>
          <button
            type="button"
            className="btn-crm btn-crm--outline"
            aria-expanded={editColumns}
            onClick={() => setEditColumns((o) => !o)}
          >
            Edit columns
          </button>
          {editColumns ? (
            <div className="ta-cols__menu" role="group" aria-label="Columns">
              {COLUMNS.map((c) => (
                <label key={c.key}>
                  <input
                    type="checkbox"
                    checked={show(c.key)}
                    onChange={() => toggleColumn(c.key)}
                  />
                  {c.label}
                </label>
              ))}
            </div>
          ) : null}
        </span>
        <a
          className="btn-crm btn-crm--outline"
          href={targetAccountsExportUrl({ view, q: query })}
          download
        >
          Export
        </a>
      </div>

      <div className="ta-table-wrap">
        <table className="ta-table">
          <thead>
            <tr>
              <th className="ta-check">
                <input
                  type="checkbox"
                  aria-label="Select all on this page"
                  checked={allTicked}
                  onChange={() =>
                    setSelected(allTicked ? new Set() : new Set(rowsOnPage.map((r) => r.id)))
                  }
                />
              </th>
              <th>Name</th>
              {show('tier') ? <th>Ideal Customer Profile Tier</th> : null}
              {show('stage') ? <th>Lifecycle stage</th> : null}
              {show('roles') ? <th className="ta-num">Contacts with Buying Roles</th> : null}
              {show('deals') ? <th className="ta-num">Open Deals</th> : null}
              {show('value') ? <th className="ta-num">Open deal value</th> : null}
              {show('owner') ? <th>Company owner</th> : null}
              {show('last') ? <th>Last engagement</th> : null}
              {show('next') ? <th>Next activity</th> : null}
            </tr>
          </thead>
          <tbody>
            {error ? (
              <tr>
                <td colSpan={colSpan} className="ta-empty" role="alert">
                  Target accounts could not be loaded: {error}
                </td>
              </tr>
            ) : !list ? (
              <tr>
                <td colSpan={colSpan} className="ta-empty">
                  Loading target accounts…
                </td>
              </tr>
            ) : !list.data.length ? (
              <tr>
                <td colSpan={colSpan} className="ta-empty">
                  {query
                    ? `No target accounts match "${query}".`
                    : view === 'all'
                      ? 'No target accounts yet. Choose target accounts to start.'
                      : 'No target accounts in this view.'}
                </td>
              </tr>
            ) : (
              list.data.map((r) => (
                <tr key={r.id} className={cn(selected.has(r.id) && 'is-selected')}>
                  <td className="ta-check">
                    <input
                      type="checkbox"
                      aria-label={`Select ${r.name}`}
                      checked={selected.has(r.id)}
                      onChange={() =>
                        setSelected((prev) => {
                          const next = new Set(prev);
                          if (next.has(r.id)) next.delete(r.id);
                          else next.add(r.id);
                          return next;
                        })
                      }
                    />
                  </td>
                  <td>
                    <Link className="ta-name" href={`/companies/${r.id}`}>
                      {r.name}
                    </Link>
                  </td>
                  {show('tier') ? (
                    <td>{r.tier ? <span className="ta-tier">{words(r.tier)}</span> : '-'}</td>
                  ) : null}
                  {show('stage') ? <td>{r.lifecycleStage ?? '-'}</td> : null}
                  {show('roles') ? <td className="ta-num">{r.contactsWithBuyingRoles}</td> : null}
                  {show('deals') ? <td className="ta-num">{r.openDeals}</td> : null}
                  {show('value') ? <td className="ta-num">{money(r.openDealValue)}</td> : null}
                  {show('owner') ? <td>{r.ownerName ?? 'Unassigned'}</td> : null}
                  {show('last') ? <td>{ago(r.lastActivityAt, now)}</td> : null}
                  {show('next') ? (
                    <td title={r.nextActivityType ? words(r.nextActivityType) : undefined}>
                      {until(r.nextActivityAt, now)}
                    </td>
                  ) : null}
                </tr>
              ))
            )}
          </tbody>
        </table>
      </div>
      <footer className="ta-foot">
        <span className="ta-count">
          {list
            ? `${list.total.toLocaleString()} target account${list.total === 1 ? '' : 's'}`
            : ''}
        </span>
        {pages > 1 ? (
          <span className="ta-pager">
            <button type="button" disabled={page === 1} onClick={() => setPage(page - 1)}>
              &lt; Prev
            </button>
            <span>
              {page} of {pages}
            </span>
            <button type="button" disabled={page === pages} onClick={() => setPage(page + 1)}>
              Next &gt;
            </button>
          </span>
        ) : null}
      </footer>
    </>
  );
}

const ANALYZE_PERIODS = [
  { key: 'thisQuarter', label: 'This quarter' },
  { key: 'thisMonth', label: 'This month' },
  { key: 'last30', label: 'Last 30 days' },
  { key: 'thisYear', label: 'This year' },
] as const;

function Bars({
  rows,
  format,
}: {
  rows: { label: string; value: number }[];
  format: (v: number) => string;
}) {
  if (!rows.length || rows.every((r) => r.value === 0)) {
    return (
      <p className="ta-empty">
        There is no data to show in this time frame. Try changing the date range.
      </p>
    );
  }
  const max = Math.max(...rows.map((r) => r.value), 1);
  return (
    <div className="sa-bars">
      {rows.map((r) => (
        <div className="sa-bar" key={r.label}>
          <span className="sa-bar__label" title={r.label}>
            {r.label}
          </span>
          <span className="sa-bar__track">
            <span className="sa-bar__fill" style={{ width: `${(r.value / max) * 100}%` }} />
          </span>
          <span className="sa-bar__value">{format(r.value)}</span>
        </div>
      ))}
    </div>
  );
}

function AnalyzeTab() {
  const [period, setPeriod] = useState<(typeof ANALYZE_PERIODS)[number]['key']>('thisQuarter');
  const [data, setData] = useState<TargetAccountAnalyze | null>(null);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    let alive = true;
    setData(null);
    analyzeTargetAccounts(periodRange(period)).then(
      (res) => {
        if (!alive) return;
        setData(res);
        setError(null);
      },
      (err: unknown) => alive && setError(errorText(err)),
    );
    return () => {
      alive = false;
    };
  }, [period]);

  if (error)
    return (
      <p className="ta-empty" role="alert">
        The analysis could not be loaded: {error}
      </p>
    );
  const money = (v: number) => formatFigure(v, 'currency', data?.currency ?? 'USD');
  const count = (v: number) => v.toLocaleString();

  return (
    <>
      <div className="ta-toolbar">
        <label className="sa-period">
          <span>Date range</span>
          <select value={period} onChange={(e) => setPeriod(e.target.value as typeof period)}>
            {ANALYZE_PERIODS.map((p) => (
              <option key={p.key} value={p.key}>
                {p.label}
              </option>
            ))}
          </select>
        </label>
      </div>
      {!data ? (
        <p className="ta-empty">Loading analysis…</p>
      ) : (
        <div className="ta-grid">
          <section className="ta-card ta-card--wide">
            <h2>Activity totals on target accounts</h2>
            <div className="ta-metrics ta-metrics--flat">
              {Object.entries(data.activities.byType).length ? (
                Object.entries(data.activities.byType).map(([type, n]) => (
                  <div className="ta-metric" key={type}>
                    <span className="ta-metric__label">{words(type)}</span>
                    <span className="ta-metric__value">{n.toLocaleString()}</span>
                  </div>
                ))
              ) : (
                <p className="ta-empty">No activities in this time frame.</p>
              )}
            </div>
          </section>
          <section className="ta-card">
            <h2>Open target account pipeline</h2>
            <p className="ta-figure">{money(data.pipeline.open.amount)}</p>
            <p className="ta-muted">
              {data.pipeline.open.count} open deal{data.pipeline.open.count === 1 ? '' : 's'} ·{' '}
              {data.pipeline.created.count} created in the period (
              {money(data.pipeline.created.amount)})
            </p>
          </section>
          <section className="ta-card">
            <h2>Closed target accounts</h2>
            <p className="ta-figure">{money(data.closed.won.amount)}</p>
            <p className="ta-muted">
              {data.closed.won.count} won · {data.closed.lost.count} lost in the period
            </p>
          </section>
          <section className="ta-card">
            <h2>Target accounts by industry</h2>
            <Bars
              rows={data.byIndustry.map((r) => ({
                label: r.industry ?? '(No value)',
                value: r.accounts,
              }))}
              format={count}
            />
          </section>
          <section className="ta-card">
            <h2>Target account totals by rep</h2>
            <Bars
              rows={data.byOwner.map((r) => ({
                label: r.ownerName ?? 'Unassigned',
                value: r.accounts,
              }))}
              format={count}
            />
          </section>
          <section className="ta-card">
            <h2>Target accounts by tier</h2>
            <Bars
              rows={data.byTier.map((r) => ({
                label: r.tier ? words(r.tier) : '(No value)',
                value: r.accounts,
              }))}
              format={count}
            />
          </section>
          <section className="ta-card">
            <h2>Target accounts with no buying roles</h2>
            <p className="ta-figure">{data.missingBuyingRoles.toLocaleString()}</p>
            <p className="ta-muted">of {data.targetAccounts.toLocaleString()} target accounts</p>
          </section>
        </div>
      )}
    </>
  );
}
