'use client';

import { useEffect, useState } from 'react';

import { usePathname, useSearchParams } from 'next/navigation';

import ShareButtons from '@/components/ShareButtons';
import { cn } from '@/lib/utils';

interface FloatingShareRailProps {
  title?: string;
  description?: string;
  className?: string;
  layout?: 'vertical' | 'horizontal';
  position?: 'right-center' | 'left-center' | 'bottom-center';
  hideOnMobile?: boolean;
  showFacebook?: boolean;
  showCopyLink?: boolean;
  showEmail?: boolean;
  showNativeShare?: boolean;
  showGoogleCalendar?: boolean;
  eventTitle?: string;
  eventStartDate?: string;
  eventEndDate?: string;
  eventLocation?: string | null;
  eventDescription?: string;
}

export default function FloatingShareRail({
  title,
  description,
  className,
  layout = 'vertical',
  position = 'right-center',
  hideOnMobile = true,
  showFacebook = true,
  showCopyLink = false,
  showEmail = true,
  showNativeShare = true,
  showGoogleCalendar = false,
  eventTitle,
  eventStartDate,
  eventEndDate,
  eventLocation,
  eventDescription,
}: FloatingShareRailProps) {
  const pathname = usePathname();
  const searchParams = useSearchParams();
  const [shareUrl, setShareUrl] = useState('');

  const search = searchParams?.toString() || '';

  useEffect(() => {
    if (!pathname || typeof window === 'undefined') return;
    const query = search ? `?${search}` : '';
    setShareUrl(`${window.location.origin}${pathname}${query}`);
  }, [pathname, search]);

  if (!shareUrl) return null;

  const isVertical = layout === 'vertical';

  return (
    <aside
      className={cn(
        'fixed z-40',
        position === 'right-center'
          ? 'right-0 top-1/2 -translate-y-1/2'
          : position === 'left-center'
            ? 'left-0 top-1/2 -translate-y-1/2'
            : 'left-1/2 bottom-4 -translate-x-1/2',
        hideOnMobile ? 'hidden lg:flex' : 'flex',
        className
      )}
      aria-label="Share this page"
    >
      <div className={cn('overflow-hidden backdrop-blur-sm')}>
        <ShareButtons
          url={shareUrl}
          title={title}
          description={description}
          showFacebook={showFacebook}
          showCopyLink={showCopyLink}
          showEmail={showEmail}
          showNativeShare={showNativeShare}
          showGoogleCalendar={showGoogleCalendar}
          eventTitle={eventTitle}
          eventStartDate={eventStartDate}
          eventEndDate={eventEndDate}
          eventLocation={eventLocation}
          eventDescription={eventDescription}
          styleVariant="filled"
          connected
          vertical={isVertical}
        />
      </div>
    </aside>
  );
}
