import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:getx_scaffold/getx_scaffold.dart';

import 'controller.dart';

class UrlHostPage extends GetView<UrlHostController> {
  const UrlHostPage({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    Get.put(UrlHostController());

    return Scaffold(
      appBar: AppBar(
        title: const Text('域名配置'),
        centerTitle: true,
      ),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: [
            const Text(
              '当前环境配置',
              style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
            ),
            const SizedBox(height: 12),
            TextField(
              controller: controller.urlController,
              decoration: InputDecoration(
                hintText: '请输入或选择API域名',
                border: OutlineInputBorder(
                  borderRadius: BorderRadius.circular(8),
                ),
                contentPadding: const EdgeInsets.symmetric(horizontal: 12, vertical: 14),
              ),
            ),
            const SizedBox(height: 24),
            const Text(
              '预设环境',
              style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
            ),
            const SizedBox(height: 8),
            Expanded(
              child: ListView.builder(
                itemCount: controller.presetUrls.length,
                itemBuilder: (context, index) {
                  final url = controller.presetUrls[index];
                  return Card(
                    elevation: 1,
                    margin: const EdgeInsets.only(bottom: 8),
                    child: ListTile(
                      title: Text(controller.urlNames[index], style: const TextStyle(fontSize: 14)),
                      subtitle: Text(url, style: const TextStyle(fontSize: 14)),
                      trailing: const Icon(Icons.touch_app, size: 18, color: Colors.grey),
                      onTap: () {
                        // 点击列表项：先填入编辑框，然后直接保存退出
                        controller.selectUrl(url);
                        controller.saveAndExit();
                      },
                    ),
                  );
                },
              ),
            ),
            ElevatedButton(
              onPressed: controller.saveAndExit,
              style: ElevatedButton.styleFrom(
                minimumSize: const Size(double.infinity, 48),
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(8),
                ),
              ),
              child: const Text('保存配置', style: TextStyle(fontSize: 16)),
            ),
          ],
        ),
      ),
    );
  }
}
