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';
import '../../data/Common/skill.dart';

// ignore: must_be_immutable
class UpdateSkillScreen extends StatelessWidget {
  Skill skill;

  UpdateSkillScreen(this.skill, {super.key});

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

// ignore: must_be_immutable
class MyCustomForm extends StatefulWidget {
  Skill skill;

  MyCustomForm(this.skill, {super.key});

  @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 {
      final url = Uri.parse('$myUrl/api/CVs/UpdateSkill/${identifier.id}');
      ScaffoldMessenger.of(context).showSnackBar(const SnackBar(
        content: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Padding(
              padding: EdgeInsets.all(5.0),
              child: Text("Updating..."),
            ),
            CircularProgressIndicator()
          ],
        ),
        duration: Duration(minutes: 1),
      ));
      final response = await http.put(
        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,
          'skillId': widget.skill.skillId.toString()
        }),
      );

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

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

  void _showFail() {
    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) {
    _nameController.text = widget.skill.name;
    _periodController.text = widget.skill.practicePeriod;

    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(
                            "Update your 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(
                                      "Update Skill",
                                      style: TextStyle(
                                          fontWeight: FontWeight.bold,
                                          color: Colors.white,
                                          fontSize: 18),
                                    ),
                                  ),
                                )),
                              ),
                              const SizedBox(height: 20),
                            ],
                          ),
                        ),
                      )
                    ],
                  ),
                ),
              ),
            )),
          )),
    );
  }
}
