import { useEffect, useState } from 'react';
import { Typography, Card, Form, Input, Button, Space, message, Descriptions } from 'antd';
import { api } from '@/lib/api';

export default function SettingsPage() {
  const [settings, setSettings] = useState<Record<string, unknown>>({});
  const [loading, setLoading] = useState(true);
  const [savingPangolin, setSavingPangolin] = useState(false);
  const [savingDefaults, setSavingDefaults] = useState(false);

  useEffect(() => {
    api.get('/settings').then(({ data }) => {
      setSettings(data.data);
      setLoading(false);
    }).catch(() => {
      message.error('Failed to load settings');
      setLoading(false);
    });
  }, []);

  const saveMultipleSettings = async (keys: string[], setLoading: (v: boolean) => void) => {
    setLoading(true);
    try {
      await Promise.all(keys.map((key) => api.put(`/settings/${key}`, { value: settings[key] })));
      message.success('Settings saved');
    } catch {
      message.error('Failed to save some settings');
    } finally {
      setLoading(false);
    }
  };

  return (
    <div>
      <Typography.Title level={3}>Settings</Typography.Title>

      <Space direction="vertical" size="large" style={{ width: '100%', maxWidth: 800 }}>
        <Card title="Port Allocation Ranges" loading={loading}>
          <Descriptions bordered column={1} size="small">
            <Descriptions.Item label="API Ports">14000 - 14999</Descriptions.Item>
            <Descriptions.Item label="Admin Ports">13000 - 13999</Descriptions.Item>
            <Descriptions.Item label="PostgreSQL Ports">15400 - 15499</Descriptions.Item>
            <Descriptions.Item label="Nginx Ports">10000 - 10999</Descriptions.Item>
          </Descriptions>
          <Typography.Text type="secondary" style={{ display: 'block', marginTop: 8 }}>
            Port ranges are configured via environment variables and cannot be changed at runtime.
          </Typography.Text>
        </Card>

        <Card title="Pangolin API Configuration" loading={loading}>
          <Form layout="vertical">
            <Form.Item label="Pangolin API URL">
              <Input
                value={(settings.pangolinApiUrl as string) || ''}
                onChange={(e) => setSettings({ ...settings, pangolinApiUrl: e.target.value })}
                placeholder="https://api.pangolin.example.com/v1"
              />
            </Form.Item>
            <Form.Item label="Pangolin API Key">
              <Input.Password
                value={(settings.pangolinApiKey as string) || ''}
                onChange={(e) => setSettings({ ...settings, pangolinApiKey: e.target.value })}
                placeholder="API key"
              />
            </Form.Item>
            <Form.Item label="Pangolin Org ID">
              <Input
                value={(settings.pangolinOrgId as string) || ''}
                onChange={(e) => setSettings({ ...settings, pangolinOrgId: e.target.value })}
                placeholder="Organization ID"
              />
            </Form.Item>
            <Button
              type="primary"
              loading={savingPangolin}
              onClick={() => saveMultipleSettings(['pangolinApiUrl', 'pangolinApiKey', 'pangolinOrgId'], setSavingPangolin)}
            >
              Save Pangolin Settings
            </Button>
          </Form>
        </Card>

        <Card title="Instance Defaults" loading={loading}>
          <Form layout="vertical">
            <Form.Item label="Default Git Branch">
              <Input
                value={(settings.defaultGitBranch as string) || 'v2'}
                onChange={(e) => setSettings({ ...settings, defaultGitBranch: e.target.value })}
              />
            </Form.Item>
            <Form.Item label="Instances Base Path">
              <Input
                value={(settings.instancesBasePath as string) || ''}
                onChange={(e) => setSettings({ ...settings, instancesBasePath: e.target.value })}
              />
            </Form.Item>
            <Button
              type="primary"
              loading={savingDefaults}
              onClick={() => saveMultipleSettings(['defaultGitBranch', 'instancesBasePath'], setSavingDefaults)}
            >
              Save Defaults
            </Button>
          </Form>
        </Card>
      </Space>
    </div>
  );
}
