import { useState } from 'react';
import { useSettings, useUpdateSetting } from '../../hooks/useAdmin';
import { SkeletonTable } from '../ui/Skeleton';
import type { SystemSetting } from '../../lib/types';

export function SettingsForm() {
  const { data: settings, isLoading, isError, error } = useSettings();
  const updateSetting = useUpdateSetting();
  const [edits, setEdits] = useState<Record<string, string>>({});

  function currentValue(setting: SystemSetting) {
    return edits[setting.key] ?? setting.value;
  }

  function handleChange(key: string, value: string) {
    setEdits((prev) => ({ ...prev, [key]: value }));
  }

  function handleSave(key: string) {
    const value = edits[key];
    if (value === undefined) return;
    updateSetting.mutate(
      { key, value },
      { onSuccess: () => setEdits((prev) => { const next = { ...prev }; delete next[key]; return next; }) },
    );
  }

  function handleToggleRegistration(current: string) {
    updateSetting.mutate({ key: 'registration', value: current === 'true' ? 'false' : 'true' });
  }

  if (isLoading) return <SkeletonTable rows={4} cols={2} />;
  if (isError) return <p className="text-sm text-red-400">{(error as Error)?.message || 'Failed to load settings'}</p>;
  if (!settings || settings.length === 0) return <p className="text-sm text-gray-500">No settings found.</p>;

  return (
    <div className="space-y-4">
      {settings.map((setting) => (
        <div key={setting.key} className="glass p-4 flex flex-wrap items-center gap-3 glass-hover">
          <label className="min-w-[140px] text-sm font-medium text-gray-300">{setting.key}</label>
          {setting.key === 'registration' ? (
            <button
              type="button"
              onClick={() => handleToggleRegistration(setting.value)}
              disabled={updateSetting.isPending}
              className={`relative inline-flex h-6 w-11 shrink-0 cursor-pointer rounded-full border-2 border-transparent transition-colors duration-200 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2 focus:ring-offset-[#0e120f] disabled:opacity-50 ${
                setting.value === 'true' ? 'bg-gradient-to-r from-blue-600 to-sky-500' : 'bg-white/[0.1]'
              }`}
              role="switch"
              aria-checked={setting.value === 'true'}
              aria-label={`Toggle ${setting.key}`}
            >
              <span className={`pointer-events-none inline-block h-5 w-5 rounded-full bg-white shadow transform transition-transform duration-200 ${setting.value === 'true' ? 'translate-x-5' : 'translate-x-0'}`} />
            </button>
          ) : (
            <div className="flex items-center gap-2 flex-1">
              <input
                type="text"
                value={currentValue(setting)}
                onChange={(e) => handleChange(setting.key, e.target.value)}
                className="flex-1 input-glass px-3 py-2 text-sm"
              />
              {edits[setting.key] !== undefined && edits[setting.key] !== setting.value && (
                <button
                  onClick={() => handleSave(setting.key)}
                  disabled={updateSetting.isPending}
                  className="btn-primary px-3 py-2 text-xs disabled:opacity-50 disabled:cursor-not-allowed"
                >
                  <span>{updateSetting.isPending ? 'Saving…' : 'Save'}</span>
                </button>
              )}
            </div>
          )}
        </div>
      ))}
    </div>
  );
}
