'use client';

import { useSuspenseQuery } from '@tanstack/react-query';
import { parseAsString, useQueryStates } from 'nuqs';
import { crmDashboardQueryOptions } from '../api/queries';
import { DashboardApprovalMetrics } from './dashboard-approval-metrics';
import { DashboardFilters } from './dashboard-filters';
import { DashboardFollowups } from './dashboard-followups';
import { DashboardFunnel } from './dashboard-funnel';
import { DashboardHotProjects } from './dashboard-hot-projects';
import { DashboardRevenueCards } from './dashboard-revenue-cards';
import { DashboardSalesRanking } from './dashboard-sales-ranking';
import { DashboardSummaryCards } from './dashboard-summary-cards';

export function CrmDashboard({ canExport }: { canExport: boolean }) {
  const [params] = useQueryStates({
    dateFrom: parseAsString,
    dateTo: parseAsString,
    branch: parseAsString,
    salesman: parseAsString,
    projectPartyRole: parseAsString,
    productType: parseAsString
  });

  const filters = {
    dateFrom: params.dateFrom,
    dateTo: params.dateTo,
    branch: params.branch,
    salesman: params.salesman,
    projectPartyRole: params.projectPartyRole,
    productType: params.productType
  };

  const { data } = useSuspenseQuery(crmDashboardQueryOptions(filters));

  return (
    <div className='space-y-6'>
      <DashboardFilters referenceData={data.referenceData} canExport={canExport} />
      <DashboardSummaryCards
        summary={data.summary}
        canViewCommercialData={data.visibility.canViewCommercialData}
      />
      {data.visibility.canViewCommercialData ? (
        <div className='grid gap-6 2xl:grid-cols-[1.35fr_1fr]'>
          <DashboardFunnel steps={data.funnel} />
          <DashboardHotProjects rows={data.hotProjects} />
        </div>
      ) : null}
      {data.visibility.canViewCommercialData ? (
        <DashboardRevenueCards revenueAnalytics={data.revenueAnalytics} />
      ) : null}
      {data.visibility.canViewCommercialData || data.visibility.canViewApprovalData ? (
        <div className='grid gap-6 2xl:grid-cols-[1.2fr_1fr]'>
          {data.visibility.canViewCommercialData ? (
            <DashboardSalesRanking rows={data.salesRanking} />
          ) : null}
          {data.visibility.canViewApprovalData ? (
            <DashboardApprovalMetrics approvals={data.approvals} />
          ) : null}
        </div>
      ) : null}
      <DashboardFollowups followups={data.followups} />
    </div>
  );
}
