'use client';

import { useParams } from 'next/navigation';
import Link from 'next/link';
import type { Route } from 'next';
import { FileDown } from 'lucide-react';

import { Button } from '@/components/ui/button';
import { cn } from '@/lib/utils';
import { usePermissions } from '@/hooks/use-permissions';
import { rangeToBounds, type DateRange } from '@/lib/analytics/range';

function toIsoLocal(d: Date): string {
  const y = d.getFullYear();
  const m = String(d.getMonth() + 1).padStart(2, '0');
  const day = String(d.getDate()).padStart(2, '0');
  return `${y}-${m}-${day}`;
}

/**
 * Dashboard "Export as PDF" affordance. As of Reports P4 this navigates
 * to the dedicated `/reports/dashboard` builder page (carrying the
 * currently-active range through `?from=YYYY-MM-DD&to=YYYY-MM-DD`)
 * instead of opening an in-dashboard dialog. The dialog body now lives
 * in `DashboardReportBuilder`.
 *
 * Permission-gated client-side on `reports.export`; the server route
 * re-checks via withPermission so a tampered client can't bypass.
 */
export function ExportDashboardPdfButton({
  className,
  initialRange,
}: {
  className?: string;
  /** Carried through to the builder so the rep doesn't re-pick a range
   *  they just chose on the dashboard. */
  initialRange?: DateRange;
} = {}) {
  const { can } = usePermissions();
  const params = useParams<{ portSlug: string }>();
  const portSlug = params?.portSlug ?? '';

  if (!can('reports', 'export')) return null;
  if (!portSlug) return null;

  const search = (() => {
    if (!initialRange) return '';
    const { from, to } = rangeToBounds(initialRange);
    return `?from=${toIsoLocal(from)}&to=${toIsoLocal(to)}`;
  })();
  const href = `/${portSlug}/reports/dashboard${search}` as Route;

  return (
    <Button
      asChild
      variant="ghost"
      size="sm"
      title="Export dashboard as PDF"
      aria-label="Export dashboard as PDF"
      className={cn('h-9 w-9 p-0 text-muted-foreground hover:text-foreground', className)}
    >
      <Link href={href}>
        <FileDown className="h-4 w-4" aria-hidden />
      </Link>
    </Button>
  );
}
