import React, { useState, useEffect } from 'react';
import { toast } from 'sonner';
import { api } from '@/api';
import { Card, CardHeader, CardTitle, CardContent } from '@/components/ui/card';
import { FieldRow, Toggle } from './adminShared';

export default function PrivacyAdminCard() {
  const [geoEnabled, setGeoEnabled] = useState(false);
  const [loading, setLoading]       = useState(true);
  const [saving, setSaving]         = useState(false);

  useEffect(() => {
    api.privacySettings()
      .then(d => { setGeoEnabled(!!d.geolocation_enabled); })
      .catch(() => toast.error('Failed to load privacy settings'))
      .finally(() => setLoading(false));
  }, []);

  async function toggleGeo(next) {
    setSaving(true);
    try {
      const d = await api.setPrivacySettings({ geolocation_enabled: next });
      setGeoEnabled(!!d.geolocation_enabled);
      toast.success(next ? 'Geolocation enabled' : 'Geolocation disabled');
    } catch {
      toast.error('Failed to update privacy settings');
    } finally {
      setSaving(false);
    }
  }

  return (
    <Card>
      <CardHeader>
        <CardTitle>Privacy</CardTitle>
      </CardHeader>
      <CardContent className="space-y-4">
        <FieldRow label="Login geolocation">
          <div className="flex items-center gap-3">
            <Toggle
              checked={geoEnabled}
              onChange={toggleGeo}
              disabled={loading || saving}
              label="Enable login geolocation"
            />
            <span className="text-sm text-muted-foreground">
              {geoEnabled ? 'On' : 'Off (default)'}
            </span>
          </div>
        </FieldRow>
        <p className="text-xs text-muted-foreground">
          When enabled, new-device logins resolve the login IP to a city/region via{' '}
          <span className="font-mono">ip-api.com</span> over plain HTTP. Disable to keep
          all login data on-device. Location data is encrypted at rest.
        </p>
      </CardContent>
    </Card>
  );
}
