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

import 'package:flutter/material.dart';
import 'package:flutter_image_compress/flutter_image_compress.dart';
import 'package:http/http.dart' as http;
import 'package:job_portal_app/Services/global_variables.dart';
import 'package:job_portal_app/logic/from_json.dart';
import 'package:path_provider/path_provider.dart';

import '../../Services/global_methods.dart';
import '../../Widgets/edit_image_profile_widget.dart';
import '../../data/Company/company.dart';
import 'company_profile_screen.dart';

// ignore: must_be_immutable
class EditCompanyInformationScreen extends StatefulWidget {
  Company? company;

  EditCompanyInformationScreen({super.key, required this.company});

  @override
  State<EditCompanyInformationScreen> createState() =>
      _EditCompanyInformationScreenState();
}

class _EditCompanyInformationScreenState
    extends State<EditCompanyInformationScreen> {
  File? image;
  final _globalKey = GlobalKey<FormState>();
  final TextEditingController _name = TextEditingController();
  final TextEditingController _phone = TextEditingController();
  final TextEditingController _email = TextEditingController();
  final TextEditingController _description = TextEditingController();
  final TextEditingController _address = TextEditingController();
  bool isPhoneSuccess = false;

  void handleImagePicked(File pickedImage) {
    setState(() {
      image = pickedImage;
    });
  }

  @override
  void initState() {
    _name.text = widget.company!.name;
    _email.text = widget.company!.email;
    _address.text = widget.company!.address;
    _description.text = widget.company!.description;
    _phone.text = widget.company!.phone;
    super.initState();
  }

  @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(
                            "Update Your Infomation",
                            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: _globalKey,
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              EditImageProfileWidget(
                                onImagePicked: handleImagePicked,
                                imageUrl: widget.company!.image,
                              ),
                              const SizedBox(height: 20),
                              GlobalMethods.textTitle(label: 'Email :'),
                              GlobalMethods.emailTextField(controller: _email),
                              GlobalMethods.textTitle(label: 'Name :'),
                              GlobalMethods.textFormFields(
                                valuekey: "Name",
                                controller: _name,
                                enabled: true,
                                fct: () {},
                                maxlength: 50,
                              ),
                              GlobalMethods.textTitle(label: 'Address :'),
                              GlobalMethods.textFormFields(
                                valuekey: "Address",
                                controller: _address,
                                enabled: true,
                                fct: () {},
                                maxlength: 50,
                              ),
                              GlobalMethods.textTitle(label: 'Phone :'),
                              _phoneTextField(),
                              GlobalMethods.textTitle(label: 'Description :'),
                              GlobalMethods.textFormFields(
                                valuekey: "Description",
                                controller: _description,
                                enabled: true,
                                fct: () {},
                                maxlength: 500,
                              ),
                              const SizedBox(height: 20),
                              InkWell(
                                onTap: () async {
                                  try {
                                    if (_globalKey.currentState!.validate()) {
                                      if (isPhoneSuccess) {
                                        await _submitForm();
                                      } else {
                                        GlobalMethods.showErrorDialog(
                                            error: "enter valid phone number",
                                            ctx: context);
                                      }
                                    }
                                  } catch (e) {
                                    ScaffoldMessenger.of(context)
                                        .hideCurrentSnackBar();
                                    GlobalMethods.showErrorDialog(
                                        error: e.toString(), ctx: context);
                                  }
                                },
                                child: Center(
                                    child: Container(
                                  width: 200,
                                  height: 50,
                                  decoration: BoxDecoration(
                                      borderRadius: BorderRadius.circular(10),
                                      color: Colors.black),
                                  child: const Center(
                                    child: Text(
                                      "Update",
                                      style: TextStyle(
                                          fontWeight: FontWeight.bold,
                                          color: Colors.white,
                                          fontSize: 18),
                                    ),
                                  ),
                                )),
                              ),
                              const SizedBox(height: 20),
                            ],
                          ),
                        ),
                      )
                    ],
                  ),
                ),
              ),
            )),
          )),
    );
  }

  Future<void> _submitForm() async {
    try {
      final url = Uri.parse('$myUrl/api/Companies/id?id=${identifier.id}');
      final request = http.MultipartRequest('put', url)
        ..fields['name'] = _name.text
        ..fields['phone'] = _phone.text
        ..fields['email'] = _email.text
        ..fields['address'] = _address.text
        ..fields['description'] = _description.text;
      request.headers['Authorization'] = "Bearer ${identifier.token}";

      if (image != null) {
        final compressedImage = await FlutterImageCompress.compressWithFile(
          image!.path,
          format: CompressFormat.webp,
          quality: 80,
        );

        final tempDir = await getTemporaryDirectory();
        final tempFile = File('${tempDir.path}/image.webp');
        await tempFile.writeAsBytes(compressedImage!);

        request.files
            .add(await http.MultipartFile.fromPath("image", tempFile.path));
      }

      _showUpdating();
      var response = await request.send();
      var responseBody = await response.stream.bytesToString();

      if (response.statusCode == 200) {
        _showSuccess();
      } else {
        String error;
        error = fromJson.toErrors(json.decode(responseBody));
        _showFail(error);
      }
    } catch (e) {
      GlobalMethods.showErrorDialog(ctx: context, error: e.toString());
    }
  }

  void _showUpdating() {
    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: 3),
    ));
  }

  void _showSuccess() {
    ScaffoldMessenger.of(context).hideCurrentSnackBar();
    ScaffoldMessenger.of(context).showSnackBar(const SnackBar(
      content: Text('Your profile was updated successfully'),
      duration: Duration(seconds: 3),
    ));
    _goToProfile(context);
  }

  void _showFail(String error) {
    ScaffoldMessenger.of(context).hideCurrentSnackBar();
    GlobalMethods.showErrorDialog(error: error, ctx: context);
  }

  void _goToProfile(context) {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        backgroundColor: Colors.black87,
        title: const Row(
          children: [
            Padding(
              padding: EdgeInsets.all(8.0),
              child: Icon(
                Icons.logout,
                size: 20,
                color: Colors.white,
              ),
            ),
            Padding(
              padding: EdgeInsets.all(8.0),
              child: Text(
                "Updated Successfully",
                style: TextStyle(color: Colors.white, fontSize: 20),
              ),
            ),
          ],
        ),
        content: const Text(
          "Show your profile?",
          style: TextStyle(color: Colors.white, fontSize: 20),
        ),
        actions: [
          TextButton(
              onPressed: () {
                Navigator.canPop(context) ? Navigator.pop(context) : Null;
              },
              child: const Text(
                "No",
                style: TextStyle(color: Colors.green, fontSize: 16),
              )),
          TextButton(
              onPressed: () {
                Navigator.canPop(context) ? Navigator.pop(context) : Null;
                Navigator.pushReplacement(
                    context,
                    MaterialPageRoute(
                        builder: (context) => const CompanyProfileScreen()));
              },
              child: const Text(
                "Yes",
                style: TextStyle(color: Colors.green, fontSize: 16),
              )),
        ],
      ),
    );
  }

  Widget _phoneTextField() {
    return Padding(
      padding: const EdgeInsets.all(5.0),
      child: TextFormField(
        key: const ValueKey("Phone"),
        maxLength: 10,
        textInputAction: TextInputAction.next,
        keyboardType: TextInputType.phone,
        controller: _phone,
        enabled: true,
        validator: (value) {
          if ((value!.length != 10) || (value[0] != "0" || value[1] != "9")) {
            return "enter ten numbers starts with 09";
          } else {
            setState(() {
              isPhoneSuccess = true;
            });
            return null;
          }
        },
        style: const TextStyle(color: Colors.black),
        decoration: const InputDecoration(
          filled: true,
          fillColor: Colors.white54,
          counterStyle: TextStyle(color: Colors.black54),
          enabledBorder: UnderlineInputBorder(
            borderSide: BorderSide(color: Colors.black),
          ),
          focusedBorder: UnderlineInputBorder(
            borderSide: BorderSide(color: Colors.black),
          ),
          errorBorder: UnderlineInputBorder(
            borderSide: BorderSide(color: Colors.red),
          ),
        ),
      ),
    );
  }
}
