import 'dart:convert';
import 'dart:io';

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

import '../../Services/global_methods.dart';

// ignore: must_be_immutable
class AddJobSkillScreen extends StatelessWidget {
  int id;

  AddJobSkillScreen({super.key, required this.id});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: MyCustomForm(id: id),
      ),
    );
  }
}

// ignore: must_be_immutable
class MyCustomForm extends StatefulWidget {
  int id;

  MyCustomForm({super.key, required this.id});

  @override
  // ignore: library_private_types_in_public_api
  _MyCustomFormState createState() => _MyCustomFormState();
}

class _MyCustomFormState extends State<MyCustomForm> {
  final _formKey = GlobalKey<FormState>();
  final _nameController = TextEditingController();
  final _periodController = TextEditingController();

  @override
  void dispose() {
    _nameController.dispose();
    _periodController.dispose();
    super.dispose();
  }

  Future<void> _submitForm() async {
    try {
      ScaffoldMessenger.of(context).showSnackBar(const SnackBar(
        content: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Padding(
              padding: EdgeInsets.all(5.0),
              child: Text("Adding..."),
            ),
            CircularProgressIndicator()
          ],
        ),
        duration: Duration(minutes: 1),
      ));
      final url = Uri.parse('$myUrl/api/Jobs/AddSkills/${widget.id}');
      final response = await http.post(
        url,
        headers: <String, String>{
          'Content-Type': 'application/json; charset=UTF-8',
          HttpHeaders.authorizationHeader: "Bearer ${identifier.token}"
        },
        body: jsonEncode(<String, String>{
          'name': _nameController.text,
          'practicePeriod': _periodController.text,
        }),
      );

      if (response.statusCode == 200) {
        _showAndPop();
      } else {
        _justShow();
      }
    } catch (error) {
      GlobalMethods.showErrorDialog(error: error.toString(), ctx: context);
    }
  }

  void _showAndPop() {
    Navigator.pop(context);
    ScaffoldMessenger.of(context).hideCurrentSnackBar();
    ScaffoldMessenger.of(context).showSnackBar(const SnackBar(
      content: Text('Skill added successfully'),
      duration: Duration(seconds: 3),
    ));
  }

  void _justShow() {
    ScaffoldMessenger.of(context).hideCurrentSnackBar();
    ScaffoldMessenger.of(context).showSnackBar(const SnackBar(
      content: Text('There is an error occured !!!'),
      duration: Duration(seconds: 3),
    ));
  }

  @override
  Widget build(BuildContext context) {
    return SafeArea(
      child: Container(
          decoration: const BoxDecoration(
              gradient: LinearGradient(
                  colors: [Colors.cyan, Colors.greenAccent],
                  begin: Alignment.centerLeft,
                  end: Alignment.centerRight,
                  stops: [0.2, 0.9])),
          child: Scaffold(
            backgroundColor: Colors.transparent,
            appBar: AppBar(
              flexibleSpace: Container(
                decoration: const BoxDecoration(
                    gradient: LinearGradient(
                        colors: [Colors.cyan, Colors.greenAccent],
                        begin: Alignment.centerLeft,
                        end: Alignment.centerRight,
                        stops: [0.2, 0.9])),
              ),
            ),
            body: Center(
                child: Padding(
              padding: const EdgeInsets.all(7.0),
              child: Card(
                color: Colors.white10,
                child: SingleChildScrollView(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      const SizedBox(
                        height: 10,
                      ),
                      const Align(
                        alignment: Alignment.center,
                        child: Padding(
                          padding: EdgeInsets.all(8.0),
                          child: Text(
                            "Add New Skill",
                            style: TextStyle(
                                color: Colors.black,
                                fontSize: 30,
                                fontWeight: FontWeight.bold,
                                fontStyle: FontStyle.italic),
                          ),
                        ),
                      ),
                      const SizedBox(
                        height: 10,
                      ),
                      const Divider(
                        thickness: 1,
                        color: Colors.grey,
                      ),
                      Padding(
                        padding: const EdgeInsets.all(0),
                        child: Form(
                          key: _formKey,
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              const SizedBox(height: 20),
                              GlobalMethods.textTitle(label: 'Skill name :'),
                              GlobalMethods.textFormFields(
                                valuekey: "Skill Name",
                                controller: _nameController,
                                enabled: true,
                                fct: () {},
                                maxlength: 50,
                              ),
                              GlobalMethods.textTitle(
                                  label: 'Practice period :'),
                              GlobalMethods.textFormFields(
                                valuekey: "Practice Period",
                                controller: _periodController,
                                enabled: true,
                                fct: () {},
                                maxlength: 50,
                              ),
                              InkWell(
                                onTap: () async {
                                  if (_formKey.currentState!.validate()) {
                                    await _submitForm();
                                  }
                                },
                                child: Center(
                                    child: Container(
                                  width: 200,
                                  height: 50,
                                  decoration: BoxDecoration(
                                      borderRadius: BorderRadius.circular(10),
                                      color: Colors.black),
                                  child: const Center(
                                    child: Text(
                                      "Add Skill",
                                      style: TextStyle(
                                          fontWeight: FontWeight.bold,
                                          color: Colors.white,
                                          fontSize: 18),
                                    ),
                                  ),
                                )),
                              ),
                              const SizedBox(height: 20),
                            ],
                          ),
                        ),
                      )
                    ],
                  ),
                ),
              ),
            )),
          )),
    );
  }
}
