import { Suspense, useEffect } from 'react';

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

import CountryTable from '@/Components/Geographic/CountryTable';
import SiteNav from '@/Components/Navigation/SiteNav';
import { LazyCountryMap } from '@/Components/ui/charts/LazyCharts';
import { EmptyState } from '@/Components/ui/empty-state';
import { Skeleton } from '@/Components/ui/skeleton';
import DashboardLayout from '@/Layouts/DashboardLayout';
import { trackEvent } from '@/lib/analytics';
import { GEOGRAPHIC_ANALYSIS_VIEWED } from '@/lib/event-catalog';

// Loading fallback for charts
const ChartLoader = () => (
  <div className="h-[400px] rounded-lg border bg-card p-4 space-y-3">
    <Skeleton className="h-5 w-40" />
    <Skeleton className="h-[320px] w-full" />
  </div>
);

interface CountryData {
  country: string;
  clicks: number;
  impressions: number;
  ctr: number;
  position: number;
  clicksTrend?: number;
}

interface Props {
  site: {
    id: number;
    name: string;
    domain: string;
  };
  countries: CountryData[];
}

export default function GeographicIndex({ site, countries }: Props) {
  useEffect(() => {
    trackEvent(GEOGRAPHIC_ANALYSIS_VIEWED, { site_id: String(site.id) });
  }, [site.id]);

  const handleCountryClick = (country: string) => {
    router.visit(
      route('geographic.detail', {
        site: site.id,
        country: country,
      }),
    );
  };

  return (
    <>
      <Head title={`${site.name} - Geographic Performance`} />

      <div className="container py-6">
        <SiteNav
          siteId={site.id}
          canAnalyze
          canRecommend
          canCannibalization
          canOpportunityMap
          canGeographic
          canDevice
        />

        <h1 className="text-2xl font-bold tracking-tight">Geographic Performance</h1>
        <p className="mt-1 text-sm text-muted-foreground">
          Traffic metrics by country showing where your audience is located
        </p>

        {countries.length === 0 ? (
          <div className="mt-6">
            <EmptyState
              title="No geographic data yet"
              description="Connect Google Search Console and sync your data to see country-level performance metrics."
            />
          </div>
        ) : (
          <div className="mt-6 space-y-6">
            <section aria-labelledby="country-map" className="rounded-lg border bg-card p-6">
              <h2 id="country-map" className="mb-4 text-lg font-semibold">
                Country Heatmap
              </h2>
              <Suspense fallback={<ChartLoader />}>
                <LazyCountryMap
                  data={countries}
                  height={400}
                  aria-label="Heatmap showing traffic distribution by country"
                />
              </Suspense>
            </section>

            <section aria-labelledby="country-table" className="rounded-lg border bg-card p-6">
              <CountryTable data={countries} onRowClick={handleCountryClick} />
            </section>
          </div>
        )}
      </div>
    </>
  );
}

GeographicIndex.layout = (page: React.ReactNode) => <DashboardLayout>{page}</DashboardLayout>;
