import { useMutation, useQuery, useQueryClient } from '@/features/query/react-query';
import {
  NotifyMeButton as NotifyMeButtonView,
  type NotifyMeButtonProps as NotifyMeButtonViewProps,
} from '@/components/ui/NotifyMeButton';
import { Button } from '@/components/ui/primitives/Button';
import { useT } from '@/lib/i18n/react';
import { useAuthGateStore } from '@/lib/stores/auth-gate';
import { authenticatedFetch } from '@/lib/authenticated-fetch';
import { Bell } from 'lucide-react';

export interface NotifyMeButtonProps {
  dealId: string;
  skuId?: string;
  isGuest: boolean;
  dealSlug: string;
  variant?: NotifyMeButtonViewProps['variant'];
  onDismiss?: () => void;
}

export function NotifyMeButton({
  dealId,
  skuId,
  isGuest,
  dealSlug: _dealSlug,
  variant = 'deal',
  onDismiss,
}: NotifyMeButtonProps) {
  const t = useT('back_in_stock');
  const queryClient = useQueryClient();
  const { triggerAuth } = useAuthGateStore();
  const queryKey = ['stock-watch', dealId, skuId ?? null] as const;

  const { data, isLoading } = useQuery({
    queryKey,
    queryFn: async () => {
      const params = new URLSearchParams({ dealId });
      if (skuId) params.set('skuId', skuId);
      const res = await fetch(`/api/stock-watch?${params}`);
      if (!res.ok) throw new Error('Failed to check subscription');
      return res.json() as Promise<{ subscribed: boolean }>;
    },
    staleTime: 60_000,
    enabled: !isGuest,
  });

  const subscribeMutation = useMutation({
    mutationFn: async () => {
      const res = await authenticatedFetch('/api/stock-watch', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ dealId, ...(skuId ? { skuId } : {}) }),
      });
      return res.json();
    },
    onSuccess: () => {
      queryClient.setQueryData(queryKey, { subscribed: true });
      onDismiss?.();
    },
  });

  const unsubscribeMutation = useMutation({
    mutationFn: async () => {
      await authenticatedFetch('/api/stock-watch', {
        method: 'DELETE',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ dealId, ...(skuId ? { skuId } : {}) }),
      });
    },
    onSuccess: () => {
      queryClient.setQueryData(queryKey, { subscribed: false });
      onDismiss?.();
    },
  });

  if (isGuest) {
    return (
      <Button
        variant="secondary"
        iconStart={<Bell size={16} aria-hidden="true" />}
        onClick={() => triggerAuth(() => subscribeMutation.mutate())}
      >
        {t('login_required')}
      </Button>
    );
  }

  return (
    <NotifyMeButtonView
      subscribed={data?.subscribed}
      loading={isLoading || subscribeMutation.isPending || unsubscribeMutation.isPending}
      variant={variant}
      onSubscribe={() => subscribeMutation.mutate()}
      onUnsubscribe={() => unsubscribeMutation.mutate()}
    />
  );
}
