import 'dart:developer';
import 'dart:io';
import 'package:elysia/page/FollowListPage.dart';
import 'package:elysia/plugin/HTTP.dart';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'package:oktoast/oktoast.dart';

import '../../plugin/C.dart';
import '../../plugin/CacheAavatar.dart';
import '../../plugin/LoadingOverlay.dart';
import 'IconSwitch.dart';
import '../../plugin/AvatarPicker.dart';
import 'MyRobotPage.dart';

class EditorRobotPage extends StatefulWidget {
  final RobotItem robotItem;

  const EditorRobotPage({super.key, required this.robotItem});

  @override
  State<EditorRobotPage> createState() => _EditorRobotPageState();
}

class _EditorRobotPageState extends State<EditorRobotPage> {
  final _formKey = GlobalKey<FormState>();

  String name = '';
  String describe = '';
  String systemPrompt = '';
  bool isPrivate = false;

  Future<void> saveRobot() async {
    if (!_formKey.currentState!.validate()) return;

    _formKey.currentState!.save();

    // 这里可以替换成上传接口或数据库操作
    LoadingOverlay.show(context: context, barrierColor: Colors.black54);
    try {
      dynamic result = await HTTP
          .create("${C.BASE_URL}/robot/editor/${widget.robotItem.robotId}")
          .setHeader(C.TOKEN)
          .setBody({"systemPrompt": systemPrompt, "private": isPrivate})
          .setRequestType(RequestType.POST)
          .execute();
      LoadingOverlay.hide();

      log(result.toString());
      if (result["code"] != 200) {
        showToast(result["message"]);
      } else {
        RobotItem robotItem = RobotItem(
          robotId: widget.robotItem.robotId,
          name: widget.robotItem.name,
          avatar: widget.robotItem.avatar,
          describe: widget.robotItem.describe,
          systemPrompt: systemPrompt,
          isPrivate: isPrivate,
          follow: widget.robotItem.follow,
        );
        Navigator.pop(context, robotItem);
        FollowListPage.flushData!(true);
      }
    } catch (e) {
      print(e);
      LoadingOverlay.hide();
    }
  }

  @override
  void initState() {
    super.initState();
    setState(() {
      name = widget.robotItem.name;
      describe = widget.robotItem.describe;
      systemPrompt = widget.robotItem.systemPrompt;
      isPrivate = widget.robotItem.isPrivate;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBar(
        title: const Text("修改器人", style: TextStyle(color: Colors.black)),
        centerTitle: true,
        backgroundColor: Colors.grey[100],
        leading: IconButton(
          icon: const Icon(Icons.arrow_back, color: Colors.black),
          onPressed: () => Navigator.pop(context),
        ),
        elevation: 0, // 去掉 AppBar 阴影
      ),
      body: SingleChildScrollView(
        padding: const EdgeInsets.all(16),
        child: Form(
          key: _formKey,
          child: Column(
            children: [
              CacheAvatar(
                url: widget.robotItem.avatar,
                size: Size(110, 110),
                circular: 120,
              ),
              const SizedBox(height: 20),

              // 名称输入
              Card(
                elevation: 0,
                color: Colors.grey[100],
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(12),
                ),
                child: Padding(
                  padding: const EdgeInsets.symmetric(
                    horizontal: 16,
                    vertical: 4,
                  ),
                  child: TextFormField(
                    readOnly: true,
                    initialValue: name,
                    decoration: InputDecoration(border: InputBorder.none),
                  ),
                ),
              ),
              const SizedBox(height: 12),

              // 描述输入
              Card(
                elevation: 0,
                color: Colors.grey[100],
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(12),
                ),
                child: Padding(
                  padding: const EdgeInsets.symmetric(
                    horizontal: 16,
                    vertical: 4,
                  ),
                  child: TextFormField(
                    readOnly: true,
                    initialValue: describe,
                    decoration: InputDecoration(border: InputBorder.none),
                    maxLines: 2,
                  ),
                ),
              ),
              const SizedBox(height: 12),

              // 系统提示词
              Card(
                elevation: 0,
                color: Colors.grey[100],
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(12),
                ),
                child: Padding(
                  padding: const EdgeInsets.symmetric(
                    horizontal: 16,
                    vertical: 4,
                  ),
                  child: TextFormField(
                    initialValue: systemPrompt,
                    maxLines: 20,
                    scrollPhysics: BouncingScrollPhysics(),
                    decoration: const InputDecoration(
                      hintText: '系统提示词',
                      border: InputBorder.none,
                    ),
                    onSaved: (value) => systemPrompt = value!.trim(),
                  ),
                ),
              ),
              const SizedBox(height: 16),

              // 是否私有
              Container(
                padding: const EdgeInsets.symmetric(
                  horizontal: 16,
                  vertical: 12,
                ),
                decoration: BoxDecoration(
                  color: Colors.grey[100],
                  borderRadius: BorderRadius.circular(12),
                ),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    const Text(
                      '是否私有',
                      style: TextStyle(
                        fontSize: 16,
                        fontWeight: FontWeight.w500,
                      ),
                    ),
                    IconSwitch(
                      value: isPrivate,
                      onChanged: (val) => setState(() => isPrivate = val),
                    ),
                  ],
                ),
              ),
              const SizedBox(height: 24),

              // 保存按钮
              SizedBox(
                width: double.infinity,
                height: 50,
                child: ElevatedButton(
                  onPressed: saveRobot,
                  style: ElevatedButton.styleFrom(
                    elevation: 0, // 去掉按钮阴影
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(12),
                    ),
                  ),
                  child: const Text(
                    '保存',
                    style: TextStyle(fontSize: 18, color: Colors.white),
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}
