'use client';

import { useEffect, useState } from 'react';
import { Alert } from '@/components/crm/Alert';
import { CrmModal, ModalHeader } from '@/components/crm/FormDrawer';
import { limitBarWidth } from '@/features/data-model/limits';
import { fmt } from '@/features/data-model/model';
import { getListLimits, type ListLimits } from '@/features/lists/api.client';
import { errorText } from '@/lib/api/errors';

/**
 * HUB-744: the Segments index's Admin settings › Segment limits. Live active and static segments
 * against their limits (2,100 each, as HubSpot), as the API counts and enforces them; segments
 * imports make are outside the limits and shown apart. The bars are the design's Segment limits
 * (segments.php, Create segment's first step: `.seg-limit-*`).
 */
export function SegmentLimitsModal({ open, onClose }: { open: boolean; onClose: () => void }) {
  const [limits, setLimits] = useState<ListLimits | null>(null);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    if (!open) return;
    let live = true;
    setError(null);
    getListLimits().then(
      (l) => {
        if (live) setLimits(l);
      },
      (err: unknown) => {
        if (live) setError(errorText(err));
      },
    );
    return () => {
      live = false;
    };
  }, [open]);

  return (
    <CrmModal id="segLimitsModal" open={open} onClose={onClose} className="seg-move-modal">
      <ModalHeader id="segLimitsModal" title="Segment limits" onClose={onClose} />
      <div className="modal__body">
        {error ? <Alert tone="danger">{error}</Alert> : null}
        {limits ? (
          <>
            <LimitItem label="Active segments used" {...limits.active} />
            <LimitItem label="Static segments used" {...limits.static} />
            <p className="lp-muted seg-delete-note">
              Segments made by imports don&apos;t count toward these limits ({limits.importLists}{' '}
              now). Deleted segments stop counting when they are deleted.
            </p>
          </>
        ) : error ? null : (
          <p className="lp-muted">Loading…</p>
        )}
      </div>
      <div className="modal__footer">
        <button type="button" className="lp-btn lp-btn--outline" onClick={onClose}>
          Close
        </button>
      </div>
    </CrmModal>
  );
}

/** segments.php `.seg-limit-item`: "Active segments used", "45 of 2,100" and its bar. */
function LimitItem({ label, used, limit }: { label: string; used: number; limit: number }) {
  return (
    <div className="seg-limit-item">
      <div className="seg-limit-head">
        <span>{label}</span>
        <strong>
          {fmt(used)} of {fmt(limit)}
        </strong>
      </div>
      <div
        className="seg-limit-bar"
        role="progressbar"
        aria-valuenow={used}
        aria-valuemin={0}
        aria-valuemax={limit}
        aria-label={label}
      >
        <div className="seg-limit-fill" style={{ width: `${limitBarWidth(used, limit)}%` }} />
      </div>
    </div>
  );
}
