'use client';

import { useState, useEffect, useCallback } from 'react';
import {
  Save,
  Globe,
  Shield,
  Bell,
  Database,
  Key,
  Power,
  Monitor,
  Smartphone,
  Tablet,
  Globe2,
} from 'lucide-react';
import { Card, CardContent, CardHeader, CardTitle, CardDescription } 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 {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import { useToast } from '@/components/ui/toast';

interface PlatformFlags {
  desktop: boolean;
  ios: boolean;
  android: boolean;
  web: boolean;
}

interface KillSwitchState {
  enabled: boolean;
  platforms: PlatformFlags;
  reason: string;
  updatedAt: string;
  updatedBy: string;
}

interface PlatformSettings {
  platformName: string;
  supportEmail: string;
  defaultLanguage: string;
  maintenanceMode: boolean;
  allowSelfRegistration: boolean;
  rateLimits: {
    globalPerMin: number;
    perUserPerMin: number;
    maxTokenBurst: number;
    abuseThreshold: number;
    autoSuspendOnAbuse: boolean;
    ipBlocklist: boolean;
  };
  notifications: {
    newUserSignup: boolean;
    usageThreshold: boolean;
    failedPayment: boolean;
    securityAlerts: boolean;
  };
  dataRetentionDays: number;
  backupFrequency: string;
  auditLogging: boolean;
  updatedAt?: string;
  updatedBy?: string;
}

const DEFAULTS: PlatformSettings = {
  platformName: '',
  supportEmail: '',
  defaultLanguage: 'en-US',
  maintenanceMode: false,
  allowSelfRegistration: true,
  rateLimits: {
    globalPerMin: 1000,
    perUserPerMin: 60,
    maxTokenBurst: 4096,
    abuseThreshold: 50,
    autoSuspendOnAbuse: true,
    ipBlocklist: true,
  },
  notifications: {
    newUserSignup: true,
    usageThreshold: true,
    failedPayment: true,
    securityAlerts: true,
  },
  dataRetentionDays: 365,
  backupFrequency: 'daily',
  auditLogging: true,
};

function getAuthHeaders(): HeadersInit {
  if (typeof window === 'undefined') return {};
  const token = localStorage.getItem('admin_access_token');
  if (!token) return {};
  return { Authorization: `Bearer ${token}` };
}

export default function SettingsPage() {
  const [saved, setSaved] = useState(false);
  const [saving, setSaving] = useState(false);
  const { toast } = useToast();
  const [settings, setSettings] = useState<PlatformSettings>(DEFAULTS);
  const [settingsLoading, setSettingsLoading] = useState(true);
  const [killSwitch, setKillSwitch] = useState<KillSwitchState | null>(null);
  const [killSwitchLoading, setKillSwitchLoading] = useState(true);
  const [killSwitchToggling, setKillSwitchToggling] = useState(false);

  const fetchSettings = useCallback(async () => {
    try {
      const res = await fetch('/api/settings/platform', { headers: getAuthHeaders() });
      if (res.ok) {
        const data = await res.json();
        setSettings({
          platformName: data.platformName ?? DEFAULTS.platformName,
          supportEmail: data.supportEmail ?? DEFAULTS.supportEmail,
          defaultLanguage: data.defaultLanguage ?? DEFAULTS.defaultLanguage,
          maintenanceMode: data.maintenanceMode ?? DEFAULTS.maintenanceMode,
          allowSelfRegistration: data.allowSelfRegistration ?? DEFAULTS.allowSelfRegistration,
          rateLimits: { ...DEFAULTS.rateLimits, ...(data.rateLimits ?? {}) },
          notifications: { ...DEFAULTS.notifications, ...(data.notifications ?? {}) },
          dataRetentionDays: data.dataRetentionDays ?? DEFAULTS.dataRetentionDays,
          backupFrequency: data.backupFrequency ?? DEFAULTS.backupFrequency,
          auditLogging: data.auditLogging ?? DEFAULTS.auditLogging,
          updatedAt: data.updatedAt,
          updatedBy: data.updatedBy,
        });
      }
    } catch {
      // use defaults
    } finally {
      setSettingsLoading(false);
    }
  }, []);

  const fetchKillSwitch = useCallback(async () => {
    try {
      const res = await fetch('/api/settings/kill-switch');
      if (res.ok) {
        const data = await res.json();
        setKillSwitch(data);
      }
    } catch {
      // ignore
    } finally {
      setKillSwitchLoading(false);
    }
  }, []);

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

  const toggleKillSwitch = async () => {
    if (!killSwitch) return;
    setKillSwitchToggling(true);
    try {
      const newEnabled = !killSwitch.enabled;
      const res = await fetch('/api/settings/kill-switch', {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          enabled: newEnabled,
          platforms: killSwitch.platforms,
          reason: newEnabled ? '' : 'Disabled by admin from dashboard',
          updatedBy: 'admin',
        }),
      });
      if (res.ok) {
        const data = await res.json();
        setKillSwitch(data);
      }
    } catch {
      // ignore
    } finally {
      setKillSwitchToggling(false);
    }
  };

  const togglePlatform = async (platform: keyof PlatformFlags) => {
    if (!killSwitch) return;
    setKillSwitchToggling(true);
    try {
      const newPlatforms = { ...killSwitch.platforms, [platform]: !killSwitch.platforms[platform] };
      const res = await fetch('/api/settings/kill-switch', {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          enabled: killSwitch.enabled,
          platforms: newPlatforms,
          reason: killSwitch.reason,
          updatedBy: 'admin',
        }),
      });
      if (res.ok) {
        const data = await res.json();
        setKillSwitch(data);
      }
    } catch {
      // ignore
    } finally {
      setKillSwitchToggling(false);
    }
  };

  const handleSave = async () => {
    setSaving(true);
    try {
      const res = await fetch('/api/settings/platform', {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json', ...getAuthHeaders() },
        body: JSON.stringify(settings),
      });
      if (res.ok) {
        const data = await res.json();
        setSettings(prev => ({ ...prev, updatedAt: data.updatedAt, updatedBy: data.updatedBy }));
        setSaved(true);
        setTimeout(() => setSaved(false), 2000);
      } else {
        toast({ title: 'Failed to save settings', variant: 'error' });
      }
    } catch {
      toast({ title: 'Network error — could not save settings', variant: 'error' });
    } finally {
      setSaving(false);
    }
  };

  if (settingsLoading && killSwitchLoading) {
    return (
      <div className="flex items-center justify-center py-20">
        <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary" />
      </div>
    );
  }

  return (
    <div className="space-y-6 max-w-3xl">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-3xl font-bold tracking-tight">Settings</h1>
          <p className="text-muted-foreground">Platform configuration and admin preferences</p>
        </div>
        <div className="flex items-center gap-3">
          {settings.updatedAt && (
            <span className="text-xs text-muted-foreground">
              Last saved: {new Date(settings.updatedAt).toLocaleString()}
            </span>
          )}
          <Button onClick={handleSave} disabled={saving || settingsLoading}>
            <Save className="mr-2 h-4 w-4" />
            {saving ? 'Saving…' : saved ? 'Saved!' : 'Save Changes'}
          </Button>
        </div>
      </div>

      {/* Kill Switch */}
      <Card
        className={
          killSwitch && !killSwitch.enabled
            ? 'border-destructive bg-destructive/5'
            : 'border-green-500/50 bg-green-500/5'
        }
      >
        <CardHeader>
          <div className="flex items-center gap-2">
            <Power
              className={`h-5 w-5 ${killSwitch?.enabled ? 'text-green-500' : 'text-destructive'}`}
            />
            <div className="flex-1">
              <CardTitle className="text-base">Platform Kill Switch</CardTitle>
              <CardDescription>
                Master toggle — disables all apps (desktop, mobile, API) in real time via Cosmos DB
              </CardDescription>
            </div>
          </div>
        </CardHeader>
        <CardContent>
          <div className="flex items-center justify-between">
            <div>
              <p
                className={`text-lg font-semibold ${killSwitch?.enabled ? 'text-green-600 dark:text-green-400' : 'text-destructive'}`}
              >
                {killSwitchLoading
                  ? 'Loading...'
                  : killSwitch?.enabled
                    ? 'PLATFORM ACTIVE'
                    : 'PLATFORM DISABLED'}
              </p>
              {killSwitch && !killSwitch.enabled && killSwitch.reason && (
                <p className="text-sm text-muted-foreground mt-1">Reason: {killSwitch.reason}</p>
              )}
              {killSwitch?.updatedAt && (
                <p className="text-xs text-muted-foreground mt-1">
                  Last changed: {new Date(killSwitch.updatedAt).toLocaleString()} by{' '}
                  {killSwitch.updatedBy}
                </p>
              )}
            </div>
            <Switch
              checked={killSwitch?.enabled ?? true}
              onCheckedChange={toggleKillSwitch}
              disabled={killSwitchLoading || killSwitchToggling}
              className="scale-125"
            />
          </div>
          {killSwitch?.enabled && (
            <>
              <Separator className="my-4" />
              <div>
                <p className="text-sm font-medium mb-3">Per-Platform Control</p>
                <p className="text-xs text-muted-foreground mb-4">
                  Disable individual platforms while keeping others active
                </p>
                <div className="grid grid-cols-2 gap-3">
                  {[
                    { key: 'desktop' as const, label: 'Desktop (macOS/Win)', icon: Monitor },
                    { key: 'ios' as const, label: 'iOS', icon: Smartphone },
                    { key: 'android' as const, label: 'Android', icon: Tablet },
                    { key: 'web' as const, label: 'Web Dashboard', icon: Globe2 },
                  ].map(({ key, label, icon: Icon }) => (
                    <div
                      key={key}
                      className="flex items-center justify-between rounded-lg border p-3"
                    >
                      <div className="flex items-center gap-2">
                        <Icon
                          className={`h-4 w-4 ${killSwitch.platforms?.[key] ? 'text-green-500' : 'text-muted-foreground'}`}
                        />
                        <span className="text-sm">{label}</span>
                      </div>
                      <Switch
                        checked={killSwitch.platforms?.[key] ?? true}
                        onCheckedChange={() => togglePlatform(key)}
                        disabled={killSwitchToggling}
                      />
                    </div>
                  ))}
                </div>
              </div>
            </>
          )}
        </CardContent>
      </Card>

      {/* General */}
      <Card>
        <CardHeader>
          <div className="flex items-center gap-2">
            <Globe className="h-5 w-5 text-muted-foreground" />
            <div>
              <CardTitle className="text-base">General</CardTitle>
              <CardDescription>Basic platform configuration</CardDescription>
            </div>
          </div>
        </CardHeader>
        <CardContent className="space-y-4">
          <div className="grid grid-cols-2 gap-4">
            <div className="space-y-2">
              <Label>Platform Name</Label>
              <Input
                value={settings.platformName}
                onChange={e => setSettings(s => ({ ...s, platformName: e.target.value }))}
              />
            </div>
            <div className="space-y-2">
              <Label>Support Email</Label>
              <Input
                type="email"
                placeholder="support@example.com"
                value={settings.supportEmail}
                onChange={e => setSettings(s => ({ ...s, supportEmail: e.target.value }))}
              />
            </div>
          </div>
          <div className="space-y-2">
            <Label>Default Language</Label>
            <Select
              value={settings.defaultLanguage}
              onValueChange={v => setSettings(s => ({ ...s, defaultLanguage: v }))}
            >
              <SelectTrigger className="w-[200px]">
                <SelectValue />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="en-US">English (US)</SelectItem>
                <SelectItem value="en-GB">English (UK)</SelectItem>
                <SelectItem value="es-ES">Spanish</SelectItem>
                <SelectItem value="fr-FR">French</SelectItem>
                <SelectItem value="de-DE">German</SelectItem>
                <SelectItem value="ja-JP">Japanese</SelectItem>
              </SelectContent>
            </Select>
          </div>
          <Separator />
          <div className="flex items-center justify-between">
            <div>
              <p className="text-sm font-medium">Maintenance Mode</p>
              <p className="text-xs text-muted-foreground">
                Disable all API access for non-admin users
              </p>
            </div>
            <Switch
              checked={settings.maintenanceMode}
              onCheckedChange={v => setSettings(s => ({ ...s, maintenanceMode: v }))}
            />
          </div>
          <div className="flex items-center justify-between">
            <div>
              <p className="text-sm font-medium">Allow Self-Registration</p>
              <p className="text-xs text-muted-foreground">Users can sign up without an invite</p>
            </div>
            <Switch
              checked={settings.allowSelfRegistration}
              onCheckedChange={v => setSettings(s => ({ ...s, allowSelfRegistration: v }))}
            />
          </div>
        </CardContent>
      </Card>

      {/* Azure Configuration — managed via Secrets Manager */}
      <Card>
        <CardHeader>
          <div className="flex items-center gap-2">
            <Key className="h-5 w-5 text-muted-foreground" />
            <div>
              <CardTitle className="text-base">Azure Configuration</CardTitle>
              <CardDescription>
                Azure secrets are managed via the{' '}
                <a
                  href="/ops/secrets"
                  className="text-primary underline underline-offset-2 hover:text-primary/80"
                >
                  Secrets Manager
                </a>{' '}
                (Key Vault)
              </CardDescription>
            </div>
          </div>
        </CardHeader>
        <CardContent>
          <p className="text-sm text-muted-foreground">
            Azure Speech keys, OpenAI keys, Cosmos connection strings, and other secrets are stored
            in Azure Key Vault and resolved at runtime. Use the{' '}
            <a href="/ops/secrets" className="text-primary underline underline-offset-2">
              Secrets Manager
            </a>{' '}
            to view, rotate, or update them.
          </p>
        </CardContent>
      </Card>

      {/* Rate Limiting */}
      <Card>
        <CardHeader>
          <div className="flex items-center gap-2">
            <Shield className="h-5 w-5 text-muted-foreground" />
            <div>
              <CardTitle className="text-base">Rate Limiting</CardTitle>
              <CardDescription>Global rate limits and abuse prevention</CardDescription>
            </div>
          </div>
        </CardHeader>
        <CardContent className="space-y-4">
          <div className="grid grid-cols-2 gap-4">
            <div className="space-y-2">
              <Label>Global Rate Limit (req/min)</Label>
              <Input
                type="number"
                value={settings.rateLimits.globalPerMin}
                onChange={e =>
                  setSettings(s => ({
                    ...s,
                    rateLimits: { ...s.rateLimits, globalPerMin: parseInt(e.target.value) || 0 },
                  }))
                }
              />
            </div>
            <div className="space-y-2">
              <Label>Per-User Rate Limit (req/min)</Label>
              <Input
                type="number"
                value={settings.rateLimits.perUserPerMin}
                onChange={e =>
                  setSettings(s => ({
                    ...s,
                    rateLimits: { ...s.rateLimits, perUserPerMin: parseInt(e.target.value) || 0 },
                  }))
                }
              />
            </div>
          </div>
          <div className="grid grid-cols-2 gap-4">
            <div className="space-y-2">
              <Label>Max Token Burst (per request)</Label>
              <Input
                type="number"
                value={settings.rateLimits.maxTokenBurst}
                onChange={e =>
                  setSettings(s => ({
                    ...s,
                    rateLimits: { ...s.rateLimits, maxTokenBurst: parseInt(e.target.value) || 0 },
                  }))
                }
              />
            </div>
            <div className="space-y-2">
              <Label>Abuse Threshold (failed auth/hr)</Label>
              <Input
                type="number"
                value={settings.rateLimits.abuseThreshold}
                onChange={e =>
                  setSettings(s => ({
                    ...s,
                    rateLimits: { ...s.rateLimits, abuseThreshold: parseInt(e.target.value) || 0 },
                  }))
                }
              />
            </div>
          </div>
          <Separator />
          <div className="flex items-center justify-between">
            <div>
              <p className="text-sm font-medium">Auto-Suspend on Abuse</p>
              <p className="text-xs text-muted-foreground">
                Automatically suspend users exceeding abuse thresholds
              </p>
            </div>
            <Switch
              checked={settings.rateLimits.autoSuspendOnAbuse}
              onCheckedChange={v =>
                setSettings(s => ({ ...s, rateLimits: { ...s.rateLimits, autoSuspendOnAbuse: v } }))
              }
            />
          </div>
          <div className="flex items-center justify-between">
            <div>
              <p className="text-sm font-medium">IP Blocklist</p>
              <p className="text-xs text-muted-foreground">
                Block requests from known malicious IPs
              </p>
            </div>
            <Switch
              checked={settings.rateLimits.ipBlocklist}
              onCheckedChange={v =>
                setSettings(s => ({ ...s, rateLimits: { ...s.rateLimits, ipBlocklist: v } }))
              }
            />
          </div>
        </CardContent>
      </Card>

      {/* Notifications */}
      <Card>
        <CardHeader>
          <div className="flex items-center gap-2">
            <Bell className="h-5 w-5 text-muted-foreground" />
            <div>
              <CardTitle className="text-base">Notifications</CardTitle>
              <CardDescription>Admin alerts and email notifications</CardDescription>
            </div>
          </div>
        </CardHeader>
        <CardContent className="space-y-4">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-sm font-medium">New User Signup</p>
              <p className="text-xs text-muted-foreground">
                Get notified when a new user registers
              </p>
            </div>
            <Switch
              checked={settings.notifications.newUserSignup}
              onCheckedChange={v =>
                setSettings(s => ({
                  ...s,
                  notifications: { ...s.notifications, newUserSignup: v },
                }))
              }
            />
          </div>
          <div className="flex items-center justify-between">
            <div>
              <p className="text-sm font-medium">Usage Threshold Alert</p>
              <p className="text-xs text-muted-foreground">
                Alert when monthly token usage exceeds 80% of budget
              </p>
            </div>
            <Switch
              checked={settings.notifications.usageThreshold}
              onCheckedChange={v =>
                setSettings(s => ({
                  ...s,
                  notifications: { ...s.notifications, usageThreshold: v },
                }))
              }
            />
          </div>
          <div className="flex items-center justify-between">
            <div>
              <p className="text-sm font-medium">Failed Payment</p>
              <p className="text-xs text-muted-foreground">
                Alert when a subscription payment fails
              </p>
            </div>
            <Switch
              checked={settings.notifications.failedPayment}
              onCheckedChange={v =>
                setSettings(s => ({
                  ...s,
                  notifications: { ...s.notifications, failedPayment: v },
                }))
              }
            />
          </div>
          <div className="flex items-center justify-between">
            <div>
              <p className="text-sm font-medium">Security Alerts</p>
              <p className="text-xs text-muted-foreground">
                Suspicious activity and brute-force attempts
              </p>
            </div>
            <Switch
              checked={settings.notifications.securityAlerts}
              onCheckedChange={v =>
                setSettings(s => ({
                  ...s,
                  notifications: { ...s.notifications, securityAlerts: v },
                }))
              }
            />
          </div>
        </CardContent>
      </Card>

      {/* Database */}
      <Card>
        <CardHeader>
          <div className="flex items-center gap-2">
            <Database className="h-5 w-5 text-muted-foreground" />
            <div>
              <CardTitle className="text-base">Database</CardTitle>
              <CardDescription>Storage and data management</CardDescription>
            </div>
          </div>
        </CardHeader>
        <CardContent className="space-y-4">
          <p className="text-sm text-muted-foreground">
            Database connection is configured via environment variables and{' '}
            <a href="/ops/secrets" className="text-primary underline underline-offset-2">
              Secrets Manager
            </a>
            . Cosmos DB endpoint and key are resolved from Azure Key Vault at runtime.
          </p>
          <Separator />
          <div className="grid grid-cols-2 gap-4">
            <div className="space-y-2">
              <Label>Data Retention (days)</Label>
              <Input
                type="number"
                value={settings.dataRetentionDays}
                onChange={e =>
                  setSettings(s => ({ ...s, dataRetentionDays: parseInt(e.target.value) || 365 }))
                }
              />
            </div>
            <div className="space-y-2">
              <Label>Backup Frequency</Label>
              <Select
                value={settings.backupFrequency}
                onValueChange={v => setSettings(s => ({ ...s, backupFrequency: v }))}
              >
                <SelectTrigger>
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="hourly">Hourly</SelectItem>
                  <SelectItem value="daily">Daily</SelectItem>
                  <SelectItem value="weekly">Weekly</SelectItem>
                </SelectContent>
              </Select>
            </div>
          </div>
          <Separator />
          <div className="flex items-center justify-between">
            <div>
              <p className="text-sm font-medium">Audit Logging</p>
              <p className="text-xs text-muted-foreground">Log all admin actions for compliance</p>
            </div>
            <Switch
              checked={settings.auditLogging}
              onCheckedChange={v => setSettings(s => ({ ...s, auditLogging: v }))}
            />
          </div>
        </CardContent>
      </Card>
    </div>
  );
}
