'use client';

import { useEffect, useState, useCallback } from 'react';
import { toast } from 'sonner';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Switch } from '@/components/ui/switch';
import { Separator } from '@/components/ui/separator';
import { Skeleton } from '@/components/ui/skeleton';
import { Badge } from '@/components/ui/badge';
import { Loader2, Save, Shield, Settings, Bell, DollarSign, Info, Send, CheckCircle, XCircle, Globe, Zap, Pencil, RotateCcw } from 'lucide-react';

// Check if a value is a masked secret (starts with asterisks)
const isMaskedSecret = (val: string) => val.startsWith('*') && val.replace(/\*/g, '').length >= 1;

interface SettingsMap {
  [key: string]: { value: string; isSecret: boolean };
}

const DEFAULTS: Record<string, string> = {
  SILKPAY_API_BASE_URL: '',
  SILKPAY_MERCHANT_ID: '',
  SILKPAY_MERCHANT_SECRET: '',
  NOTIFY_URL: '',
  RETURN_URL: '',
  RETURN_URL_UPLOAD: '',
  RETURN_URL_TYPE: 'success',
  TELEGRAM_BOT_TOKEN: '',
  TELEGRAM_CHANNEL_ID: '',
  ENABLE_TELEGRAM: 'false',
  MIN_AMOUNT: '',
  MAX_AMOUNT: '',
  CURRENCY: 'INR',
  APP_NAME: 'SilkPay Gateway',
  MAINTENANCE_MODE: 'false',
  SCREENSHOT_UPLOAD_ENABLED: 'false',
  ACTIVE_GATEWAY: 'SILKPAY',
  LGPAY_APP_ID: '',
  LGPAY_SECRET_KEY: '',
  LGPAY_TRADE_TYPE: '',
  LGPAY_NOTIFY_URL: '',
};
const NON_SECRET_OVERRIDES = new Set(['TELEGRAM_CHANNEL_ID']);

export default function AdminSettingsPage() {
  const [settings, setSettings] = useState<Record<string, string>>({ ...DEFAULTS });
  const [originalValues, setOriginalValues] = useState<Record<string, string>>({ ...DEFAULTS });
  const [secretFields, setSecretFields] = useState<Set<string>>(new Set());
  const [editingSecrets, setEditingSecrets] = useState<Set<string>>(new Set());
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [hasChanges, setHasChanges] = useState(false);
  const [testingTelegram, setTestingTelegram] = useState(false);
  const [telegramTestResult, setTelegramTestResult] = useState<{ success: boolean; message: string } | null>(null);
  const [detectedDomain, setDetectedDomain] = useState<string>('');

  const fetchSettings = useCallback(async () => {
    setLoading(true);
    try {
      const res = await fetch('/api/admin/settings');
      if (!res.ok) throw new Error('Failed to load settings');
      const data: { settings: SettingsMap } = await res.json();

      const loaded: Record<string, string> = { ...DEFAULTS };
      const secrets = new Set<string>();

      for (const [key, meta] of Object.entries(data.settings)) {
        loaded[key] = meta.value;
        if (meta.isSecret && !NON_SECRET_OVERRIDES.has(key)) secrets.add(key);
      }

      setSettings(loaded);
      setOriginalValues(loaded);
      setSecretFields(secrets);
      setEditingSecrets(new Set());

      // Auto-detect domain from current URL
      if (typeof window !== 'undefined') {
        setDetectedDomain(window.location.origin);
      }
    } catch {
      toast.error('Failed to load settings. Please try again.');
    } finally {
      setLoading(false);
    }
  }, []);

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

  useEffect(() => {
    const changed = Object.keys(DEFAULTS).some((key) => settings[key] !== originalValues[key]);
    setHasChanges(changed);
  }, [originalValues, settings]);

  const handleInputChange = (key: string, value: string) => {
    setSettings((prev) => ({ ...prev, [key]: value }));
  };

  const handleSwitchChange = (key: string, checked: boolean) => {
    setSettings((prev) => ({ ...prev, [key]: String(checked) }));
  };

  const buildPayload = () => {
    const payload: Record<string, string> = {};
    for (const [key, value] of Object.entries(settings)) {
      if (secretFields.has(key)) {
        if (editingSecrets.has(key) && value.trim() !== '') {
          payload[key] = value;
        }
      } else {
        payload[key] = value;
      }
    }
    return payload;
  };

  const startSecretEdit = (key: string) => {
    setEditingSecrets((prev) => new Set(prev).add(key));
    setSettings((prev) => ({ ...prev, [key]: '' }));
  };

  const cancelSecretEdit = (key: string) => {
    setEditingSecrets((prev) => {
      const next = new Set(prev);
      next.delete(key);
      return next;
    });
    setSettings((prev) => ({ ...prev, [key]: originalValues[key] || '' }));
  };

  const autoFillReturnUrl = (field: 'NOTIFY_URL' | 'RETURN_URL' | 'RETURN_URL_UPLOAD' | 'LGPAY_NOTIFY_URL', path: string) => {
    if (detectedDomain) {
      handleInputChange(field, detectedDomain + path);
    }
  };

  const handleTestTelegram = async () => {
    setTestingTelegram(true);
    setTelegramTestResult(null);
    try {
      const res = await fetch('/api/admin/settings', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ action: 'test_telegram' }),
      });
      const data = await res.json();
      if (data.success) {
        setTelegramTestResult({ success: true, message: data.message });
        toast.success('Test message sent to Telegram!');
      } else {
        setTelegramTestResult({ success: false, message: data.error || 'Failed' });
        toast.error(data.error || 'Failed to send test message');
      }
    } catch {
      setTelegramTestResult({ success: false, message: 'Network error' });
      toast.error('Failed to send test message');
    } finally {
      setTestingTelegram(false);
    }
  };

  const handleSave = async () => {
    setSaving(true);
    try {
      const payload = buildPayload();
      const res = await fetch('/api/admin/settings', {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(payload),
      });
      if (!res.ok) {
        const data = await res.json();
        throw new Error(data.error || 'Failed to save settings');
      }
      toast.success('Settings saved successfully!');
      await fetchSettings();
    } catch (err) {
      toast.error(err instanceof Error ? err.message : 'Failed to save settings');
    } finally {
      setSaving(false);
    }
  };

  if (loading) return <SettingsSkeleton />;

  const activeGateway = settings.ACTIVE_GATEWAY || 'SILKPAY';

  return (
    <div className="space-y-6">
      {/* Page Header */}
      <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
        <div>
          <h1 className="text-2xl font-bold text-gray-900 flex items-center gap-2">
            <Settings className="h-6 w-6 text-emerald-600" />
            Settings
          </h1>
          <p className="text-sm text-gray-500 mt-1">
            Configure your payment gateway and application preferences
          </p>
        </div>
        <div className="flex items-center gap-2">
          {hasChanges && (
            <Badge variant="outline" className="text-amber-600 border-amber-300 bg-amber-50">
              Unsaved changes
            </Badge>
          )}
          <Button onClick={handleSave} disabled={saving || !hasChanges} className="bg-emerald-600 hover:bg-emerald-700 text-white shadow-sm">
            {saving ? (<><Loader2 className="mr-2 h-4 w-4 animate-spin" /> Saving...</>) : (<><Save className="mr-2 h-4 w-4" /> Save Changes</>)}
          </Button>
        </div>
      </div>
      <Separator />

      {/* Domain Info Card */}
      {detectedDomain && (
        <div className="flex items-start gap-3 rounded-lg border border-emerald-200 bg-emerald-50 p-4">
          <Globe className="h-5 w-5 text-emerald-600 mt-0.5 shrink-0" />
          <div className="text-sm text-emerald-800">
            <p className="font-medium">Detected Domain: <code className="rounded bg-emerald-100 px-1.5 py-0.5 text-xs font-mono">{detectedDomain}</code></p>
            <p className="mt-0.5 text-emerald-600">Click &quot;Auto-fill&quot; buttons below to set callback/return URLs automatically.</p>
          </div>
        </div>
      )}

      {/* Secret Values Notice */}
      <div className="flex items-start gap-3 rounded-lg border border-blue-200 bg-blue-50 p-4">
        <Info className="h-5 w-5 text-blue-600 mt-0.5 shrink-0" />
        <div className="text-sm text-blue-800">
          <p className="font-medium">Encrypted &amp; Secure</p>
          <p className="mt-0.5 text-blue-600">
            Secret values (marked with <Badge variant="secondary" className="ml-1 text-xs px-1.5 py-0">Secret</Badge>) are encrypted on the server. Masked fields show only the last 4 characters. Leave them unchanged to keep the existing value.
          </p>
        </div>
      </div>

      {/* ═══ Gateway Selection ═══ */}
      <Card>
        <CardHeader>
          <div className="flex items-center gap-2">
            <div className="flex h-9 w-9 items-center justify-center rounded-lg bg-violet-100">
              <Zap className="h-5 w-5 text-violet-600" />
            </div>
            <div>
              <CardTitle className="text-lg">Active Gateway</CardTitle>
              <CardDescription>Select which payment gateway to use for new orders</CardDescription>
            </div>
          </div>
        </CardHeader>
        <CardContent className="space-y-4">
          <div className="grid gap-3 sm:grid-cols-3">
            {[
              { value: 'SILKPAY', label: 'SilkPay', desc: 'Default SilkPay gateway', color: 'emerald' },
              { value: 'LGPAY', label: 'LG-Pay', desc: 'LG-Pay payment gateway', color: 'blue' },
              { value: 'RANDOM', label: 'Random', desc: 'Randomly select gateway', color: 'purple' },
            ].map((gw) => {
              const isActive = activeGateway === gw.value;
              const colorMap: Record<string, string> = {
                emerald: isActive ? 'border-emerald-400 bg-emerald-50 text-emerald-700 ring-2 ring-emerald-200' : 'border-gray-200 bg-white text-gray-600 hover:border-emerald-200',
                blue: isActive ? 'border-blue-400 bg-blue-50 text-blue-700 ring-2 ring-blue-200' : 'border-gray-200 bg-white text-gray-600 hover:border-blue-200',
                purple: isActive ? 'border-purple-400 bg-purple-50 text-purple-700 ring-2 ring-purple-200' : 'border-gray-200 bg-white text-gray-600 hover:border-purple-200',
              };
              return (
                <button
                  key={gw.value}
                  type="button"
                  onClick={() => handleInputChange('ACTIVE_GATEWAY', gw.value)}
                  className={`rounded-lg border p-4 text-left transition-all ${colorMap[gw.color]}`}
                >
                  <p className="font-semibold text-sm">{gw.label}</p>
                  <p className="text-xs mt-1 opacity-70">{gw.desc}</p>
                  {isActive && <CheckCircle className="h-4 w-4 mt-2 text-current" />}
                </button>
              );
            })}
          </div>
          {activeGateway === 'RANDOM' && (
            <div className="rounded-lg border border-purple-200 bg-purple-50 p-3 text-sm text-purple-700">
              <b>Random Mode:</b> Each new order will randomly use either SilkPay or LG-Pay gateway (50/50 chance).
            </div>
          )}
        </CardContent>
      </Card>

      {/* ═══ SilkPay Settings ═══ */}
      <Card>
        <CardHeader>
          <div className="flex items-center gap-2">
            <div className="flex h-9 w-9 items-center justify-center rounded-lg bg-emerald-100">
              <Shield className="h-5 w-5 text-emerald-600" />
            </div>
            <div>
              <CardTitle className="text-lg">SilkPay Gateway</CardTitle>
              <CardDescription>SilkPay API configuration</CardDescription>
            </div>
          </div>
        </CardHeader>
        <CardContent className="space-y-5">
          <div className="grid gap-5 sm:grid-cols-2">
            <FormField label="API Base URL" value={settings.SILKPAY_API_BASE_URL} onChange={(v) => handleInputChange('SILKPAY_API_BASE_URL', v)} placeholder="https://api.silkpay.io" />
            <FormField label="Merchant ID (mId)" value={settings.SILKPAY_MERCHANT_ID} onChange={(v) => handleInputChange('SILKPAY_MERCHANT_ID', v)} placeholder="M-XXXXXXXX" />
          </div>
          <SecretField
            label="Merchant Secret"
            value={settings.SILKPAY_MERCHANT_SECRET}
            onChange={(v) => handleInputChange('SILKPAY_MERCHANT_SECRET', v)}
            placeholder="Enter new secret"
            editing={editingSecrets.has('SILKPAY_MERCHANT_SECRET')}
            onEdit={() => startSecretEdit('SILKPAY_MERCHANT_SECRET')}
            onCancel={() => cancelSecretEdit('SILKPAY_MERCHANT_SECRET')}
          />

          {/* Notify URL with auto-fill */}
          <div className="space-y-2">
            <div className="flex items-center gap-2">
              <Label className="text-sm font-medium flex-1">Notify URL (Callback)</Label>
              {detectedDomain && (
                <Button type="button" variant="outline" size="sm" className="text-xs h-7" onClick={() => autoFillReturnUrl('NOTIFY_URL', '/api/payin/callback')}>
                  <Globe className="h-3 w-3 mr-1" /> Auto-fill
                </Button>
              )}
            </div>
            <Input type="text" value={settings.NOTIFY_URL} onChange={(e) => handleInputChange('NOTIFY_URL', e.target.value)} placeholder="https://yourdomain.com/api/payin/callback" className="h-10" />
          </div>

          <div className="grid gap-5 sm:grid-cols-2">
            <div className="space-y-2">
              <div className="flex items-center gap-2">
                <Label className="text-sm font-medium flex-1">Return URL (Success)</Label>
                {detectedDomain && (
                  <Button type="button" variant="outline" size="sm" className="text-xs h-7" onClick={() => autoFillReturnUrl('RETURN_URL', '/payment-success')}>
                    <Globe className="h-3 w-3 mr-1" /> Auto
                  </Button>
                )}
              </div>
              <Input type="text" value={settings.RETURN_URL} onChange={(e) => handleInputChange('RETURN_URL', e.target.value)} placeholder="https://yourdomain.com/payment-success" className="h-10" />
            </div>
            <div className="space-y-2">
              <div className="flex items-center gap-2">
                <Label className="text-sm font-medium flex-1">Return URL (Upload)</Label>
                {detectedDomain && (
                  <Button type="button" variant="outline" size="sm" className="text-xs h-7" onClick={() => autoFillReturnUrl('RETURN_URL_UPLOAD', '/upload')}>
                    <Globe className="h-3 w-3 mr-1" /> Auto
                  </Button>
                )}
              </div>
              <Input type="text" value={settings.RETURN_URL_UPLOAD} onChange={(e) => handleInputChange('RETURN_URL_UPLOAD', e.target.value)} placeholder="https://yourdomain.com/upload" className="h-10" />
            </div>
          </div>

          {/* Return URL Type */}
          <div className="rounded-lg border border-gray-200 p-4">
            <div className="flex items-center justify-between">
              <div className="space-y-0.5">
                <Label className="text-sm font-medium">Return URL Type</Label>
                <p className="text-xs text-gray-500">Which page users see after payment</p>
              </div>
            </div>
            <div className="mt-3 flex gap-2">
              {['success', 'upload'].map((type) => (
                <button key={type} type="button" onClick={() => handleInputChange('RETURN_URL_TYPE', type)}
                  className={`rounded-lg border px-4 py-2 text-sm font-medium transition-colors ${
                    settings.RETURN_URL_TYPE === type ? 'border-emerald-300 bg-emerald-50 text-emerald-700' : 'border-gray-200 bg-white text-gray-600 hover:bg-gray-50'
                  }`}>
                  {type === 'success' ? 'Success Page' : 'Upload Page'}
                </button>
              ))}
            </div>
          </div>
        </CardContent>
      </Card>

      {/* ═══ LG-Pay Settings ═══ */}
      <Card>
        <CardHeader>
          <div className="flex items-center gap-2">
            <div className="flex h-9 w-9 items-center justify-center rounded-lg bg-blue-100">
              <Shield className="h-5 w-5 text-blue-600" />
            </div>
            <div>
              <CardTitle className="text-lg">LG-Pay Gateway</CardTitle>
              <CardDescription>
                <a href="https://www.lg-pay.com/docs/" target="_blank" rel="noopener noreferrer" className="text-blue-600 hover:underline">
                  LG-Pay API configuration (Docs)
                </a>
              </CardDescription>
            </div>
          </div>
        </CardHeader>
        <CardContent className="space-y-5">
          <div className="grid gap-5 sm:grid-cols-2">
            <FormField label="App ID (app_id)" value={settings.LGPAY_APP_ID} onChange={(v) => handleInputChange('LGPAY_APP_ID', v)} placeholder="YD5097" />
            <FormField label="Trade Type (trade_type)" value={settings.LGPAY_TRADE_TYPE} onChange={(v) => handleInputChange('LGPAY_TRADE_TYPE', v)} placeholder="test" />
          </div>
          <SecretField
            label="Secret Key"
            value={settings.LGPAY_SECRET_KEY}
            onChange={(v) => handleInputChange('LGPAY_SECRET_KEY', v)}
            placeholder="Enter new LG-Pay secret key"
            editing={editingSecrets.has('LGPAY_SECRET_KEY')}
            onEdit={() => startSecretEdit('LGPAY_SECRET_KEY')}
            onCancel={() => cancelSecretEdit('LGPAY_SECRET_KEY')}
          />

          {/* LG-Pay Notify URL */}
          <div className="space-y-2">
            <div className="flex items-center gap-2">
              <Label className="text-sm font-medium flex-1">LG-Pay Notify URL (Callback)</Label>
              {detectedDomain && (
                <Button type="button" variant="outline" size="sm" className="text-xs h-7" onClick={() => autoFillReturnUrl('LGPAY_NOTIFY_URL', '/api/payin/lgpay-callback')}>
                  <Globe className="h-3 w-3 mr-1" /> Auto-fill
                </Button>
              )}
            </div>
            <Input type="text" value={settings.LGPAY_NOTIFY_URL} onChange={(e) => handleInputChange('LGPAY_NOTIFY_URL', e.target.value)} placeholder="https://yourdomain.com/api/payin/lgpay-callback" className="h-10" />
          </div>

          {/* Account Info */}
          <div className="rounded-lg border border-blue-100 bg-blue-50/50 p-4 text-xs text-blue-700 space-y-1">
            <p className="font-semibold">LG-Pay Account Info:</p>
            <p>Merchant: <code className="bg-blue-100 px-1 rounded">YD5097/unlimited</code></p>
            <p>Portal: <a href="https://www.lg-pay.com/app/merchant/page/login.html" target="_blank" rel="noopener noreferrer" className="underline">https://www.lg-pay.com/app/merchant/page/login.html</a></p>
            <p>Docs: <a href="https://www.lg-pay.com/docs/" target="_blank" rel="noopener noreferrer" className="underline">https://www.lg-pay.com/docs/</a></p>
          </div>
        </CardContent>
      </Card>

      {/* ═══ Telegram Settings ═══ */}
      <Card>
        <CardHeader>
          <div className="flex items-center gap-2">
            <div className="flex h-9 w-9 items-center justify-center rounded-lg bg-sky-100">
              <Bell className="h-5 w-5 text-sky-600" />
            </div>
            <div>
              <CardTitle className="text-lg">Telegram Notifications</CardTitle>
              <CardDescription>Configure Telegram bot for order notifications</CardDescription>
            </div>
          </div>
        </CardHeader>
        <CardContent className="space-y-5">
          <SecretField
            label="Bot Token"
            value={settings.TELEGRAM_BOT_TOKEN}
            onChange={(v) => handleInputChange('TELEGRAM_BOT_TOKEN', v)}
            placeholder="Enter new bot token"
            editing={editingSecrets.has('TELEGRAM_BOT_TOKEN')}
            onEdit={() => startSecretEdit('TELEGRAM_BOT_TOKEN')}
            onCancel={() => cancelSecretEdit('TELEGRAM_BOT_TOKEN')}
          />
          <FormField label="Channel ID" value={settings.TELEGRAM_CHANNEL_ID} onChange={(v) => handleInputChange('TELEGRAM_CHANNEL_ID', v)} placeholder="@yourchannel or -100XXXXXXXXXX" />
          <div className="flex items-center justify-between rounded-lg border border-gray-200 p-4">
            <div className="space-y-0.5">
              <Label className="text-sm font-medium">Enable Notifications</Label>
              <p className="text-xs text-gray-500">Send order alerts to your Telegram channel</p>
            </div>
            <Switch checked={settings.ENABLE_TELEGRAM === 'true'} onCheckedChange={(checked) => handleSwitchChange('ENABLE_TELEGRAM', checked)} />
          </div>
          <div className="flex flex-col sm:flex-row items-start sm:items-center justify-between gap-3 rounded-lg border border-sky-200 bg-sky-50/50 p-4">
            <div className="space-y-0.5">
              <Label className="text-sm font-medium text-sky-800">Test Connection</Label>
              <p className="text-xs text-sky-600">Send a test message to verify your Telegram bot</p>
            </div>
            <Button variant="outline" size="sm" onClick={handleTestTelegram} disabled={testingTelegram || !settings.TELEGRAM_CHANNEL_ID || (editingSecrets.has('TELEGRAM_BOT_TOKEN') && !settings.TELEGRAM_BOT_TOKEN)} className="border-sky-300 text-sky-700 hover:bg-sky-100 hover:text-sky-800 shrink-0">
              {testingTelegram ? (<><Loader2 className="mr-2 h-4 w-4 animate-spin" /> Sending...</>) : (<><Send className="mr-2 h-4 w-4" /> Send Test Message</>)}
            </Button>
          </div>
          {telegramTestResult && (
            <div className={`flex items-center gap-2 rounded-lg border p-3 text-sm ${telegramTestResult.success ? 'border-emerald-200 bg-emerald-50 text-emerald-700' : 'border-red-200 bg-red-50 text-red-700'}`}>
              {telegramTestResult.success ? <CheckCircle className="h-4 w-4 shrink-0" /> : <XCircle className="h-4 w-4 shrink-0" />}
              <span>{telegramTestResult.message}</span>
            </div>
          )}
        </CardContent>
      </Card>

      {/* ═══ Payment Limits ═══ */}
      <Card>
        <CardHeader>
          <div className="flex items-center gap-2">
            <div className="flex h-9 w-9 items-center justify-center rounded-lg bg-amber-100">
              <DollarSign className="h-5 w-5 text-amber-600" />
            </div>
            <div>
              <CardTitle className="text-lg">Payment Limits</CardTitle>
              <CardDescription>Set minimum and maximum payment amounts</CardDescription>
            </div>
          </div>
        </CardHeader>
        <CardContent>
          <div className="grid gap-5 sm:grid-cols-3">
            <NumberField label="Minimum Amount" value={settings.MIN_AMOUNT} onChange={(v) => handleInputChange('MIN_AMOUNT', v)} placeholder="1.00" />
            <NumberField label="Maximum Amount" value={settings.MAX_AMOUNT} onChange={(v) => handleInputChange('MAX_AMOUNT', v)} placeholder="10000.00" />
            <FormField label="Currency" value={settings.CURRENCY} onChange={(v) => handleInputChange('CURRENCY', v)} placeholder="USD" />
          </div>
        </CardContent>
      </Card>

      {/* ═══ App Settings ═══ */}
      <Card>
        <CardHeader>
          <div className="flex items-center gap-2">
            <div className="flex h-9 w-9 items-center justify-center rounded-lg bg-violet-100">
              <Settings className="h-5 w-5 text-violet-600" />
            </div>
            <div>
              <CardTitle className="text-lg">Application</CardTitle>
              <CardDescription>General application configuration</CardDescription>
            </div>
          </div>
        </CardHeader>
        <CardContent className="space-y-5">
          <FormField label="App Name" value={settings.APP_NAME} onChange={(v) => handleInputChange('APP_NAME', v)} placeholder="SilkPay" />
          <div className="flex items-center justify-between rounded-lg border border-gray-200 p-4">
            <div className="space-y-0.5">
              <Label className="text-sm font-medium">Maintenance Mode</Label>
              <p className="text-xs text-gray-500">Temporarily disable the payment page</p>
            </div>
            <Switch checked={settings.MAINTENANCE_MODE === 'true'} onCheckedChange={(checked) => handleSwitchChange('MAINTENANCE_MODE', checked)} />
          </div>
          <div className="flex items-center justify-between rounded-lg border border-gray-200 p-4">
            <div className="space-y-0.5">
              <Label className="text-sm font-medium">Screenshot Upload</Label>
              <p className="text-xs text-gray-500">Allow users to upload payment screenshots</p>
            </div>
            <Switch checked={settings.SCREENSHOT_UPLOAD_ENABLED === 'true'} onCheckedChange={(checked) => handleSwitchChange('SCREENSHOT_UPLOAD_ENABLED', checked)} />
          </div>
        </CardContent>
      </Card>

      {/* Bottom Save */}
      <div className="flex items-center justify-end gap-3 pt-2 pb-4">
        <Button variant="outline" onClick={fetchSettings} disabled={saving}>Discard</Button>
        <Button onClick={handleSave} disabled={saving || !hasChanges} className="bg-emerald-600 hover:bg-emerald-700 text-white shadow-sm">
          {saving ? (<><Loader2 className="mr-2 h-4 w-4 animate-spin" /> Saving...</>) : (<><Save className="mr-2 h-4 w-4" /> Save Changes</>)}
        </Button>
      </div>
    </div>
  );
}

/* ── Reusable Field Components ─────────────────────────────────── */

interface FormFieldProps {
  label: string;
  value: string;
  onChange: (value: string) => void;
  placeholder?: string;
  type?: string;
}

function FormField({ label, value, onChange, placeholder, type = 'text' }: FormFieldProps) {
  return (
    <div className="space-y-2">
      <Label className="text-sm font-medium">{label}</Label>
      <Input type={type} value={value} onChange={(e) => onChange(e.target.value)} placeholder={placeholder} className="h-10" />
    </div>
  );
}

function NumberField({ label, value, onChange, placeholder }: FormFieldProps) {
  return (
    <div className="space-y-2">
      <Label className="text-sm font-medium">{label}</Label>
      <Input type="number" min="0" step="any" value={value} onChange={(e) => onChange(e.target.value)} placeholder={placeholder} className="h-10" />
    </div>
  );
}

function SecretField({
  label,
  value,
  onChange,
  placeholder,
  editing,
  onEdit,
  onCancel,
}: FormFieldProps & {
  editing: boolean;
  onEdit: () => void;
  onCancel: () => void;
}) {
  const masked = isMaskedSecret(value);
  return (
    <div className="space-y-2">
      <div className="flex flex-wrap items-center gap-2">
        <Label className="text-sm font-medium flex-1">{label}</Label>
        <Badge variant="secondary" className="text-xs px-1.5 py-0">Secret</Badge>
        {editing ? (
          <Button type="button" variant="outline" size="sm" className="h-7 text-xs" onClick={onCancel}>
            <RotateCcw className="h-3 w-3 mr-1" />
            Cancel
          </Button>
        ) : (
          <Button type="button" variant="outline" size="sm" className="h-7 text-xs" onClick={onEdit}>
            <Pencil className="h-3 w-3 mr-1" />
            Change
          </Button>
        )}
      </div>
      <Input
        type="text"
        readOnly={masked && !editing}
        value={value}
        onChange={(e) => onChange(e.target.value)}
        placeholder={editing ? placeholder : 'Masked secret'}
        className="h-10 font-mono text-sm"
      />
      {masked && !editing && <p className="text-xs text-gray-400">Value is masked. Only the last 4 characters are visible. Click Change to replace it.</p>}
      {editing && <p className="text-xs text-gray-400">Enter a new value to replace the current secret.</p>}
    </div>
  );
}

/* ── Skeleton Loader ───────────────────────────────────────────── */

function SettingsSkeleton() {
  return (
    <div className="space-y-6">
      <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
        <div className="space-y-2"><Skeleton className="h-8 w-48" /><Skeleton className="h-4 w-72" /></div>
        <Skeleton className="h-10 w-32" />
      </div>
      <Skeleton className="h-px w-full" />
      {Array.from({ length: 6 }).map((_, i) => (
        <Card key={i}>
          <CardHeader>
            <div className="flex items-center gap-3">
              <Skeleton className="h-9 w-9 rounded-lg" />
              <div className="space-y-1.5"><Skeleton className="h-5 w-36" /><Skeleton className="h-4 w-48" /></div>
            </div>
          </CardHeader>
          <CardContent className="space-y-4">
            <div className="grid gap-4 sm:grid-cols-2"><Skeleton className="h-16 w-full rounded-lg" /><Skeleton className="h-16 w-full rounded-lg" /></div>
            <Skeleton className="h-16 w-full rounded-lg" />
          </CardContent>
        </Card>
      ))}
      <div className="flex justify-end gap-3 pt-2 pb-4"><Skeleton className="h-10 w-24" /><Skeleton className="h-10 w-32" /></div>
    </div>
  );
}
