import { useEffect, useState } from "react";
import { useNavigate } from "react-router-dom";
import { getDashboardAnalytics, type DashboardAnalytics } from "../../api/adminApi";

export default function AdminDashboard() {
  const navigate = useNavigate();
  const [analytics, setAnalytics] = useState<DashboardAnalytics | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    loadAnalytics();
  }, []);

  async function loadAnalytics() {
    setLoading(true);
    setError(null);
    try {
      const data = await getDashboardAnalytics();
      setAnalytics(data);
    } catch (err: any) {
      setError(err.message || "Failed to load analytics");
    } finally {
      setLoading(false);
    }
  }

  if (loading) {
    return (
      <div className="bf-admin-page">
        <div className="bf-admin-loading">Loading analytics...</div>
      </div>
    );
  }

  if (error) {
    return (
      <div className="bf-admin-page">
        <div className="bf-admin-error">{error}</div>
        <button className="btn" onClick={loadAnalytics}>Retry</button>
      </div>
    );
  }

  if (!analytics) return null;

  const statusColors: Record<string, string> = {
    brace_generated: "#4ade80",
    processing_brace: "#fbbf24",
    brace_failed: "#f87171",
    created: "#60a5fa",
    landmarks_detected: "#a78bfa",
    landmarks_approved: "#34d399",
    analysis_complete: "#22d3ee",
  };

  return (
    <div className="bf-admin-page">
      <div className="bf-admin-header">
        <h1>Admin Dashboard</h1>
        <p className="bf-admin-subtitle">Analytics and system overview</p>
      </div>

      {/* Quick Stats */}
      <div className="bf-admin-stats-grid">
        <div className="bf-admin-stat-card">
          <div className="bf-admin-stat-value">{analytics.cases.total}</div>
          <div className="bf-admin-stat-label">Total Cases</div>
        </div>
        <div className="bf-admin-stat-card">
          <div className="bf-admin-stat-value">{analytics.cases.byStatus.brace_generated || 0}</div>
          <div className="bf-admin-stat-label">Braces Generated</div>
        </div>
        <div className="bf-admin-stat-card">
          <div className="bf-admin-stat-value">{analytics.users.total}</div>
          <div className="bf-admin-stat-label">Total Users</div>
        </div>
        <div className="bf-admin-stat-card">
          <div className="bf-admin-stat-value">{analytics.users.recentLogins}</div>
          <div className="bf-admin-stat-label">Active (7 days)</div>
        </div>
      </div>

      {/* Charts Row */}
      <div className="bf-admin-charts-row">
        {/* Case Status Distribution */}
        <div className="bf-admin-card">
          <h3>Case Status Distribution</h3>
          <div className="bf-admin-status-list">
            {Object.entries(analytics.cases.byStatus).map(([status, count]) => (
              <div key={status} className="bf-admin-status-item">
                <div className="bf-admin-status-bar-container">
                  <div 
                    className="bf-admin-status-bar" 
                    style={{ 
                      width: `${(count / analytics.cases.total) * 100}%`,
                      backgroundColor: statusColors[status] || "#64748b"
                    }}
                  />
                </div>
                <div className="bf-admin-status-label">
                  <span className="bf-admin-status-name">{status.replace(/_/g, " ")}</span>
                  <span className="bf-admin-status-count">{count}</span>
                </div>
              </div>
            ))}
          </div>
        </div>

        {/* Rigo Classification Distribution */}
        <div className="bf-admin-card">
          <h3>Rigo Classification</h3>
          {Object.keys(analytics.rigoDistribution).length > 0 ? (
            <div className="bf-admin-rigo-grid">
              {Object.entries(analytics.rigoDistribution)
                .sort((a, b) => b[1] - a[1])
                .map(([type, count]) => (
                  <div key={type} className="bf-admin-rigo-item">
                    <div className="bf-admin-rigo-type">{type}</div>
                    <div className="bf-admin-rigo-count">{count}</div>
                  </div>
                ))}
            </div>
          ) : (
            <div className="bf-admin-empty">No brace data yet</div>
          )}
        </div>
      </div>

      {/* Cobb Angle Statistics */}
      <div className="bf-admin-card">
        <h3>Cobb Angle Statistics</h3>
        <p className="bf-admin-card-subtitle">
          Based on {analytics.cobbAngles.totalCasesWithAngles} cases with angle data
        </p>
        <div className="bf-admin-cobb-grid">
          {(["PT", "MT", "TL"] as const).map((angle) => (
            <div key={angle} className="bf-admin-cobb-card">
              <div className="bf-admin-cobb-header">{angle}</div>
              <div className="bf-admin-cobb-stats">
                <div className="bf-admin-cobb-stat">
                  <span className="bf-admin-cobb-label">Avg</span>
                  <span className="bf-admin-cobb-value">{analytics.cobbAngles[angle].avg}°</span>
                </div>
                <div className="bf-admin-cobb-stat">
                  <span className="bf-admin-cobb-label">Min</span>
                  <span className="bf-admin-cobb-value">{analytics.cobbAngles[angle].min}°</span>
                </div>
                <div className="bf-admin-cobb-stat">
                  <span className="bf-admin-cobb-label">Max</span>
                  <span className="bf-admin-cobb-value">{analytics.cobbAngles[angle].max}°</span>
                </div>
              </div>
            </div>
          ))}
        </div>
      </div>

      {/* Processing & Body Scan Stats */}
      <div className="bf-admin-charts-row">
        <div className="bf-admin-card">
          <h3>Processing Time</h3>
          {analytics.processingTime.count > 0 ? (
            <div className="bf-admin-processing-stats">
              <div className="bf-admin-processing-stat">
                <span className="bf-admin-processing-label">Average</span>
                <span className="bf-admin-processing-value">
                  {(analytics.processingTime.avg / 1000).toFixed(1)}s
                </span>
              </div>
              <div className="bf-admin-processing-stat">
                <span className="bf-admin-processing-label">Fastest</span>
                <span className="bf-admin-processing-value">
                  {(analytics.processingTime.min / 1000).toFixed(1)}s
                </span>
              </div>
              <div className="bf-admin-processing-stat">
                <span className="bf-admin-processing-label">Slowest</span>
                <span className="bf-admin-processing-value">
                  {(analytics.processingTime.max / 1000).toFixed(1)}s
                </span>
              </div>
            </div>
          ) : (
            <div className="bf-admin-empty">No processing data yet</div>
          )}
        </div>

        <div className="bf-admin-card">
          <h3>Body Scan Usage</h3>
          <div className="bf-admin-bodyscan-stats">
            <div className="bf-admin-bodyscan-chart">
              <div 
                className="bf-admin-bodyscan-fill"
                style={{ height: `${analytics.bodyScan.percentage}%` }}
              />
              <div className="bf-admin-bodyscan-percentage">
                {analytics.bodyScan.percentage}%
              </div>
            </div>
            <div className="bf-admin-bodyscan-legend">
              <div className="bf-admin-bodyscan-item">
                <span className="bf-admin-bodyscan-dot bf-admin-bodyscan-dot--with" />
                <span>With Body Scan: {analytics.bodyScan.withBodyScan}</span>
              </div>
              <div className="bf-admin-bodyscan-item">
                <span className="bf-admin-bodyscan-dot bf-admin-bodyscan-dot--without" />
                <span>X-ray Only: {analytics.bodyScan.withoutBodyScan}</span>
              </div>
            </div>
          </div>
        </div>
      </div>

      {/* Quick Links */}
      <div className="bf-admin-quick-links">
        <button className="bf-admin-link-btn" onClick={() => navigate("/admin/users")}>
          Manage Users →
        </button>
        <button className="bf-admin-link-btn" onClick={() => navigate("/admin/cases")}>
          View All Cases →
        </button>
        <button className="bf-admin-link-btn" onClick={() => navigate("/admin/activity")}>
          Activity Log →
        </button>
      </div>
    </div>
  );
}
