import 'dart:io';

import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import 'package:momo/models/login_resp.dart';
import 'package:momo/provider/token.dart';
import 'package:momo/request/http_client.dart';

class LoginPage extends StatelessWidget {
  const LoginPage({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: const Text("登录"),
          centerTitle: true,
        ),
        body: const Padding(
          padding: EdgeInsets.fromLTRB(20, 0, 20, 0),
          child: LoginForm(),
        ));
  }
}

class LoginForm extends ConsumerStatefulWidget {
  const LoginForm({Key? key}) : super(key: key);

  @override
  ConsumerState<LoginForm> createState() => _LoginFormState();
}

class _LoginFormState extends ConsumerState<LoginForm> {
  TextEditingController usernameController =
      TextEditingController(text: "kencho");
  TextEditingController passwordController =
      TextEditingController(text: "169482");

  @override
  Widget build(BuildContext context) {
    return ListView(
      children: [
        Form(
            child: Column(
          children: [
            TextFormField(
              controller: usernameController,
              decoration: const InputDecoration(
                enabledBorder: OutlineInputBorder(borderSide: BorderSide()),
                focusedBorder: OutlineInputBorder(borderSide: BorderSide()),
                hintText: 'Enter your username',
              ),
            ),
            const SizedBox(
              height: 20,
            ),
            TextFormField(
              obscureText: true,
              controller: passwordController,
              // keyboardType: TextInputType.,
              decoration: const InputDecoration(
                enabledBorder: OutlineInputBorder(borderSide: BorderSide()),
                focusedBorder: OutlineInputBorder(borderSide: BorderSide()),
                hintText: 'Enter your password',
              ),
            ),
            const SizedBox(
              height: 20,
            ),
          ],
        )),
        ElevatedButton(
            child: const Text("登录"),
            onPressed: () async {
              if (usernameController.text.isEmpty ||
                  passwordController.text.isEmpty) {
                return;
              }
              try {
                Response resp = await dio.post("/user/login", data: {
                  "username": usernameController.text,
                  "password": passwordController.text
                });
                if (resp.statusCode == HttpStatus.ok) {
                  LoginResp loginResp = LoginResp.fromJson(resp.data);
                  ref.watch(tokenProvider.notifier).setToken(loginResp.token);
                } else {
                  print(resp.statusCode);
                }
              } catch (e) {
                if (e is DioError) {
                  print(e.response);
                  ScaffoldMessenger.of(context).showSnackBar(SnackBar(
                      content: Text(e.response?.data["msg"] ?? "请求错误")));
                }
              }
            }),
      ],
    );
  }
}
