import { Eye } from 'lucide-react';

import { useEffect } from 'react';

import { Head, Link, usePage } from '@inertiajs/react';

import { Logo, TextLogo } from '@/Components/branding/Logo';
import ReportPreview from '@/Components/Reports/ReportPreview';
import { ThemeToggle } from '@/Components/theme';
import { Alert, AlertDescription } from '@/Components/ui/alert';
import { Badge } from '@/Components/ui/badge';
import { Button } from '@/Components/ui/button';
import { hasAnalyticsConsent, trackProductEvent } from '@/lib/analytics';
import { CTA_CLICKED, SHARED_REPORT_VIEWED } from '@/lib/event-catalog';
import { type Branding, type PageProps } from '@/types';

interface Report {
  id: number;
  name: string;
  sections: string[];
  filters: Record<string, unknown>;
  status: string;
  generated_at: string | null;
  data: Record<string, unknown> | null;
}

interface Site {
  name: string;
  domain: string;
}

interface SharedLink {
  view_count: number;
}

interface Props {
  report: Report;
  site: Site;
  shared_link: SharedLink;
}

export default function View({ report, site, shared_link: sharedLink }: Props) {
  const { auth } = usePage<PageProps>().props;
  const branding = report.data?.branding as Branding | null | undefined;
  const showRankwizBranding = !branding?.remove_rankwiz_branding;

  // Consent is sampled once on mount (and again if report.id or auth.user changes).
  // The CookieConsent banner is shown before this page renders for visitors
  // without prior consent, so consent state is stable by the time this effect runs.
  // If the consent infrastructure ever becomes asynchronous or post-render, add a
  // reactive consent value to the dependency array here to avoid missing the event.
  useEffect(() => {
    if (!hasAnalyticsConsent()) {
      return;
    }
    trackProductEvent(SHARED_REPORT_VIEWED, {
      report_id: String(report.id),
      is_authenticated: Boolean(auth?.user),
    });
  }, [report.id, auth?.user]);

  return (
    <>
      <Head title={`${report.name} - Shared Report`} />

      <div className="min-h-screen bg-background">
        {/* Header */}
        <header className="border-b bg-card">
          <div className="container mx-auto px-4 py-4 flex items-center justify-between">
            {showRankwizBranding ? (
              <div className="flex items-center gap-3">
                <Logo className="h-8 w-8" />
                <TextLogo className="font-bold text-lg" />
              </div>
            ) : branding?.logo_url ? (
              <img
                src={branding.logo_url}
                alt={branding.company_name ?? 'Company logo'}
                className="h-8 max-w-[200px] object-contain"
              />
            ) : (
              <span className="font-bold text-lg" style={{ color: branding?.primary_color }}>
                {branding?.company_name ?? 'Report'}
              </span>
            )}
            <ThemeToggle />
          </div>
        </header>

        {/* Content */}
        <main className="container mx-auto px-4 py-8 max-w-6xl">
          {/* Shared Report Info Banner */}
          <Alert className="mb-6">
            <Eye className="h-4 w-4" />
            <AlertDescription className="flex flex-col sm:flex-row sm:items-center justify-between gap-3">
              <div className="flex items-center gap-2 flex-wrap">
                <span className="text-sm">
                  This is a shared report from <strong>{site.name}</strong>
                </span>
                <Badge variant="secondary" className="text-xs">
                  {sharedLink.view_count} {sharedLink.view_count === 1 ? 'view' : 'views'}
                </Badge>
              </div>
              {showRankwizBranding && (
                <Button asChild variant="outline" size="sm" className="self-start sm:self-auto">
                  <Link
                    href="/"
                    onClick={() =>
                      trackProductEvent(CTA_CLICKED, {
                        cta_text: 'Try RankWiz Free',
                        cta_location: 'shared_report_banner',
                      })
                    }
                  >
                    Try RankWiz Free
                  </Link>
                </Button>
              )}
            </AlertDescription>
          </Alert>

          {/* Report Content */}
          {report.status === 'completed' && report.data ? (
            <ReportPreview report={report} />
          ) : (
            <div className="rounded-lg border bg-card p-12 text-center">
              <h2 className="text-xl font-semibold mb-2">Report Not Available</h2>
              <p className="text-muted-foreground">
                This report is still being generated or encountered an error.
              </p>
            </div>
          )}
        </main>

        {/* Footer */}
        <footer className="border-t bg-card mt-12">
          <div className="container mx-auto px-4 py-8 text-center">
            <p className="text-sm text-muted-foreground">
              Report shared from <span className="font-medium text-foreground">{site.domain}</span>
            </p>
            <p className="text-xs text-muted-foreground mt-2">
              {showRankwizBranding ? (
                <>
                  Powered by{' '}
                  <Link
                    href="/"
                    className="font-semibold text-foreground hover:underline"
                    onClick={() =>
                      trackProductEvent(CTA_CLICKED, {
                        cta_text: 'RankWiz AI',
                        cta_location: 'shared_report_footer',
                      })
                    }
                  >
                    RankWiz AI
                  </Link>
                </>
              ) : (
                <>
                  Powered by{' '}
                  <span className="font-semibold text-foreground">
                    {branding?.company_name ?? 'Your Company'}
                  </span>
                </>
              )}
            </p>
          </div>
        </footer>
      </div>
    </>
  );
}
