'use client';

import { useEffect, useState } from 'react';
import { Bell, Save } from 'lucide-react';
import { api } from '@/lib/api';

type NotificationType = {
  id: string;
  name: string;
  description: string;
  enabled: boolean;
  customizable: boolean;
  template: string;
};

type NotificationSettingsResponse = {
  data: NotificationType[];
};

export default function NotificationsPage(): React.JSX.Element {
  const [notifications, setNotifications] = useState<NotificationType[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [saving, setSaving] = useState(false);

  useEffect(() => {
    api.get<NotificationSettingsResponse>('/notifications/settings')
      .then((res) => {
        setNotifications(res.data ?? []);
        setError(null);
      })
      .catch((err) => {
        setError(err instanceof Error ? err.message : 'Не удалось загрузить настройки уведомлений');
      })
      .finally(() => setLoading(false));
  }, []);

  const toggleNotification = (id: string) => {
    setNotifications((prev) =>
      prev.map((n) => (n.id === id ? { ...n, enabled: !n.enabled } : n))
    );
  };

  const updateTemplate = (id: string, template: string) => {
    setNotifications((prev) =>
      prev.map((n) => (n.id === id ? { ...n, template } : n))
    );
  };

  const handleSave = async () => {
    setSaving(true);
    try {
      await api.put('/notifications/settings', { notifications });
    } catch {
      // Ignore save errors for now
    } finally {
      setSaving(false);
    }
  };

  if (loading) {
    return (
      <div className="flex items-center justify-center h-64">
        <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary" />
      </div>
    );
  }

  if (error) {
    return (
      <div className="flex items-center justify-center h-64">
        <div className="text-center">
          <p className="text-error text-sm mb-2">{error}</p>
          <button
            onClick={() => window.location.reload()}
            className="text-sm text-primary hover:underline"
          >
            Попробовать снова
          </button>
        </div>
      </div>
    );
  }

  return (
    <div>
      <div className="flex items-center justify-between mb-6">
        <div>
          <h1 className="text-2xl font-bold text-gray-900">Настройки уведомлений</h1>
          <p className="text-sm text-muted mt-1">
            Управляйте типами push-уведомлений для сотрудников клуба
          </p>
        </div>
        <button
          onClick={() => void handleSave()}
          disabled={saving}
          className="flex items-center gap-2 bg-primary text-white px-4 py-2.5 rounded-xl text-sm font-medium hover:bg-primary/90 transition-colors disabled:opacity-50"
        >
          <Save className="h-4 w-4" />
          {saving ? 'Сохранение...' : 'Сохранить'}
        </button>
      </div>

      <div className="space-y-4">
        {notifications.map((notification) => (
          <div
            key={notification.id}
            className="bg-card rounded-xl p-6 shadow-sm border border-border"
          >
            <div className="flex items-start justify-between mb-3">
              <div className="flex items-start gap-3">
                <div className="bg-orange-50 text-primary p-2 rounded-lg mt-0.5">
                  <Bell className="h-4 w-4" />
                </div>
                <div>
                  <h3 className="text-sm font-semibold text-gray-900">
                    {notification.name}
                  </h3>
                  <p className="text-xs text-muted mt-0.5">
                    {notification.description}
                  </p>
                </div>
              </div>

              <button
                onClick={() => toggleNotification(notification.id)}
                className={`relative inline-flex h-6 w-11 items-center rounded-full transition-colors ${
                  notification.enabled ? 'bg-primary' : 'bg-gray-300'
                }`}
              >
                <span
                  className={`inline-block h-4 w-4 transform rounded-full bg-white transition-transform ${
                    notification.enabled ? 'translate-x-6' : 'translate-x-1'
                  }`}
                />
              </button>
            </div>

            {notification.enabled && notification.customizable && (
              <div className="mt-3 pl-11">
                <label className="block text-xs font-medium text-gray-600 mb-1">
                  Шаблон сообщения
                </label>
                <textarea
                  value={notification.template}
                  onChange={(e) => updateTemplate(notification.id, e.target.value)}
                  rows={2}
                  className="w-full px-3 py-2 border border-border rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-primary/30 focus:border-primary resize-none"
                />
              </div>
            )}
          </div>
        ))}

        {notifications.length === 0 && (
          <div className="text-center py-12 text-muted text-sm">
            Нет настроек уведомлений
          </div>
        )}
      </div>
    </div>
  );
}
