import { useEffect, useState, type FormEvent } from 'react';
import { Card } from '@/components/ui/Card';
import { Input } from '@/components/ui/Input';
import { Toggle } from '@/components/ui/Toggle';
import { Button } from '@/components/ui/Button';
import { useToast } from '@/components/ui/Toast';
import { ownerAPI } from '@/api/client';
import { staggerContainer, staggerItem } from '@/lib/animations';
import { motion } from 'framer-motion';

export default function SystemConfig() {
  const { toast } = useToast();
  const [config, setConfig] = useState<any>({});
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);

  useEffect(() => {
    ownerAPI.getConfig().then(({ data }) => setConfig(data)).catch(() => {}).finally(() => setLoading(false));
  }, []);

  async function handleSave(e: FormEvent) {
    e.preventDefault();
    setSaving(true);
    try {
      await ownerAPI.updateConfig(config);
      toast('Configuration saved', 'success');
    } catch {
      toast('Failed to save configuration', 'error');
    } finally {
      setSaving(false);
    }
  }

  function updateField(key: string, value: any) {
    setConfig((prev: any) => ({ ...prev, [key]: value }));
  }

  return (
    <div className="p-6">
      <h1 className="text-xl font-bold text-text-primary mb-6">Platform Configuration</h1>

      <form onSubmit={handleSave}>
        <motion.div variants={staggerContainer} initial="initial" animate="animate" className="space-y-6">
          <motion.div variants={staggerItem}>
            <Card>
              <h2 className="text-sm font-bold text-text-muted uppercase tracking-widest mb-4">General</h2>
              <div className="space-y-4">
                <Input label="Site Name" value={config.site_name || ''} onChange={(e) => updateField('site_name', e.target.value)} />
                <Input label="Public Domain" value={config.public_domain || ''} onChange={(e) => updateField('public_domain', e.target.value)} />
                <Input label="Public Host (IP)" value={config.public_host || ''} onChange={(e) => updateField('public_host', e.target.value)} />
                <Toggle checked={!!config.maintenance_mode} onChange={(v) => updateField('maintenance_mode', v)} label="Maintenance Mode" />
              </div>
            </Card>
          </motion.div>

          <motion.div variants={staggerItem}>
            <Card>
              <h2 className="text-sm font-bold text-text-muted uppercase tracking-widest mb-4">CS2 Servers</h2>
              <div className="grid grid-cols-2 gap-4">
                <Input label="Port Range Start" type="number" value={config.port_range_start || 27015} onChange={(e) => updateField('port_range_start', parseInt(e.target.value))} />
                <Input label="Port Range End" type="number" value={config.port_range_end || 27064} onChange={(e) => updateField('port_range_end', parseInt(e.target.value))} />
                <Input label="Max Concurrent Servers" type="number" value={config.max_concurrent || 50} onChange={(e) => updateField('max_concurrent', parseInt(e.target.value))} />
                <Input label="Server Timeout (seconds)" type="number" value={config.server_timeout || 120} onChange={(e) => updateField('server_timeout', parseInt(e.target.value))} />
              </div>
            </Card>
          </motion.div>

          <div className="flex justify-end">
            <Button type="submit" loading={saving} size="lg">Save Changes</Button>
          </div>
        </motion.div>
      </form>
    </div>
  );
}
