'use client';
import React, { useEffect, useState } from 'react';
import api from '@/lib/api';

interface Setting {
  key: string;
  value: string;
  category: string;
}

export default function AdminSettingsPage() {
  const [settings, setSettings] = useState<Setting[]>([]);
  const [isSaving, setIsSaving] = useState(false);

  useEffect(() => {
    fetchSettings();
  }, []);

  const fetchSettings = async () => {
    try {
      const res = await api.get('/admin/settings');
      setSettings(res.data);
    } catch (err) {
      console.error(err);
    }
  };

  const handleInputChange = (key: string, newValue: string) => {
    setSettings(prev => prev.map(s => s.key === key ? { ...s, value: newValue } : s));
  };

  const handleSave = async () => {
    try {
      setIsSaving(true);
      const payload = settings.map(s => ({ key: s.key, value: s.value }));
      await api.put('/admin/settings', { settings: payload });
      alert('Settings saved successfully!');
    } catch (err) {
      console.error(err);
      alert('Failed to save settings.');
    } finally {
      setIsSaving(false);
    }
  };

  const groupedSettings = settings.reduce((acc, curr) => {
    if (!acc[curr.category]) acc[curr.category] = [];
    acc[curr.category].push(curr);
    return acc;
  }, {} as Record<string, Setting[]>);

  return (
    <div className="p-10 max-w-5xl mx-auto font-sans pb-32">
      <div className="flex flex-col sm:flex-row justify-between items-start sm:items-center mb-10 gap-4">
        <div>
          <h1 className="text-4xl font-extrabold text-gray-900 tracking-tight">API Integrations</h1>
          <p className="text-gray-500 mt-2 font-medium">Securely manage your 3rd-party webhook and API keys.</p>
        </div>
        <button 
          onClick={handleSave}
          disabled={isSaving}
          className="bg-indigo-600 text-white px-8 py-3 rounded-xl font-bold hover:bg-indigo-700 disabled:opacity-50 transition-all shadow-lg hover:shadow-indigo-500/30 flex items-center gap-2"
        >
          {isSaving ? (
            'Saving to Database...'
          ) : (
            <>
              <svg className="w-5 h-5" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M8 7H5a2 2 0 00-2 2v9a2 2 0 002 2h14a2 2 0 002-2V9a2 2 0 00-2-2h-3m-1 4l-3 3m0 0l-3-3m3 3V4" /></svg>
              Save Configuration
            </>
          )}
        </button>
      </div>

      <div className="space-y-8">
        {Object.keys(groupedSettings).map(category => (
          <div key={category} className="bg-white rounded-2xl shadow-xl shadow-gray-200/50 border border-gray-200 overflow-hidden relative">
            
            {/* Category Header */}
            <div className="bg-gradient-to-r from-gray-50 to-white px-8 py-5 border-b border-gray-100 flex items-center gap-3">
              <div className="w-2 h-6 bg-indigo-500 rounded-full"></div>
              <h2 className="text-xl font-bold text-gray-900 capitalize">{category} Configuration</h2>
            </div>

            <div className="p-8 grid grid-cols-1 md:grid-cols-2 gap-8">
              {groupedSettings[category].map(setting => {
                const isSecret = setting.key.includes('key') || setting.key.includes('secret') || setting.key.includes('password');
                return (
                  <div key={setting.key} className="space-y-2">
                    <label className="block text-sm font-bold text-gray-700 uppercase tracking-wider">
                      {setting.key.replace(/_/g, ' ')}
                    </label>
                    <div className="relative">
                      <input
                        type={isSecret ? 'password' : 'text'}
                        value={setting.value || ''}
                        onChange={(e) => handleInputChange(setting.key, e.target.value)}
                        className="w-full bg-gray-50 border-gray-300 rounded-xl shadow-inner px-4 py-3 border focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500 font-mono text-sm text-gray-800 placeholder-gray-400 transition-colors"
                        placeholder={`Enter ${setting.key}`}
                      />
                      {isSecret && (
                         <div className="absolute inset-y-0 right-0 pr-3 flex items-center pointer-events-none">
                           <svg className="w-5 h-5 text-gray-400" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 15v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2zm10-10V7a4 4 0 00-8 0v4h8z" /></svg>
                         </div>
                      )}
                    </div>
                  </div>
                );
              })}
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}
