import React, { useMemo } from 'react';
import { useTranslation } from 'react-i18next';
import { useToast } from '@/components/ui/Toast';
import {
  useNotificationTypes,
  useUpdateNotificationPreference,
} from '@/api/hooks';

interface NotificationTypeItem {
  type_key: string;
  plugin_name: string;
  category: string;
  label: string;
  description: string | null;
  is_enabled_by_default: boolean;
  is_enabled: boolean;
}

export function SettingsNotificationsPage() {
  const { t } = useTranslation();
  const toast = useToast();
  const { data, isLoading, error } = useNotificationTypes();
  const updateMutation = useUpdateNotificationPreference();

  const items: NotificationTypeItem[] = data?.items ?? [];

  // Group by plugin_name
  const grouped = useMemo(() => {
    const map = new Map<string, NotificationTypeItem[]>();
    for (const item of items) {
      const key = item.plugin_name;
      if (!map.has(key)) map.set(key, []);
      map.get(key)!.push(item);
    }
    return Array.from(map.entries());
  }, [items]);

  const handleToggle = (typeKey: string, isEnabled: boolean) => {
    updateMutation.mutate(
      { typeKey, isEnabled },
      {
        onSuccess: () => {
          toast.success(t('notifications.saved'));
        },
        onError: (err: any) => {
          toast.error(err.message || t('common.error'));
        },
      }
    );
  };

  if (isLoading) {
    return (
      <div className="flex items-center justify-center py-12">
        <p className="text-secondary-500">{t('common.loading')}</p>
      </div>
    );
  }

  if (error) {
    return (
      <div className="flex items-center justify-center py-12">
        <p className="text-red-600">{t('common.error')}</p>
      </div>
    );
  }

  return (
    <div data-testid="settings-notifications-page">
      <div className="mb-6">
        <h2 className="text-2xl font-bold text-secondary-900">
          {t('notifications.title')}
        </h2>
        <p className="mt-1 text-sm text-secondary-500">
          {t('notifications.description')}
        </p>
      </div>

      {grouped.length === 0 && (
        <div className="rounded-lg border border-secondary-200 p-8 text-center">
          <p className="text-secondary-500">{t('common.noResults')}</p>
        </div>
      )}

      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        {grouped.map(([pluginName, pluginItems]) => (
          <div
            key={pluginName}
            className="rounded-lg border border-secondary-200 bg-white shadow-sm overflow-hidden"
          >
            <div className="border-b border-secondary-200 bg-secondary-50 px-5 py-3">
              <h3 className="text-lg font-semibold text-secondary-900 capitalize">
                {pluginName}
              </h3>
            </div>
            <div className="divide-y divide-secondary-100">
              {pluginItems.map((item) => (
                <div
                  key={item.type_key}
                  className="flex items-start justify-between gap-4 px-5 py-4"
                >
                  <div className="flex-1 min-w-0">
                    <p className="text-sm font-medium text-secondary-900">
                      {item.label}
                    </p>
                    {item.description && (
                      <p className="mt-0.5 text-xs text-secondary-500">
                        {item.description}
                      </p>
                    )}
                  </div>
                  <ToggleSwitch
                    checked={item.is_enabled}
                    onChange={(checked) => handleToggle(item.type_key, checked)}
                    disabled={updateMutation.isPending}
                    ariaLabel={item.label}
                  />
                </div>
              ))}
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

function ToggleSwitch({
  checked,
  onChange,
  disabled,
  ariaLabel,
}: {
  checked: boolean;
  onChange: (checked: boolean) => void;
  disabled?: boolean;
  ariaLabel: string;
}) {
  return (
    <button
      type="button"
      role="switch"
      aria-checked={checked}
      aria-label={ariaLabel}
      disabled={disabled}
      onClick={() => onChange(!checked)}
      className={`relative inline-flex h-6 w-11 flex-shrink-0 cursor-pointer rounded-full border-2 border-transparent transition-colors duration-200 ease-in-out focus:outline-none focus:ring-2 focus:ring-primary-500 focus:ring-offset-2 disabled:opacity-50 disabled:cursor-not-allowed ${
        checked ? 'bg-primary-600' : 'bg-secondary-300'
      }`}
    >
      <span
        className={`pointer-events-none inline-block h-5 w-5 transform rounded-full bg-white shadow ring-0 transition duration-200 ease-in-out ${
          checked ? 'translate-x-5' : 'translate-x-0'
        }`}
      />
    </button>
  );
}
