import { usePublicFormReport } from '@/hooks/usePublicFormReport';
import { PublicFormReportGenerator } from '@/components/PublicFormReportGenerator';
import { PublicFormReportPdfExport } from '@/components/PublicFormReportPdfExport';
import { Loader2, AlertCircle } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Dialog, DialogContent, DialogTrigger } from '@/components/ui/dialog';

export function PublicFormReportViewer({ submissionId, triggerLabel = "View Report" }) {
  const { report, loading, error } = usePublicFormReport(submissionId);
  const hasReportData = report && report.report_data;

  return (
    <Dialog>
      <DialogTrigger asChild>
        <Button variant="outline" size="sm" className="text-xs">{triggerLabel}</Button>
      </DialogTrigger>
      <DialogContent className="max-w-4xl h-[90vh] flex flex-col p-0 bg-muted">
        {loading ? (
          <div className="flex items-center justify-center h-full">
            <Loader2 className="w-8 h-8 animate-spin text-primary" />
          </div>
        ) : error ? (
          <div className="flex flex-col items-center justify-center h-full text-destructive p-6">
            <AlertCircle className="w-10 h-10 mb-2" />
            <p>Unable to load report. {error}</p>
          </div>
        ) : !hasReportData ? (
          <div className="flex flex-col items-center justify-center h-full text-muted-foreground p-6">
            <AlertCircle className="w-10 h-10 mb-2" />
            <p>Report data is unavailable or generating.</p>
          </div>
        ) : (
          <>
            <div className="p-4 bg-card border-b flex justify-between items-center shrink-0">
              <h2 className="font-semibold text-lg text-foreground">Submission Report</h2>
              <div className="flex gap-2">
                <Button variant="ghost" size="sm" onClick={() => window.print()}>Print</Button>
                <PublicFormReportPdfExport
                  reportData={report.report_data}
                  templateData={report.public_form_templates}
                />
              </div>
            </div>
            <div className="flex-1 overflow-y-auto p-4 md:p-8">
              <PublicFormReportGenerator report={report} />
            </div>
          </>
        )}
      </DialogContent>
    </Dialog>
  );
}

export default PublicFormReportViewer;
