'use client';

// Admin-tools card that surfaces the at-risk count and opens the full panel in a modal.

import React, { useEffect, useState } from 'react';
import styles from '@/app/admin/page.module.css';

interface AtRiskCardProps {
  onClick: () => void;
}

interface AtRiskCountsResponse {
  success: boolean;
  counts?: { missingZo: number; missingSubdomain: number; total: number };
}

export function AtRiskCard({ onClick }: AtRiskCardProps) {
  const [total, setTotal] = useState<number | null>(null);

  useEffect(() => {
    let cancelled = false;
    (async () => {
      try {
        // Counts-only endpoint skips the full dealer findMany — the card just needs the badge number.
        const res = await fetch('/api/admin/at-risk/counts');
        const body = (await res.json()) as AtRiskCountsResponse;
        if (!cancelled && res.ok && body.success && body.counts) {
          setTotal(body.counts.total);
        }
      } catch {
        // Swallow — the card stays clickable; opening the modal surfaces the real error.
      }
    })();
    return () => {
      cancelled = true;
    };
  }, []);

  return (
    <button
      type="button"
      onClick={onClick}
      className={`${styles.adminToolCard} ${styles.adminToolCardButton}`}
    >
      <div className={`${styles.adminToolIcon} ${styles.atRiskIcon}`} aria-hidden="true">
        <svg
          width="24"
          height="24"
          viewBox="0 0 24 24"
          fill="none"
          stroke="currentColor"
          strokeWidth="2"
        >
          <path d="M10.29 3.86 1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z" />
          <line x1="12" y1="9" x2="12" y2="13" />
          <line x1="12" y1="17" x2="12.01" y2="17" />
        </svg>
      </div>
      <div className={styles.adminToolInfo}>
        <h3>
          At-Risk Dealers
          {total !== null && total > 0 && (
            <span data-testid="at-risk-badge" className={styles.atRiskBadge} aria-live="polite">
              {total}
            </span>
          )}
        </h3>
        <p>Dealers missing ZO or subdomain</p>
      </div>
    </button>
  );
}
