import moment from 'moment';
import { useDashboardDayData } from '@/queries/dashboard';
import { Skeleton } from '@/components/UI/Loaders/Skeleton';
import { info } from '@/pagesComponents/Dashboard/constants';
import { DashboardCart } from '@/pagesComponents/Dashboard/DashboardCart';
import { PaperWithGraphic } from '@/pagesComponents/Dashboard/PaperWithGraphic';
import { PieChartGraphic } from '@/pagesComponents/Dashboard/Graphics/PieChartGraphic';
import { SingleAreaChartGraphic } from '@/pagesComponents/Dashboard/Graphics/SingleAreaChartGraphic';
import { HorizontalBarChartGraphic } from '@/pagesComponents/Dashboard/Graphics/HorizontalBarChartGraphic';
import {
  pieChartGraphicData,
} from './constants';
import { DataListBlock } from './DataListBlock';

interface IProps {
  days: string;
}

export const DashboardData: React.FC<IProps> = ({
  days
}) => {
  const {data, isLoading: dashboardLoading } = useDashboardDayData({
    searchDays: +days,
    vehiclesStatus: 0
  })

  const dashboardData = data?.instrumentPanel;

  return (
    <>
      <ul
        className={`mt-[30px] grid justify-between items-center overflow-x-auto whitespace-nowrap scrollbar pb-2 ${dashboardLoading ? 'gap-2' : ''}`}
        style={{
          gridTemplateColumns: `repeat(${info.dashboard.info.length}, 1fr)`,
        }}
      >
        {dashboardLoading ? (
          new Array(info.dashboard.info.length)
            .fill('')
            .map((_, index) => (
              <Skeleton
                key={index}
                className={`w-full ${info.dashboard.classNames.wrapperClassname}`}
              />
            ))
        ) : (
          <>
            {dashboardData?.result === 0 &&
              dashboardData?.info &&
              info.dashboard.info?.map((inf) => {
                const infoData = dashboardData.info;
                let value = infoData[inf.key as keyof typeof infoData] || 0;
                if (inf.key === 'AI_TOTAL') {
                  // При ключе AI_TOTAL нужно высчитывать сумму всех айтемов
                  value = 0;
                  const items = info.dashboard.info;
                  for (let i = 0; i < items.length; i++) {
                    const itemData = infoData[items[i].key as keyof typeof infoData];
                    value +=
                      typeof itemData === 'number' || typeof itemData === 'bigint' ? itemData : 0;
                  }
                }
                return (
                  <DashboardCart
                    key={inf.key}
                    title={inf.title}
                    value={value}
                    className={info.dashboard.classNames.wrapperClassname}
                    contentClassName={`${info.dashboard.classNames.contentClassname} ${inf.borderColor}`}
                  />
                );
              })}
          </>
        )}
      </ul>

      <section className='my-[30px] grid grid-cols-4 gap-8'>
        <DataListBlock />

        <PaperWithGraphic title='Ранг тревог ТС'>
          <HorizontalBarChartGraphic
            data={data?.vehicleArmTop?.vehicleChartsData || []}
            yKey='vehiIdno'
            xKey='alarmCount'
            className='mt-4'
          />
        </PaperWithGraphic>
        <PaperWithGraphic title='Ранг тревог водителя'>
          {/* <RadialBarChartGraphic data={threeLevelGraphicData} className='mt-4' /> */}
          no Data
        </PaperWithGraphic>
        <PaperWithGraphic title='Ранг тревог компании (км)'>
        <HorizontalBarChartGraphic
            data={data?.companyArmTop?.companyChartsData || []}
            yKey='companyName'
            xKey='alarmCount'
            yFormat={(item: string) => {return item.length > 7 ? item.toString().slice(0, 7)+"..." : item}}
            className='mt-4'
          />
        </PaperWithGraphic>
      </section>

      <section className='grid grid-cols-3 gap-8'>
        <PaperWithGraphic title='Ненормальное вождение'>
          <PieChartGraphic
            data={pieChartGraphicData}
            withPercentVisible
            height={222}
            className='mt-9 items-center'
            graphicClassName='min-w-[222px]'
          />
        </PaperWithGraphic>
        <PaperWithGraphic title='Номер тревоги AI'>
          <SingleAreaChartGraphic
            data={data?.instrumentPanelAlarm?.chartsData?.map((el, index) => {
              const item = el[0];
              return {
                ...item,
                countTotal: Object.keys(item).filter((el) => el.endsWith('_count')).reduce((prev, curr) => prev + ((item as any)?.[curr] || 0), 0),
                onlyNotEmps: Object.fromEntries(Object.keys(item).filter((el) => el.endsWith('_count') && (item as any)[el] > 0).map((key) => [key, (item as any)[key]])) as Record<string, number>,
                date: moment(data.instrumentPanelAlarm.interValDate[index]).format("YYYY-MM-DD")
              }
            }).sort((a, b) => +moment(a.date, "YYYY-MM-DD") - +moment(b.date, "YYYY-MM-DD")) || []}
            xKey={'date'}
            yKey={['countTotal']}
            withXAxis
            withYAxis
            height={220}
            id='numberAlarm'
            className='mt-8'
          />
        </PaperWithGraphic>
        <PaperWithGraphic title='Номер обработки сигнала тревоги'>
          <SingleAreaChartGraphic
            data={Object.keys(data?.instrumentPanelAlarmHandleRate?.chartsData || {}).map((key) => {
              return {
                ...data?.instrumentPanelAlarmHandleRate?.chartsData[key],
                date: key,
              }
            }).sort((a, b) => +moment(a.date, "YYYY-MM-DD") - +moment(b.date, "YYYY-MM-DD")) || []}
            xKey={'date'}
            yKey={'alarmCount'}
            withXAxis
            withYAxis
            height={220}
            color='green'
            id='numberSignalAlarm'
            className='mt-8'
          />
        </PaperWithGraphic>
      </section>
    </>
  );
};
