
"use client";

import React, { useState, useEffect, useCallback, Suspense, useMemo } from 'react';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle, CardDescription, CardFooter } from '@/components/ui/card';
import { TableHeader, TableRow, TableHead, TableCell, TableBody } from "@/components/ui/table";
import type { DataItem, CountInfo } from '@/types';
import { Printer, AlertTriangle, BarChart3, Clock, CheckSquare, Info, ClipboardX as ReportClipboardXIcon, Download, Loader2 } from 'lucide-react';
import { useToast } from '@/hooks/use-toast';
import { format } from 'date-fns';
import { useTheme } from 'next-themes';
import { useAuth } from '@/contexts/AuthContext'; // Import useAuth
import { useRouter } from 'next/navigation'; // Import useRouter


interface FinishEstimatorHistoryEntry {
  id: string;
  timestamp: number;
  totalLocations: number;
  completedLocations: number;
  locationsToSkip: number;
  startTime: string;
  breakDuration: number;
  currentTimeInput?: string;
  endTime: string;
  calculatedTimePerLocation: number;
  progressPercentage: number;
  remainingLocationsToCount: number;
}

interface ScanCheckHistoryEntry {
  id: string;
  timestamp: number;
  inputs: {
    unitsCounted: number;
    unitsChecked: number;
    currentErrors: number;
    newErrors: number;
  };
  outputs: {
    accuracyPercentage: string;
    currentAccuracyPercentage: string;
    checkPercentage: string;
    newCheckPercentage: string;
    totalErrors: number;
    effectiveUnitsCheckedAfterNewErrors: number;
  };
}

interface ErrorTrackerRecord {
  id: string;
  location: string;
  counterId: string;
  counterName: string;
  errors: number;
  notes: string;
  timestamp: number;
}

const LOCAL_STORAGE_KEY_BREAKDOWN_ITEMS = 'breakdownItems';
const LOCAL_STORAGE_KEY_ESTIMATOR_HISTORY = 'finishEstimatorHistory';
const LOCAL_STORAGE_KEY_ACCURACY_HISTORY = 'scanCheckAccuracyHistory';
const LOCAL_STORAGE_KEY_ERROR_RECORDS = 'countErrorTrackerRecords';
const LOCAL_STORAGE_KEY_COUNT_INFO = 'countToolHubInfo';


function ReportPageContent() {
  const [breakdownItems, setBreakdownItems] = useState<DataItem[]>([]);
  const [estimatorHistory, setEstimatorHistory] = useState<FinishEstimatorHistoryEntry[]>([]);
  const [accuracyHistory, setAccuracyHistory] = useState<ScanCheckHistoryEntry[]>([]);
  const [errorTrackerRecords, setErrorTrackerRecords] = useState<ErrorTrackerRecord[]>([]);
  const [countInfo, setCountInfo] = useState<CountInfo | null>(null);
  const [isLoading, setIsLoading] = useState(true);
  const [reportGeneratedAt, setReportGeneratedAt] = useState<Date | null>(null);
  const [isDownloadingPdf, setIsDownloadingPdf] = useState(false);
  const { toast } = useToast();
  const { theme: userThemePreference, setTheme, resolvedTheme } = useTheme();
  
  const { user, isLoading: isAuthLoading, isAuthenticated } = useAuth();
  const router = useRouter();

  const loadData = useCallback(() => {
    setIsLoading(true);
    try {
      const storedBreakdownItems = localStorage.getItem(LOCAL_STORAGE_KEY_BREAKDOWN_ITEMS);
      setBreakdownItems(storedBreakdownItems ? JSON.parse(storedBreakdownItems) : []);

      const storedEstimatorHistory = localStorage.getItem(LOCAL_STORAGE_KEY_ESTIMATOR_HISTORY);
      if (storedEstimatorHistory) {
        const parsedEstimatorHistory: FinishEstimatorHistoryEntry[] = JSON.parse(storedEstimatorHistory);
        parsedEstimatorHistory.sort((a, b) => b.timestamp - a.timestamp);
        setEstimatorHistory(parsedEstimatorHistory);
      } else {
        setEstimatorHistory([]);
      }

      const storedAccuracyHistory = localStorage.getItem(LOCAL_STORAGE_KEY_ACCURACY_HISTORY);
      if (storedAccuracyHistory) {
        const parsedAccuracyHistory: ScanCheckHistoryEntry[] = JSON.parse(storedAccuracyHistory);
        parsedAccuracyHistory.sort((a, b) => b.timestamp - a.timestamp);
        setAccuracyHistory(parsedAccuracyHistory);
      } else {
        setAccuracyHistory([]);
      }

      const storedErrorRecords = localStorage.getItem(LOCAL_STORAGE_KEY_ERROR_RECORDS);
      if (storedErrorRecords) {
        const parsedErrorRecords: ErrorTrackerRecord[] = JSON.parse(storedErrorRecords);
        parsedErrorRecords.sort((a, b) => b.timestamp - a.timestamp);
        setErrorTrackerRecords(parsedErrorRecords);
      } else {
        setErrorTrackerRecords([]);
      }

      const storedCountInfo = localStorage.getItem(LOCAL_STORAGE_KEY_COUNT_INFO);
      if (storedCountInfo) {
        const parsedInfo = JSON.parse(storedCountInfo);
        setCountInfo({
          ...parsedInfo,
          week1Units: parsedInfo.week1Units === null ? undefined : (Number(parsedInfo.week1Units) || undefined),
          sohUnits: parsedInfo.sohUnits === null ? undefined : (Number(parsedInfo.sohUnits) || undefined),
        });
      } else {
        setCountInfo(null);
      }
      setReportGeneratedAt(new Date());

    } catch (error) {
      console.error("Error loading data from localStorage for report:", error);
      toast({
        title: "Error Loading Report Data",
        description: "Could not load data from your browser's storage.",
        variant: "destructive",
      });
      setBreakdownItems([]);
      setEstimatorHistory([]);
      setAccuracyHistory([]);
      setErrorTrackerRecords([]);
      setCountInfo(null);
      setReportGeneratedAt(null);
    }
    setIsLoading(false);
  }, [toast]);

  useEffect(() => {
    if (!isAuthLoading && !isAuthenticated) {
        router.push('/'); // Or a login page
    } else if (!isAuthLoading && isAuthenticated) {
        loadData();
        const handleStorageChange = (event: StorageEvent) => {
          if (
            event.key === LOCAL_STORAGE_KEY_BREAKDOWN_ITEMS ||
            event.key === LOCAL_STORAGE_KEY_ESTIMATOR_HISTORY ||
            event.key === LOCAL_STORAGE_KEY_ACCURACY_HISTORY ||
            event.key === LOCAL_STORAGE_KEY_ERROR_RECORDS ||
            event.key === LOCAL_STORAGE_KEY_COUNT_INFO ||
            event.key === null 
          ) {
            loadData();
          }
        };
        window.addEventListener('storage', handleStorageChange);
        return () => {
          window.removeEventListener('storage', handleStorageChange);
        };
    }
  }, [loadData, isAuthLoading, isAuthenticated, router]);

  const handlePrint = () => {
    window.print();
  };

  const generatePdfFilename = () => {
    if (countInfo && countInfo.countDate && countInfo.clientName && countInfo.siteName) {
      try {
         if (countInfo.countDate && !isNaN(new Date(countInfo.countDate + 'T00:00:00').getTime())) {
            const datePart = format(new Date(countInfo.countDate + 'T00:00:00'), 'yyMMdd');
            const clientPart = countInfo.clientName.replace(/[^a-zA-Z0-9_.-]/g, '_').substring(0, 30);
            const sitePart = countInfo.siteName.replace(/[^a-zA-Z0-9_.-]/g, '_').substring(0, 30);
            return `${datePart}_${clientPart}_${sitePart}.pdf`;
        }
      } catch (e) {
        console.error("Error formatting filename:", e);
      }
    }
    return 'CountToolHub_Report.pdf';
  };

  const handleDownloadPdf = async () => {
    setIsDownloadingPdf(true);
    toast({ title: "Generating PDF", description: "Please wait, this may take a moment..." });

    const reportContentElement = document.getElementById('reportCardContent');
    if (!reportContentElement) {
      toast({ title: "Error", description: "Report content element not found.", variant: "destructive" });
      setIsDownloadingPdf(false);
      return;
    }

    const tableWrappers = Array.from(reportContentElement.querySelectorAll<HTMLElement>('.report-table-scroll-wrapper'));
    const originalStyles: Array<{el: HTMLElement, maxHeight: string, overflowY: string, border: string}> = [];

    const printExportHeaderElement = document.getElementById('print-export-header');
    let originalPrintExportHeaderClasses: string | undefined = undefined;

    const originalThemeSetting = userThemePreference || 'system';
    let themeWasSwitched = false;

    try {
      if (resolvedTheme === 'dark') {
        setTheme('light');
        themeWasSwitched = true;
        await new Promise(resolve => setTimeout(resolve, 300));
      }

      tableWrappers.forEach(wrapper => {
        originalStyles.push({
          el: wrapper,
          maxHeight: wrapper.style.maxHeight,
          overflowY: wrapper.style.overflowY,
          border: wrapper.style.border
        });
        wrapper.style.maxHeight = 'none';
        wrapper.style.overflowY = 'visible';
        wrapper.style.border = 'none'; 
      });

      if (printExportHeaderElement) {
        originalPrintExportHeaderClasses = printExportHeaderElement.className;
        printExportHeaderElement.classList.remove('hidden');
        printExportHeaderElement.classList.add('block', 'text-primary');
      }

      const html2pdfModule = await import('html2pdf.js');
      const html2pdf = html2pdfModule.default;


      if (html2pdf) {
        const pdfFilename = generatePdfFilename();
        const opt = {
          margin:       10,
          filename:     pdfFilename,
          image:        { type: 'jpeg', quality: 0.98 },
          html2canvas:  { scale: 2, useCORS: true, logging: false, scrollY: -window.scrollY, windowWidth: reportContentElement.scrollWidth, windowHeight: reportContentElement.scrollHeight },
          jsPDF:        { unit: 'mm', format: 'a4', orientation: 'portrait' },
          pagebreak:    { mode: ['avoid-all', 'css', 'legacy'] }
        };
        await html2pdf().from(reportContentElement).set(opt).save();
        toast({ title: "PDF Downloaded", description: `Your report has been downloaded as ${pdfFilename}.` });
      } else {
        throw new Error("Failed to load PDF generation library.");
      }
    } catch (error: any) {
      console.error("Error generating PDF:", error);
      toast({ title: "PDF Generation Failed", description: `An error occurred: ${error.message}. Check console for details.`, variant: "destructive" });
    } finally {
      tableWrappers.forEach((wrapper, index) => {
         if (originalStyles[index]) {
            wrapper.style.maxHeight = originalStyles[index].maxHeight;
            wrapper.style.overflowY = originalStyles[index].overflowY;
            wrapper.style.border = originalStyles[index].border;
        }
      });

      if (printExportHeaderElement && originalPrintExportHeaderClasses !== undefined) {
        printExportHeaderElement.className = originalPrintExportHeaderClasses;
      }

      if (themeWasSwitched) {
        setTheme(originalThemeSetting);
      }
      setIsDownloadingPdf(false);
    }
  };

  const latestUnitsCounted = accuracyHistory.length > 0 ? accuracyHistory[0].inputs.unitsCounted : "N/A";
  const mostRecentFinishEstimate = estimatorHistory.length > 0 ? estimatorHistory[0].endTime : "N/A";
  const mostRecentErrorRate = accuracyHistory.length > 0 ? `${accuracyHistory[0].outputs.accuracyPercentage}%` : "N/A";

  const groupedBreakdownItems = useMemo(() => {
    if (!breakdownItems || breakdownItems.length === 0) return {};
    const groups = breakdownItems.reduce((acc, item) => {
      const key = item.originalRangeInput || 'No Specific Location';
      if (!acc[key]) {
        acc[key] = [];
      }
      acc[key].push(item);
      return acc;
    }, {} as Record<string, DataItem[]>);

    for (const key in groups) {
        groups[key].sort((a, b) => {
            const locA = a.location;
            const locB = b.location;

            if (typeof locA === 'number' && typeof locB === 'number') {
                return locA - locB;
            }
            if (typeof locA === 'string' && typeof locB === 'string') {
                const numA = parseInt(locA, 10);
                const numB = parseInt(locB, 10);
                if (!isNaN(numA) && !isNaN(numB) && String(numA) === locA && String(numB) === locB) {
                  return numA - numB;
                }
                return locA.localeCompare(locB);
            }
            if (typeof locA === 'number') return -1; 
            if (typeof locB === 'number') return 1;  
            return 0; 
        });
    }
    return groups;
  }, [breakdownItems]);


  if (isAuthLoading || isLoading) {
    return (
      <div className="container mx-auto p-4 sm:p-6 lg:p-8 flex justify-center items-center min-h-screen print:w-[95%]">
        <Loader2 className="h-12 w-12 text-primary animate-spin" />
        <p className="ml-4 text-muted-foreground">
          {isAuthLoading ? 'Loading authentication...' : 'Loading report data...'}
        </p>
      </div>
    );
  }
  
  if (!isAuthenticated) {
    return (
        <div className="container mx-auto p-4 sm:p-6 lg:p-8 flex flex-col items-center justify-center min-h-[calc(100vh-150px)]">
            <p className="text-lg text-muted-foreground">Redirecting to login...</p>
        </div>
    );
  }

  const allDataEmpty = Object.keys(groupedBreakdownItems).length === 0 && estimatorHistory.length === 0 && accuracyHistory.length === 0 && errorTrackerRecords.length === 0 &&
    (!countInfo || (!countInfo.countDate && !countInfo.clientName && !countInfo.siteName && !countInfo.countManagerName && countInfo.week1Units === undefined && countInfo.sohUnits === undefined));

  return (
    <div className="container mx-auto p-4 sm:p-6 lg:p-8 print:w-[95%]">
      <Card className="mb-8 print:shadow-none print:border-none">
        <CardHeader className="flex flex-row items-start sm:items-center justify-between print:hidden">
          <div>
            <CardTitle className="text-2xl font-bold text-primary">Consolidated Report</CardTitle>
            <CardDescription>A summary of all data from your tools. Data is loaded from browser storage.</CardDescription>
          </div>
          <div className="flex gap-2 mt-2 sm:mt-0">
            <Button onClick={handleDownloadPdf} disabled={isDownloadingPdf} className="print:hidden">
              {isDownloadingPdf ? <Loader2 className="mr-2 h-4 w-4 animate-spin" /> : <Download className="mr-2 h-4 w-4" />}
              Download PDF
            </Button>
            <Button onClick={handlePrint} className="print:hidden">
              <Printer className="mr-2 h-4 w-4" /> Print Report
            </Button>
          </div>
        </CardHeader>
        <CardContent id="reportCardContent" className="print:pt-0">
            <div id="print-export-header" className="hidden print:block text-center text-lg font-semibold my-4 text-primary">
                End of Count Report
            </div>
            {allDataEmpty && (
                 <div className="flex flex-col items-center justify-center text-center p-10 border-2 border-dashed rounded-lg">
                    <AlertTriangle className="h-12 w-12 text-muted-foreground mb-4" />
                    <p className="text-xl font-semibold text-muted-foreground">No Data Available</p>
                    <p className="text-muted-foreground">There is no saved data from any of the tools to display in this report.</p>
                    <p className="text-sm text-muted-foreground mt-2">If you recently cleared data, this page will update shortly.</p>
                </div>
            )}

            {!allDataEmpty && (
              <>
                <section className="mb-8 page-break-avoid">
                  <h2 className="text-xl font-semibold mb-3 text-primary border-b pb-2 flex items-center gap-2"><Info /> Count Information</h2>
                  <div className="grid grid-cols-1 md:grid-cols-2 gap-x-6 gap-y-2 p-4 border rounded-lg bg-muted/30">
                      {countInfo?.countDate && <div><span className="font-medium text-muted-foreground">Count Date:</span> {new Date(countInfo.countDate + 'T00:00:00').toLocaleDateString('en-GB')}</div>}
                      {countInfo?.clientName && <div><span className="font-medium text-muted-foreground">Client Name:</span> {countInfo.clientName}</div>}
                      {countInfo?.siteName && <div><span className="font-medium text-muted-foreground">Site Name:</span> {countInfo.siteName}</div>}
                      {countInfo?.countManagerName && <div><span className="font-medium text-muted-foreground">Count Manager:</span> {countInfo.countManagerName}</div>}
                      {countInfo?.week1Units !== undefined && <div><span className="font-medium text-muted-foreground">Week-1 Units:</span> {countInfo.week1Units.toLocaleString('en-GB')}</div>}
                      {countInfo?.sohUnits !== undefined && <div><span className="font-medium text-muted-foreground">SOH Units:</span> {countInfo.sohUnits.toLocaleString('en-GB')}</div>}
                  </div>
                </section>

                <section className="mb-8 page-break-avoid">
                  <h2 className="text-xl font-semibold mb-3 text-primary border-b pb-2 flex items-center gap-2"><BarChart3 /> Key Metrics Summary</h2>
                  <div className="grid grid-cols-1 md:grid-cols-3 gap-4 p-4 border rounded-lg bg-muted/30">
                      <div className="flex flex-col">
                          <span className="text-sm text-muted-foreground">Most Recent Finish Estimate:</span>
                          <span className="text-lg font-semibold text-primary">{mostRecentFinishEstimate}</span>
                      </div>
                      <div className="flex flex-col">
                          <span className="text-sm text-muted-foreground">Latest Units Counted:</span>
                          <span className="text-lg font-semibold text-primary">{typeof latestUnitsCounted === 'number' ? latestUnitsCounted.toLocaleString('en-GB') : latestUnitsCounted}</span>
                      </div>
                      <div className="flex flex-col">
                          <span className="text-sm text-muted-foreground">Most Recent Error Rate:</span>
                          <span className="text-lg font-semibold text-primary">{mostRecentErrorRate}</span>
                      </div>
                  </div>
                </section>
              </>
            )}

          {estimatorHistory.length > 0 && (
            <section className="mb-8 page-break-avoid">
              <h2 className="text-xl font-semibold mb-3 text-primary border-b pb-2 flex items-center gap-2"><Clock /> Finish Estimator History ({estimatorHistory.length} entries)</h2>
              <div className="report-table-scroll-wrapper max-h-[400px] overflow-y-auto rounded-md border print:max-h-none print:overflow-visible print:border-none">
                <table className="w-full caption-bottom text-sm">
                  <TableHeader>
                    <TableRow>
                      <TableHead>Timestamp</TableHead>
                      <TableHead>Total Loc.</TableHead>
                      <TableHead>Completed</TableHead>
                      <TableHead>Skipped</TableHead>
                      <TableHead>Start Time</TableHead>
                      <TableHead>Break (min)</TableHead>
                      <TableHead>End Time</TableHead>
                      <TableHead>Avg. Time/Loc</TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {estimatorHistory.map((entry) => (
                      <TableRow key={entry.id}>
                        <TableCell>{new Date(entry.timestamp).toLocaleString('en-GB')}</TableCell>
                        <TableCell>{entry.totalLocations}</TableCell>
                        <TableCell>{entry.completedLocations}</TableCell>
                        <TableCell>{entry.locationsToSkip}</TableCell>
                        <TableCell>{entry.startTime}</TableCell>
                        <TableCell>{entry.breakDuration}</TableCell>
                        <TableCell>{entry.endTime}</TableCell>
                        <TableCell>{entry.calculatedTimePerLocation} min</TableCell>
                      </TableRow>
                    ))}
                  </TableBody>
                </table>
              </div>
            </section>
          )}

          {accuracyHistory.length > 0 && (
            <section className="mb-8 page-break-avoid">
              <h2 className="text-xl font-semibold mb-3 text-primary border-b pb-2 flex items-center gap-2"><CheckSquare /> Scan Check Accuracy History ({accuracyHistory.length} entries)</h2>
              <div className="report-table-scroll-wrapper max-h-[400px] overflow-y-auto rounded-md border print:max-h-none print:overflow-visible print:border-none">
                 <table className="w-full caption-bottom text-sm">
                  <TableHeader>
                    <TableRow>
                      <TableHead>Timestamp</TableHead>
                      <TableHead>Units Counted</TableHead>
                      <TableHead>Initial Checked</TableHead>
                      <TableHead>Initial Errors</TableHead>
                      <TableHead>New Errors</TableHead>
                      <TableHead>Total Errors</TableHead>
                       <TableHead>New Accuracy</TableHead>
                      <TableHead>New Check Rate</TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {accuracyHistory.map((entry) => (
                      <TableRow key={entry.id}>
                        <TableCell>{new Date(entry.timestamp).toLocaleString('en-GB')}</TableCell>
                        <TableCell>{entry.inputs.unitsCounted}</TableCell>
                        <TableCell>{entry.inputs.unitsChecked}</TableCell>
                        <TableCell>{entry.inputs.currentErrors}</TableCell>
                        <TableCell>{entry.inputs.newErrors}</TableCell>
                        <TableCell>{entry.outputs.totalErrors}</TableCell>
                        <TableCell>{entry.outputs.accuracyPercentage}%</TableCell>
                        <TableCell>{entry.outputs.newCheckPercentage}%</TableCell>
                      </TableRow>
                    ))}
                  </TableBody>
                </table>
              </div>
            </section>
          )}

          {errorTrackerRecords.length > 0 && (
            <section className="mb-8 page-break-avoid">
              <h2 className="text-xl font-semibold mb-3 text-primary border-b pb-2 flex items-center gap-2"><ReportClipboardXIcon /> Count Error Tracker Records ({errorTrackerRecords.length} entries)</h2>
               <div className="report-table-scroll-wrapper max-h-[400px] overflow-y-auto rounded-md border print:max-h-none print:overflow-visible print:border-none">
                <table className="w-full caption-bottom text-sm">
                  <TableHeader>
                    <TableRow>
                      <TableHead>Timestamp</TableHead>
                      <TableHead>Location</TableHead>
                      <TableHead>Counter ID</TableHead>
                      <TableHead>Counter Name</TableHead>
                      <TableHead>Errors</TableHead>
                      <TableHead>Notes</TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {errorTrackerRecords.map((record) => (
                      <TableRow key={record.id}>
                        <TableCell>{new Date(record.timestamp).toLocaleString('en-GB')}</TableCell>
                        <TableCell>{record.location}</TableCell>
                        <TableCell>{record.counterId}</TableCell>
                        <TableCell>{record.counterName}</TableCell>
                        <TableCell>{record.errors}</TableCell>
                        <TableCell className="whitespace-pre-wrap">{record.notes}</TableCell>
                      </TableRow>
                    ))}
                  </TableBody>
                </table>
              </div>
            </section>
          )}

           {Object.keys(groupedBreakdownItems).length > 0 && (
            <section className="page-break-avoid">
              <h2 className="text-xl font-semibold mb-3 text-primary border-b pb-2">Breakdown Tool Data</h2>
              {Object.entries(groupedBreakdownItems).map(([rangeKey, itemsInRange]) => (
                <div key={rangeKey} className="mb-6">
                  <h3 className="text-md font-semibold my-2 text-primary/80">
                    {rangeKey === 'No Specific Location' || rangeKey === "" ? 'Items with No Specific Location' : `Range/Location: ${rangeKey}`} ({itemsInRange.length} item(s))
                  </h3>
                  <div className="report-table-scroll-wrapper max-h-[400px] overflow-y-auto rounded-md border print:max-h-none print:overflow-visible print:border-none">
                    <table className="w-full caption-bottom text-sm">
                      <TableHeader>
                        <TableRow>
                          <TableHead>Location</TableHead>
                          <TableHead>Aisle</TableHead>
                          <TableHead>Type</TableHead>
                          <TableHead>Original Description</TableHead>
                        </TableRow>
                      </TableHeader>
                      <TableBody>
                        {itemsInRange.map((item) => (
                          <TableRow key={item.id}>
                            <TableCell>{item.location || '-'}</TableCell>
                            <TableCell>{item.aisle || '-'}</TableCell>
                            <TableCell>{item.type || '-'}</TableCell>
                            <TableCell className="whitespace-pre-wrap break-words">{item.description || '-'}</TableCell>
                          </TableRow>
                        ))}
                      </TableBody>
                    </table>
                  </div>
                </div>
              ))}
            </section>
          )}
        </CardContent>
        {!allDataEmpty && (
          <CardFooter className="print:hidden flex justify-between items-center">
            <div className="flex-1">
              {reportGeneratedAt && (
                <p className="text-xs text-muted-foreground">
                  Report generated: {reportGeneratedAt.toLocaleString('en-GB')}
                </p>
              )}
            </div>
            <div className="flex gap-2">
              <Button onClick={handleDownloadPdf} disabled={isDownloadingPdf} className="print:hidden">
                {isDownloadingPdf ? <Loader2 className="mr-2 h-4 w-4 animate-spin" /> : <Download className="mr-2 h-4 w-4" />}
                Download PDF
              </Button>
              <Button onClick={handlePrint} className="print:hidden">
                <Printer className="mr-2 h-4 w-4" /> Print Report
              </Button>
            </div>
          </CardFooter>
        )}
      </Card>
    </div>
  );
}

export default function ConsolidatedReportPage() {
  return (
    <Suspense fallback={<div className="container mx-auto p-4 sm:p-6 lg:p-8 flex justify-center items-center min-h-screen print:w-[95%]"><Loader2 className="h-12 w-12 text-primary animate-spin mr-2" /> <p>Loading report page...</p></div>}>
      <ReportPageContent />
    </Suspense>
  )
}
