'use client';

import { useTranslations } from 'next-intl';
import { useAuth } from '@/lib/hooks/useAuth';
import {
  canViewTasks,
  canViewTreatment,
} from '@/components/shared/permissions';
import { ChartCard } from '@/components/today/ChartCard';
import { TodayBarChart } from '@/components/today/TodayBarChart';
import { ChartCardSkeleton } from '@/components/today/TodaySkeleton';
import type { TodaySummaryCharts } from '@/types/today';

interface TodayChartsSectionProps {
  charts: TodaySummaryCharts;
  loading?: boolean;
  isInitialLoad?: boolean;
  className?: string;
}

export function TodayChartsSection({
  charts,
  loading = false,
  isInitialLoad = false,
  className = '',
}: TodayChartsSectionProps) {
  const t = useTranslations('today');
  const { currentOrganization } = useAuth();
  const orgType = currentOrganization?.type;

  const showTreatmentMix =
    orgType === 'CLINIC' && canViewTreatment(currentOrganization);
  const showTasksByStep =
    orgType === 'LAB' && canViewTasks(currentOrganization);

  if (!showTreatmentMix && !showTasksByStep) {
    return null;
  }

  const treatmentData = charts.treatmentMixWeek ?? [];
  const tasksData = charts.tasksByWorkflowStep ?? [];

  if (isInitialLoad) {
    return (
      <div className={`grid grid-cols-1 gap-4 ${className}`}>
        {showTreatmentMix ? <ChartCardSkeleton /> : null}
        {showTasksByStep ? <ChartCardSkeleton /> : null}
      </div>
    );
  }

  const chartCount = (showTreatmentMix ? 1 : 0) + (showTasksByStep ? 1 : 0);

  return (
    <div
      className={`grid grid-cols-1 ${chartCount > 1 ? 'lg:grid-cols-2' : ''} gap-4 ${loading ? 'opacity-70 transition-opacity' : ''} ${className}`}
    >
      {showTreatmentMix ? (
        <ChartCard
          title={t('chartTreatmentMixTitle')}
          subtitle={t('chartTreatmentMixSubtitle')}
          isEmpty={treatmentData.length === 0}
          emptyMessage={t('chartEmpty')}
        >
          <TodayBarChart data={treatmentData} />
        </ChartCard>
      ) : null}

      {showTasksByStep ? (
        <ChartCard
          title={t('chartTasksByStepTitle')}
          subtitle={t('chartTasksByStepSubtitle')}
          isEmpty={tasksData.length === 0}
          emptyMessage={t('chartEmpty')}
        >
          <TodayBarChart data={tasksData} />
        </ChartCard>
      ) : null}
    </div>
  );
}
