// @ts-nocheck
import React, { useEffect, useState } from 'react';
import { Box, H2, Text } from '@adminjs/design-system';
import { ApiClient } from 'adminjs';

type DashboardStats = {
  clinics: number;
  labs: number;
  users: number;
  labCases: number;
};

const StatCard = ({
  label,
  value,
  loading,
}: {
  label: string;
  value?: number;
  loading: boolean;
}) => (
  <Box p="lg" bg="primary20" style={{ flex: 1, minWidth: '140px' }}>
    <Text>{label}</Text>
    <Box mt="default" style={{ fontSize: '2rem', fontWeight: 'bold' }}>
      {loading ? '…' : (value ?? '—')}
    </Box>
  </Box>
);

const Dashboard = () => {
  const [stats, setStats] = useState<DashboardStats | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    const api = new ApiClient();
    api
      .getDashboard()
      .then((response) => {
        setStats(response.data as DashboardStats);
        setError(null);
      })
      .catch(() => {
        setError('Could not load dashboard stats.');
      })
      .finally(() => {
        setLoading(false);
      });
  }, []);

  return (
    <Box variant="grey">
      <Box variant="white" p="xl">
        <H2>DyoLink Admin</H2>
        <Text>Manage clinics, labs, users, and production data.</Text>

        {error ? (
          <Box mt="xl">
            <Text>{error}</Text>
          </Box>
        ) : (
          <Box
            mt="xl"
            style={{ display: 'flex', gap: '20px', flexWrap: 'wrap' }}
          >
            <StatCard label="Clinics" value={stats?.clinics} loading={loading} />
            <StatCard label="Labs" value={stats?.labs} loading={loading} />
            <StatCard label="Users" value={stats?.users} loading={loading} />
            <StatCard
              label="Lab cases"
              value={stats?.labCases}
              loading={loading}
            />
          </Box>
        )}
      </Box>
    </Box>
  );
};

export default Dashboard;
