'use client';

import { useCallback, useEffect, useState } from 'react';
import { motion } from 'framer-motion';
import { Bell, ShieldCheck, UserPlus } from 'lucide-react';
import { CustomToggle } from '@/app/admin/_components/CustomToggle';
import { getResponseErrorTextWithRequestId } from '@/lib/api-client';

type NotificationsResponse = {
  role: string;
  approvalModeEnabled: boolean;
  notifications: {
    newUserRegistered: boolean;
    pendingUserApproval: boolean;
  };
};

type NotificationsTabProps = {
  isAdmin: boolean;
  setErrorMessage: (message: string) => void;
  setSuccessMessage: (message: string) => void;
  onApprovalModeChanged: (enabled: boolean) => void;
};

export function NotificationsTab({ isAdmin, setErrorMessage, setSuccessMessage, onApprovalModeChanged }: NotificationsTabProps) {
  const [settings, setSettings] = useState<NotificationsResponse | null>(null);
  const [isSaving, setIsSaving] = useState(false);

  const getApiErrorText = useCallback(async (response: Response, fallback: string) => {
    return getResponseErrorTextWithRequestId(response, fallback);
  }, []);

  useEffect(() => {
    let cancelled = false;
    const load = async () => {
      const response = await fetch('/api/admin/notifications', { cache: 'no-store' });
      if (!response.ok) {
        throw new Error(await getApiErrorText(response, 'Не удалось загрузить настройки уведомлений'));
      }
      const data = await response.json() as NotificationsResponse;
      if (!cancelled) {
        setSettings(data);
        onApprovalModeChanged(data.approvalModeEnabled);
      }
    };

    void load().catch((error) => {
      if (!cancelled) {
        setErrorMessage(error instanceof Error ? error.message : 'Не удалось загрузить настройки уведомлений');
      }
    });

    return () => {
      cancelled = true;
    };
  }, [getApiErrorText, onApprovalModeChanged, setErrorMessage]);

  const save = useCallback(async (patch: Record<string, unknown>) => {
    setIsSaving(true);
    setSuccessMessage('');
    try {
      const response = await fetch('/api/admin/notifications', {
        method: 'PATCH',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(patch),
      });
      if (!response.ok) {
        throw new Error(await getApiErrorText(response, 'Не удалось сохранить настройки уведомлений'));
      }
      const data = await response.json() as NotificationsResponse;
      setSettings(data);
      onApprovalModeChanged(data.approvalModeEnabled);
      setErrorMessage('');
      setSuccessMessage('Настройки уведомлений сохранены.');
    } catch (error) {
      setErrorMessage(error instanceof Error ? error.message : 'Не удалось сохранить настройки уведомлений');
    } finally {
      setIsSaving(false);
    }
  }, [getApiErrorText, onApprovalModeChanged, setErrorMessage, setSuccessMessage]);

  if (!settings) {
    return (
      <motion.div key="notifications-loading" initial={{ opacity: 0, y: 10 }} animate={{ opacity: 1, y: 0 }} exit={{ opacity: 0, y: -10 }} className="rounded-2xl border border-white/10 bg-white/[0.02] p-10 text-center text-sm text-gray-400">
        Загрузка настроек уведомлений...
      </motion.div>
    );
  }

  return (
    <motion.div key="notifications" initial={{ opacity: 0, y: 10 }} animate={{ opacity: 1, y: 0 }} exit={{ opacity: 0, y: -10 }} className="mx-auto max-w-4xl space-y-6 pb-10">
      {isAdmin ? (
        <div className="flex items-center justify-between gap-4 rounded-3xl border border-white/5 bg-[#0A0A0A] p-5 shadow-xl">
          <div className="flex min-w-0 items-start gap-3">
            <div className="flex h-10 w-10 shrink-0 items-center justify-center rounded-xl border border-emerald-500/20 bg-emerald-500/10 text-emerald-300">
              <ShieldCheck className="h-5 w-5" />
            </div>
            <div>
              <p className="text-sm font-semibold text-white">Режим одобрения пользователей</p>
              <p className="text-xs text-gray-500">Если включён, новые пользователи ждут ручного одобрения.</p>
            </div>
          </div>
          <CustomToggle
            checked={settings.approvalModeEnabled}
            onChange={(value) => void save({ approvalModeEnabled: value })}
          />
        </div>
      ) : null}

      <div className="grid grid-cols-1 gap-3 md:grid-cols-2">
        <div className="flex items-center justify-between gap-4 rounded-3xl border border-white/5 bg-[#0A0A0A] p-5 shadow-xl">
          <div className="flex min-w-0 items-start gap-3">
            <div className="flex h-10 w-10 shrink-0 items-center justify-center rounded-xl border border-violet-500/20 bg-violet-500/10 text-violet-300">
              <UserPlus className="h-5 w-5" />
            </div>
            <div>
              <p className="text-sm font-semibold text-white">Новая регистрация</p>
              <p className="text-xs text-gray-500">Сообщать вам о каждом новом пользователе.</p>
            </div>
          </div>
          <CustomToggle
            checked={settings.notifications.newUserRegistered}
            onChange={(value) => void save({ notifications: { newUserRegistered: value } })}
          />
        </div>

        {settings.approvalModeEnabled ? (
          <div className="flex items-center justify-between gap-4 rounded-3xl border border-white/5 bg-[#0A0A0A] p-5 shadow-xl">
            <div className="flex min-w-0 items-start gap-3">
              <div className="flex h-10 w-10 shrink-0 items-center justify-center rounded-xl border border-amber-500/20 bg-amber-500/10 text-amber-300">
                <Bell className="h-5 w-5" />
              </div>
              <div>
                <p className="text-sm font-semibold text-white">Ожидает одобрения</p>
                <p className="text-xs text-gray-500">Сообщать вам о пользователях, ожидающих допуска.</p>
              </div>
            </div>
            <CustomToggle
              checked={settings.notifications.pendingUserApproval}
              onChange={(value) => void save({ notifications: { pendingUserApproval: value } })}
            />
          </div>
        ) : null}
      </div>

      {isSaving ? <p className="text-xs text-gray-500">Сохранение...</p> : null}
    </motion.div>
  );
}
