'use client';

import { cn } from '@/lib/utils/cn';
import Link from 'next/link';
import type { DashboardReportId, DashboardReportWidget, DashboardWidget } from '../types';
import { WidgetView } from '../ui/WidgetView';
import { widgetTitle } from './model';
import { useDropdown } from './useDropdown';

/** The full report page each widget comes from ("Go to report"). */
export const REPORT_PAGE: Record<DashboardReportId, string> = {
  won_by_month: '/reports',
  pipeline_by_stage: '/reports',
  forecast: '/reports',
  targets: '/reports/targets',
  activity: '/reports/activity',
  workflows: '/reports/workflows',
  sequences: '/reports/sequences',
};

export type WidgetAction =
  | 'settings'
  | 'clone'
  | 'rename'
  | 'export'
  | 'move'
  | 'add-dashboard'
  | 'resize'
  | 'earlier'
  | 'later'
  | 'remove'
  | 'edit-note';

type Item = {
  action: WidgetAction;
  label: string;
  divider?: boolean;
  edit?: boolean;
  danger?: boolean;
};

/**
 * QA #587: one report widget with the design's card actions (refresh, report settings and the
 * "More report actions" menu, reports-dashboard.js `initMetricCardControls`). Only the actions our
 * widgets support are listed; "Edit in Report Builder", "Share via", "Change owner", "Set tags"
 * and "Delete" (a report is not a separate thing from its widget yet) are left out.
 */
export function ReportWidgetCard({
  widget,
  shown,
  refreshKey,
  canEdit,
  isFirst,
  isLast,
  onRefresh,
  onAction,
}: {
  widget: DashboardReportWidget;
  /** The widget with the dashboard filters applied. */
  shown: DashboardReportWidget;
  refreshKey: number;
  canEdit: boolean;
  isFirst: boolean;
  isLast: boolean;
  onRefresh: () => void;
  onAction: (action: WidgetAction) => void;
}) {
  const menu = useDropdown();
  const title = widgetTitle(widget);
  const full = widget.position.w >= 12;
  const items: Item[] = [
    { action: 'clone', label: 'Clone', edit: true },
    { action: 'rename', label: 'Rename', edit: true },
    { action: 'export', label: 'Export data' },
    { action: 'move', label: 'Move', divider: true, edit: true },
    { action: 'add-dashboard', label: 'Add to dashboard' },
    {
      action: 'resize',
      label: full ? 'Resize to half width' : 'Resize to full width',
      divider: true,
      edit: true,
    },
    ...(isFirst ? [] : [{ action: 'earlier' as const, label: 'Move up', edit: true }]),
    ...(isLast ? [] : [{ action: 'later' as const, label: 'Move down', edit: true }]),
    { action: 'remove', label: 'Remove from dashboard', divider: true, edit: true, danger: true },
  ];
  return (
    <div className="dashboard-widget-card" aria-label={title}>
      <div className="reports-card-actions" aria-label={`${title} actions`}>
        <button
          type="button"
          className="reports-card-actions__button"
          aria-label="Refresh report"
          title="Refresh report"
          onClick={onRefresh}
        >
          <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" aria-hidden="true">
            <path d="M21 12a9 9 0 0 0-9-9 9.75 9.75 0 0 0-6.74 2.74L3 8" />
            <path d="M3 3v5h5" />
            <path d="M3 12a9 9 0 0 0 9 9 9.75 9.75 0 0 0 6.74-2.74L21 16" />
            <path d="M16 16h5v5" />
          </svg>
        </button>
        {canEdit ? (
          <button
            type="button"
            className="reports-card-actions__button"
            aria-label="Report settings"
            title="Report settings"
            onClick={() => onAction('settings')}
          >
            <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" aria-hidden="true">
              <path d="M10 5H3" />
              <path d="M12 19H3" />
              <path d="M14 3v4" />
              <path d="M16 17v4" />
              <path d="M21 12h-9" />
              <path d="M21 19h-5" />
              <path d="M21 5h-7" />
              <path d="M8 10v4" />
              <path d="M8 12H3" />
            </svg>
          </button>
        ) : null}
        <div className="dropdown reports-card-actions__dropdown" ref={menu.ref}>
          <button
            type="button"
            className="reports-card-actions__button"
            aria-label="More report actions"
            title="More report actions"
            aria-haspopup="menu"
            aria-expanded={menu.open}
            onClick={menu.toggle}
          >
            <svg viewBox="0 0 24 24" aria-hidden="true">
              <circle cx="12" cy="5" r="1.5" fill="currentColor" stroke="none" />
              <circle cx="12" cy="12" r="1.5" fill="currentColor" stroke="none" />
              <circle cx="12" cy="19" r="1.5" fill="currentColor" stroke="none" />
            </svg>
          </button>
          <div className="dropdown__menu reports-widget-menu" role="menu" hidden={!menu.open}>
            <Link
              href={
                widget.reportId === 'saved_report'
                  ? `/reports/library/${encodeURIComponent(widget.filters.savedReportId ?? '')}`
                  : REPORT_PAGE[widget.reportId]
              }
              className="dropdown__item reports-widget-menu__item"
              role="menuitem"
            >
              <span className="reports-widget-menu__label">Go to report</span>
            </Link>
            {items
              .filter((item) => canEdit || !item.edit)
              .map((item) => (
                <span key={item.action} style={{ display: 'contents' }}>
                  {item.divider ? (
                    <span className="reports-widget-menu__divider" role="separator" />
                  ) : null}
                  <button
                    type="button"
                    className={cn(
                      'dropdown__item reports-widget-menu__item',
                      item.danger ? 'reports-widget-menu__item--danger' : '',
                    )}
                    role="menuitem"
                    onClick={() => {
                      menu.close();
                      onAction(item.action);
                    }}
                  >
                    <span className="reports-widget-menu__label">{item.label}</span>
                  </button>
                </span>
              ))}
          </div>
        </div>
      </div>
      <WidgetView key={refreshKey} widget={shown} />
    </div>
  );
}

/**
 * QA #587 "Add note / rich text": the design's notes card (`.reports-audit-widget`) with its
 * Edit / Delete menu. The text is plain (line breaks kept), never HTML.
 */
export function NoteWidgetCard({
  widget,
  canEdit,
  onAction,
}: {
  widget: DashboardWidget;
  canEdit: boolean;
  onAction: (action: WidgetAction) => void;
}) {
  const menu = useDropdown();
  return (
    <section className="card reports-audit-widget crm-p-3">
      <header className="reports-audit-widget__header crm-d-flex crm-align-items-center crm-justify-content-between crm-gap-2 crm-pb-3 crm-mb-3 crm-border-bottom">
        <h2 className="crm-fs-6 crm-fw-bold crm-text-dark crm-d-flex crm-align-items-center crm-gap-2 crm-m-0">
          <svg
            className="icon iconSize-18 crm-text-primary"
            viewBox="0 0 24 24"
            fill="none"
            stroke="currentColor"
            strokeWidth="1.8"
            strokeLinecap="round"
            strokeLinejoin="round"
            aria-hidden="true"
          >
            <circle cx="12" cy="12" r="9" />
            <path d="M12 11v5M12 8h.01" />
          </svg>
          <span>{widget.title || 'Dashboard note'}</span>
        </h2>
        {canEdit ? (
          <div
            className="dropdown reports-audit-dropdown"
            data-dropdown-align="right"
            ref={menu.ref}
          >
            <button
              type="button"
              className="icon-btn icon-btn--ghost"
              aria-label="Note options"
              aria-haspopup="menu"
              aria-expanded={menu.open}
              onClick={menu.toggle}
            >
              <svg
                className="icon iconSize-18"
                viewBox="0 0 24 24"
                fill="currentColor"
                aria-hidden="true"
              >
                <circle cx="5" cy="12" r="1.6" />
                <circle cx="12" cy="12" r="1.6" />
                <circle cx="19" cy="12" r="1.6" />
              </svg>
            </button>
            <div className="dropdown__menu" role="menu" hidden={!menu.open}>
              {(
                [
                  ['edit-note', 'Edit'],
                  [
                    'resize',
                    widget.position.w >= 12 ? 'Resize to half width' : 'Resize to full width',
                  ],
                  ['move', 'Move'],
                ] as const
              ).map(([action, label]) => (
                <button
                  key={action}
                  className="dropdown__item"
                  type="button"
                  role="menuitem"
                  onClick={() => {
                    menu.close();
                    onAction(action);
                  }}
                >
                  {label}
                </button>
              ))}
              <button
                className="dropdown__item dropdown__item--danger"
                type="button"
                role="menuitem"
                onClick={() => {
                  menu.close();
                  onAction('remove');
                }}
              >
                Delete
              </button>
            </div>
          </div>
        ) : null}
      </header>
      <div
        className="reports-audit-scroll"
        style={{ whiteSpace: 'pre-wrap', overflowWrap: 'anywhere' }}
      >
        {widget.text}
      </div>
    </section>
  );
}
