import 'dart:convert';
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;



class QuizGenHomePage extends StatefulWidget {
  @override
  _QuizGenHomePageState createState() => _QuizGenHomePageState();
}

class _QuizGenHomePageState extends State<QuizGenHomePage> {
  final TextEditingController _inputController = TextEditingController();
  String? output;
  bool isLoading = false;

  // Base URL
  final String baseUrl = "https://yuntian-deng-chatgpt4.hf.space/call";

  Future<String?> postRequest(String apiName, List<dynamic> data) async {
    final Uri url = Uri.parse('$baseUrl/$apiName');
    try {
      setState(() {
        isLoading = true;
      });
      final response = await http.post(
        url,
        headers: {"Content-Type": "application/json"},
        body: jsonEncode({"data": data}),
      );
      print(response.statusCode);
      if (response.statusCode == 200) {
        final responseBody = jsonDecode(response.body);

        // Check if responseBody is a Map or List
        if (responseBody is List && responseBody.isNotEmpty) {
          return responseBody[0].toString();
        } else if (responseBody is Map) {
          return responseBody["data"]?[0]?.toString();
        } else {
          return "Unexpected response format: $responseBody";
        }
      } else {
        return "Error: ${response.statusCode}";
      }
    } catch (e) {
      return "Error: $e";
    } finally {
      setState(() {
        isLoading = false;
      });
    }
  }


  Future<void> enableInputs() async {
    final result = await postRequest("enable_inputs", []);
    setState(() {
      output = result;
    });
  }


  Future<void> resetTextbox() async {
    final result = await postRequest("reset_textbox", []);
    setState(() {
      output = result;
    });
  }

  Future<void> predict(String input, double topP, double temperature,
      int parameter16, List<List<dynamic>> parameter4) async {
    final result = await postRequest("predict", [
      input,
      topP,
      temperature,
      parameter16,
      parameter4,
    ]);
    setState(() {
      output = result;
    });
    print(output);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("API Interaction"),
      ),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          children: [
            TextField(
              controller: _inputController,
              decoration: InputDecoration(
                labelText: "Input",
                border: OutlineInputBorder(),
              ),
            ),
            const SizedBox(height: 16),
            ElevatedButton(
              onPressed: enableInputs,
              child: Text("Enable Inputs"),
            ),
            ElevatedButton(
              onPressed: resetTextbox,
              child: Text("Reset Textbox"),
            ),
            ElevatedButton(
              onPressed: () {
                predict(
                  _inputController.text,
                  0.0, // Example Top-p value
                  0.0, // Example Temperature
                  3,   // Example parameter_16
                  [["Hello!", null]], // Example parameter_4
                );
              },
              child: Text("Predict"),
            ),
            const SizedBox(height: 16),

            if (isLoading)
              CircularProgressIndicator()

            else if (output != null)
              Text(
                "Output: $output",
                style: TextStyle(fontSize: 16),
              ),
          ],
        ),
      ),
    );

  }
}
I/flutter (26484): 200
I/flutter (26484): null