import SimpleBarChart from '@/components/analytics/SimpleBarChart.tsx';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/Card.tsx';
import { Grid } from '@/components/ui/layout';
import MetricItem from '@/components/ui/MetricItem.tsx';
import { useOrganizationStats } from '@/hooks/api/useAdminAPI.ts';
import { useTranslation } from '@/hooks/useI18n.tsx';
import { useMemo } from 'react';

const AdminOrganizationsAnalyticsPage = () => {
  const { t } = useTranslation();
  const { data: stats, isLoading } = useOrganizationStats();

  const bySector = useMemo(() => {
    if (!stats) return [] as Array<{ label: string; value: number }>;
    return Object.entries(stats.bySector || {}).map(([label, value]) => ({ label, value }));
  }, [stats]);

  const bySubtype = useMemo(() => {
    if (!stats) return [] as Array<{ label: string; value: number }>;
    return Object.entries(stats.bySubtype || {}).map(([label, value]) => ({ label, value }));
  }, [stats]);

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold">{t('admin.analytics.organizations.title')}</h1>
          <p className="text-muted-foreground">{t('admin.analytics.organizations.subtitle')}</p>
        </div>
      </div>

      <Grid cols={{ md: 2, lg: 4 }} gap="md">
        <MetricItem label={t('admin.analytics.organizations.total')} value={stats?.total ?? 0} />
        <MetricItem
          label={t('admin.analytics.organizations.verified')}
          value={stats?.verified ?? 0}
        />
        <MetricItem
          label={t('admin.analytics.organizations.pending')}
          value={stats?.pending ?? 0}
        />
        <MetricItem
          label={t('admin.analytics.organizations.newThisMonth')}
          value={stats?.newThisMonth ?? 0}
        />
      </Grid>

      <Grid cols={{ md: 2 }} gap="lg">
        <Card>
          <CardHeader>
            <CardTitle>{t('admin.analytics.organizations.bySector')}</CardTitle>
          </CardHeader>
          <CardContent>
            {isLoading ? (
              <div className="py-8 text-center text-muted-foreground">Loading…</div>
            ) : (
              <SimpleBarChart data={bySector} title={t('admin.analytics.organizations.bySector')} />
            )}
          </CardContent>
        </Card>

        <Card>
          <CardHeader>
            <CardTitle>{t('admin.analytics.organizations.bySubtype')}</CardTitle>
          </CardHeader>
          <CardContent>
            {isLoading ? (
              <div className="py-8 text-center text-muted-foreground">Loading…</div>
            ) : (
              <SimpleBarChart
                data={bySubtype}
                title={t('admin.analytics.organizations.bySubtype')}
              />
            )}
          </CardContent>
        </Card>
      </Grid>
    </div>
  );
};

export default AdminOrganizationsAnalyticsPage;
