import { useMutation, useQueryClient } from '@tanstack/react-query';
import { useEffect, useRef, useState } from 'react';

import { UserService } from '@/client/services/UserService';
import { useUserNotifications } from '@/hooks/user/useUserNotifications';

import { RadioOption, SectionHeading, Toggle } from './primitives';

export function NotificationsTab() {
  const { data: notifs, isLoading, error } = useUserNotifications();
  const queryClient = useQueryClient();

  const [settings, setSettings] = useState({
    email_notifications: true,
    web_notifications: true,
    mention_notifications: true,
    review_notifications: true,
    security_notifications: true,
    marketing_emails: false,
  });
  const [digest, setDigest] = useState('weekly');

  const updateMutation = useMutation({
    mutationFn: (body: Record<string, string | boolean | undefined>) =>
      UserService.userUpdateNotifications({ requestBody: body }),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['user', 'notifications'] });
    },
  });

  const isInitialized = useRef(false);
  useEffect(() => {
    if (notifs && !isInitialized.current) {
      isInitialized.current = true;
      setSettings({
        email_notifications: notifs.email_notifications,
        web_notifications: notifs.web_notifications,
        mention_notifications: notifs.mention_notifications,
        review_notifications: notifs.review_notifications,
        security_notifications: notifs.security_notifications,
        marketing_emails: notifs.marketing_emails,
      });
      setDigest(notifs.digest_frequency?.toLowerCase() ?? 'weekly');
    }
  }, [notifs]);

  function toggle(key: string, value: boolean) {
    setSettings((s) => ({ ...s, [key]: value }));
    updateMutation.mutate({ [key]: value });
  }

  if (isLoading) {
    return (
      <div className="flex items-center gap-2 p-8 text-[14px] text-muted-foreground">
        <span className="inline-block size-4 animate-spin rounded-full border-2 border-border border-t-muted-foreground" />
        Loading…
      </div>
    );
  }

  if (error) {
    return (
      <div className="p-8">
        <div className="rounded-md border border-destructive/40 bg-destructive/10 px-4 py-3 text-[14px] text-destructive">
          Failed to load notification settings.
        </div>
      </div>
    );
  }

  const channels = [
    { key: 'email_notifications', label: 'Email', description: 'Receive notifications via email.' },
    {
      key: 'web_notifications',
      label: 'In-app',
      description: 'Show notifications while using the app.',
    },
  ];

  const subscriptions = [
    { key: 'mention_notifications', label: '@mentions', description: 'When someone mentions you.' },
    {
      key: 'review_notifications',
      label: 'Review requests',
      description: 'When someone requests your review.',
    },
    {
      key: 'security_notifications',
      label: 'Security alerts',
      description: 'Important security notices about your account.',
    },
    {
      key: 'marketing_emails',
      label: 'Product updates',
      description: 'Tips, product news, and feature announcements.',
    },
  ];

  return (
    <div className="px-8 pt-10 pb-8 max-w-[560px]">
      <SectionHeading
        title="Notifications"
        description="Choose when and how you want to be notified."
      />

      <div className="mb-8">
        <h3 className="mb-2 text-[13px] font-semibold text-foreground">Channels</h3>
        <div className="rounded-md border border-border divide-y divide-border/60">
          {channels.map((ch) => (
            <Toggle
              key={ch.key}
              label={ch.label}
              description={ch.description}
              checked={settings[ch.key as keyof typeof settings]}
              onChange={(v) => toggle(ch.key, v)}
            />
          ))}
        </div>
      </div>

      <div className="mb-8">
        <h3 className="mb-2 text-[13px] font-semibold text-foreground">Subscriptions</h3>
        <div className="rounded-md border border-border divide-y divide-border/60">
          {subscriptions.map((sub) => (
            <Toggle
              key={sub.key}
              label={sub.label}
              description={sub.description}
              checked={settings[sub.key as keyof typeof settings]}
              onChange={(v) => toggle(sub.key, v)}
            />
          ))}
        </div>
      </div>

      <div>
        <h3 className="mb-3 text-[13px] font-semibold text-foreground">Digest frequency</h3>
        <div className="space-y-2">
          {[
            { value: 'realtime', label: 'Real-time', description: 'Send immediately.' },
            { value: 'daily', label: 'Daily', description: 'One summary per day.' },
            { value: 'weekly', label: 'Weekly', description: 'One summary per week.' },
            { value: 'never', label: 'Never', description: "Don't send digest emails." },
          ].map((opt) => (
            <RadioOption
              key={opt.value}
              value={opt.value}
              label={opt.label}
              description={opt.description}
              selected={digest === opt.value}
              onChange={() => {
                setDigest(opt.value);
                updateMutation.mutate({
                  digest_frequency: opt.value === 'never' ? undefined : opt.value,
                });
              }}
            />
          ))}
        </div>
      </div>
    </div>
  );
}
