import { Download, Filter } from 'lucide-react';

import { useEffect } from 'react';

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

import { FeatureGateTeaser } from '@/Components/billing/FeatureGateTeaser';
import BrandedHeader from '@/Components/BrandedHeader';
import PageHeader from '@/Components/layout/PageHeader';
import SiteNav from '@/Components/Navigation/SiteNav';
import RecommendationRoiTable from '@/Components/Roi/RecommendationRoiTable';
import RoiSummaryCard from '@/Components/Roi/RoiSummaryCard';
import RoiTimelineChart from '@/Components/Roi/RoiTimelineChart';
import { Button } from '@/Components/ui/button';
import { EmptyState } from '@/Components/ui/empty-state';
import DashboardLayout from '@/Layouts/DashboardLayout';
import { trackProductEvent } from '@/lib/analytics';
import { FEATURE_USED, ROI_DASHBOARD_VIEWED } from '@/lib/event-catalog';
import { cn } from '@/lib/utils';
import type { PageProps } from '@/types';
import type { RoiDashboardPageProps } from '@/types/roi';

interface FilterPillProps {
  label: string;
  active: boolean;
  href: string;
}

function FilterPill({ label, active, href }: FilterPillProps) {
  return (
    <Link
      href={href}
      aria-current={active ? 'page' : undefined}
      className={cn(
        'inline-flex items-center rounded-full px-3 py-1.5 text-sm font-medium transition-colors',
        active
          ? 'bg-primary text-primary-foreground'
          : 'bg-muted text-muted-foreground hover:bg-muted/80',
      )}
    >
      {label}
    </Link>
  );
}

function buildFilterUrl(siteId: number, params: Record<string, string | null | undefined>): string {
  const baseUrl = route('sites.roi.index', siteId);
  const searchParams = new URLSearchParams();
  for (const [key, value] of Object.entries(params)) {
    if (value) {
      searchParams.set(key, value);
    }
  }
  const qs = searchParams.toString();
  return qs ? `${baseUrl}?${qs}` : baseUrl;
}

function buildExportUrl(
  siteId: number,
  filters: { action_type: string | null; time_interval: string | null },
): string {
  const baseUrl = route('sites.roi.export', siteId);
  const searchParams = new URLSearchParams();
  if (filters.action_type) searchParams.set('action_type', filters.action_type);
  if (filters.time_interval) searchParams.set('time_interval', filters.time_interval);
  const qs = searchParams.toString();
  return qs ? `${baseUrl}?${qs}` : baseUrl;
}

const ACTION_TYPE_LABELS: Record<string, string> = {
  noindex: 'Noindex',
  content_rewrite: 'AI Draft',
  meta_tag_optimization: 'Meta Tags',
  internal_linking: 'Internal Linking',
  thin_content: 'Thin Content',
  cannibalization_consolidation: 'Cannibalization',
  light_refresh: 'Light Refresh',
  section_refresh: 'Section Refresh',
  full_rewrite: 'Full Rewrite',
  reposition_intent: 'Reposition Intent',
};

const TIME_INTERVAL_LABELS: Record<string, string> = {
  '7': '7 Days',
  '14': '14 Days',
  '30': '30 Days',
  '90': '90 Days',
};

export default function RoiDashboard({
  site,
  summary,
  recommendations,
  timeline_data: timelineData,
  filters,
}: RoiDashboardPageProps) {
  const { branding, plan } = usePage<PageProps>().props;
  const isFreeUser = !plan || plan === 'free';
  const hasData = summary.total_recommendations_tracked > 0;

  useEffect(() => {
    trackProductEvent(ROI_DASHBOARD_VIEWED, { site_id: String(site.id) });
    trackProductEvent(FEATURE_USED, { feature: 'roi_dashboard' });
    // intentional: fire-once page-view events on mount; Inertia props are stable per render
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  return (
    <DashboardLayout>
      <Head title={`${site.name} - ROI Dashboard`} />

      <PageHeader
        title="ROI Dashboard"
        subtitle={`${site.name} · ${site.domain}`}
        actions={
          hasData ? (
            <Button variant="outline" size="sm" asChild>
              <a href={buildExportUrl(site.id, filters)} download>
                <Download className="h-4 w-4 mr-1" />
                Export CSV
              </a>
            </Button>
          ) : undefined
        }
      />

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

        {/* Branded Header */}
        <BrandedHeader
          branding={branding}
          subtitle="ROI Performance Dashboard"
          periodLabel="Recommendation Impact Tracking"
          className="mb-6"
        />

        {/* Pro feature teaser for free users */}
        {isFreeUser && (
          <div className="mb-6">
            <FeatureGateTeaser
              featureName="ROI Tracking"
              description="See exactly how clicks and impressions change after applying each recommendation — click/impression delta, CTR change, and position movement tracked automatically."
              ctaLabel="Unlock ROI Tracking"
            />
          </div>
        )}

        {!hasData ? (
          <EmptyState
            title="No ROI data yet"
            description="Mark recommendations as 'Applied' to start tracking their traffic impact. ROI metrics will appear here after your next GSC sync."
            action={
              <Button asChild>
                <Link href={route('recommendations.index', site.id)}>View Recommendations</Link>
              </Button>
            }
          />
        ) : (
          <>
            {/* Summary Card */}
            <div className="mb-6">
              <RoiSummaryCard summary={summary} primaryColor={branding?.primary_color} />
            </div>

            {/* Filters */}
            <div className="mb-6 space-y-4">
              {/* Action Type Filter */}
              <div>
                <div className="flex items-center gap-2 mb-2">
                  <Filter className="h-4 w-4 text-muted-foreground" />
                  <span className="text-sm font-medium text-muted-foreground">Action Type</span>
                </div>
                <div className="flex flex-wrap gap-2">
                  <FilterPill
                    label="All"
                    active={!filters.action_type}
                    href={buildFilterUrl(site.id, { time_interval: filters.time_interval })}
                  />
                  {Object.entries(ACTION_TYPE_LABELS).map(([type, label]) => (
                    <FilterPill
                      key={type}
                      label={label}
                      active={filters.action_type === type}
                      href={buildFilterUrl(site.id, {
                        action_type: type,
                        time_interval: filters.time_interval,
                      })}
                    />
                  ))}
                </div>
              </div>

              {/* Time Interval Filter */}
              <div>
                <div className="flex items-center gap-2 mb-2">
                  <Filter className="h-4 w-4 text-muted-foreground" />
                  <span className="text-sm font-medium text-muted-foreground">Tracking Period</span>
                </div>
                <div className="flex flex-wrap gap-2">
                  <FilterPill
                    label="All Periods"
                    active={!filters.time_interval}
                    href={buildFilterUrl(site.id, { action_type: filters.action_type })}
                  />
                  {Object.entries(TIME_INTERVAL_LABELS).map(([interval, label]) => (
                    <FilterPill
                      key={interval}
                      label={label}
                      active={filters.time_interval === interval}
                      href={buildFilterUrl(site.id, {
                        action_type: filters.action_type,
                        time_interval: interval,
                      })}
                    />
                  ))}
                </div>
              </div>
            </div>

            {/* Timeline Chart */}
            <div className="mb-6">
              <RoiTimelineChart
                timelineData={timelineData}
                primaryColor={branding?.primary_color}
              />
            </div>

            {/* ROI Table */}
            <div>
              <h2 className="text-lg font-semibold mb-4">Recommendation Performance</h2>
              <RecommendationRoiTable recommendations={recommendations} />
            </div>
          </>
        )}

        {/* Footer - Conditional RankWiz Branding */}
        {hasData && (
          <div className="mt-8 pt-6 border-t text-center">
            {branding?.remove_rankwiz_branding ? (
              <p className="text-sm text-muted-foreground">
                © {new Date().getFullYear()} {branding.company_name || 'Your Company'}. All rights
                reserved.
              </p>
            ) : (
              <p className="text-sm text-muted-foreground">
                {branding?.company_name && (
                  <>
                    © {new Date().getFullYear()} {branding.company_name}. Powered by{' '}
                  </>
                )}
                <span className="font-semibold">RankWiz AI</span>
              </p>
            )}
          </div>
        )}
      </div>
    </DashboardLayout>
  );
}
