import React from 'react';
import { useParams } from 'react-router-dom';
import { useQuery, useQueryClient } from '@tanstack/react-query';
import { HiUserGroup, HiCollection } from 'react-icons/hi';
import { ProjectPageShell } from '@/features/projects/components/ProjectPageShell';
import { ReportPageLayout } from '@/features/projects/components/ReportPageLayout';
import { api } from '@/shared/utils/api';

interface WorkDistributionReport {
  meta: {
    project_id: string;
    report_type: string;
  };
  summary: {
    total_assignees: number;
    total_items: number;
  };
  chart: {
    labels: string[];
    datasets: Array<{
      label: string;
      data: number[];
      backgroundColor: string;
    }>;
  };
  table: {
    headers: string[];
    rows: Array<Record<string, unknown>>;
  };
}

async function fetchWorkDistributionReport(
  projectId: string
): Promise<WorkDistributionReport> {
  const response = await api.get<{ data: WorkDistributionReport }>(
    `/projects/${projectId}/reports/work-distribution`
  );
  return (response as { data: WorkDistributionReport }).data;
}

const WorkDistributionReportPage: React.FC = () => {
  const { id } = useParams<{ id: string }>();
  const queryClient = useQueryClient();

  const { data, isLoading } = useQuery({
    queryKey: ['projects', id, 'reports', 'work-distribution'],
    queryFn: () => fetchWorkDistributionReport(id!),
    enabled: Boolean(id),
  });

  const handleExportCsv = () => {
    window.open(`/api/v1/projects/${id}/reports/export/work_distribution`, '_blank');
  };

  if (!id) return null;

  return (
    <ProjectPageShell projectId={id}>
      {() => (
        <ReportPageLayout
          title="Work Distribution Report"
          subtitle="Analyze how work is distributed across team members"
          isLoading={isLoading}
          isEmpty={!data || data.chart.labels.length === 0}
          emptyMessage="Assign work items to see distribution"
          summaryMetrics={
            data
              ? [
                  {
                    label: 'Team Members',
                    value: data.summary.total_assignees,
                    icon: HiUserGroup,
                  },
                  {
                    label: 'Total Items',
                    value: data.summary.total_items,
                    icon: HiCollection,
                  },
                ]
              : undefined
          }
          chartType="bar"
          chartData={data?.chart}
          chartHeight={350}
          tableData={data?.table}
          onRefresh={() =>
            queryClient.invalidateQueries({
              queryKey: ['projects', id, 'reports', 'work-distribution'],
            })
          }
          onExportCsv={handleExportCsv}
        />
      )}
    </ProjectPageShell>
  );
};

export default WorkDistributionReportPage;
