import 'dart:convert';

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

import '/utils/storage/session_cookie.dart';
import '/components/user_search_result.dart';
import '/data_models/user_search.dart';
import '/models/my_profile.dart';

class FriendAddSearch extends StatefulWidget {
  const FriendAddSearch({
    Key? key,
  }) : super(key: key);

  @override
  State<FriendAddSearch> createState() => _FriendAddSearchState();
}

class _FriendAddSearchState extends State<FriendAddSearch> {
  UserSearch? user;
  Text centerMessage = const Text('Search to add friends...');

  TextEditingController searchController = TextEditingController();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        elevation: 0,
        automaticallyImplyLeading: false,
        flexibleSpace: SafeArea(
          child: Container(
          padding: const EdgeInsets.only(right: 16),
              child: Row(
                  children: <Widget>[
                    IconButton(
                      onPressed: () {
                        Navigator.pop(context);
                      },
                      icon: Icon(
                              Icons.arrow_back,
                              color: Theme.of(context).appBarTheme.iconTheme?.color,
                            ),
                    ),
                    const SizedBox(width: 2),
                    Expanded(
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: <Widget>[
                          Text(
                            'Add Friends',
                            style: TextStyle(
                              fontSize: 16,
                              fontWeight: FontWeight.w600,
                              color: Theme.of(context).appBarTheme.toolbarTextStyle?.color
                            )
                          ),
                        ],
                      )
                    )
                  ]
                ),
              ),
        ),
      ),
      body: Stack(
        children: <Widget>[
          Padding(
            padding: const EdgeInsets.only(top: 16,left: 16,right: 16),
            child: TextField(
              autofocus: true,
              decoration: InputDecoration(
                hintText: 'Search...',
                prefixIcon: const Icon(
                  Icons.search,
                  size: 20
                ),
                suffixIcon: Padding(
                  padding: const EdgeInsets.only(top: 4, bottom: 4, right: 8),
                  child: OutlinedButton(
                    style: ButtonStyle(
                      backgroundColor: MaterialStateProperty.all(Theme.of(context).colorScheme.secondary),
                      foregroundColor: MaterialStateProperty.all(Theme.of(context).colorScheme.onSecondary),
                      shape: MaterialStateProperty.all(RoundedRectangleBorder(borderRadius: BorderRadius.circular(16.0))),
                      elevation: MaterialStateProperty.all(4),
                    ),
                    onPressed: searchUsername,
                    child: const Icon(Icons.search, size: 25),
                  ),
                ),
              ),
            controller: searchController,
            ),
          ),
          Padding(
            padding: const EdgeInsets.only(top: 90),
            child: showFriend(),
          ),
        ],
      ),
    );
  }

  Widget showFriend() {
    if (user == null) {
      return Center(
        child: centerMessage,
      );
    }

    return UserSearchResult(
      user: user!,
    );
  }

  Future<void> searchUsername() async {
    if (searchController.text.isEmpty) {
      return;
    }

    Map<String, String> params = {};
    params['username'] = searchController.text;
    var uri = await MyProfile.getServerUrl('api/v1/auth/users');
    uri = uri.replace(queryParameters: params);

    var resp = await http.get(
      uri,
      headers: {
        'cookie': await getSessionCookie(),
      }
    );

    if (resp.statusCode != 200) {
      user = null;
      centerMessage = const Text('User not found');
      setState(() {});
      return;
    }

    user = UserSearch.fromJson(
      jsonDecode(resp.body)
    );

    setState(() {});
    FocusScope.of(context).unfocus();
    searchController.clear();
  }
}
