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 BookInterviewScreen extends StatefulWidget {
  int jobseekerId;
  int jobId;

  BookInterviewScreen(
      {super.key, required this.jobId, required this.jobseekerId});

  @override
  State<BookInterviewScreen> createState() => _BookInterviewScreenState();
}

class _BookInterviewScreenState extends State<BookInterviewScreen> {
  DateTime? picked;

  final _globalKey = GlobalKey<FormState>();
  final TextEditingController _address = TextEditingController();
  final TextEditingController _dateTime = TextEditingController();

  @override
  void initState() {
    _dateTime.text = "";

    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return SafeArea(
      child: Scaffold(
        backgroundColor: Colors.transparent,
        body: 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(
                            "Book Interview Now",
                            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: [
                              GlobalMethods.textTitle(label: 'Address :'),
                              GlobalMethods.textFormFields(
                                valuekey: "Address",
                                controller: _address,
                                enabled: true,
                                fct: () {},
                                maxlength: 50,
                              ),
                              GlobalMethods.textTitle(label: 'Date :'),
                              GlobalMethods.textFormFields(
                                valuekey: "Date",
                                controller: _dateTime,
                                enabled: false,
                                fct: () {
                                  _selectDateTime();
                                },
                                maxlength: 50,
                              ),
                              const SizedBox(height: 20),
                              InkWell(
                                onTap: () async {
                                  if (_globalKey.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(
                                      "Send",
                                      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/Interviews/BookInterview');

      final request = http.MultipartRequest('post', url)
        ..fields['address'] = _address.text
        ..fields['companyId'] = identifier.id.toString()
        ..fields['jobSeekerId'] = widget.jobseekerId.toString()
        ..fields['jobId'] = widget.jobId.toString()
        ..fields['date'] = _dateTime.text;
      request.headers['Authorization'] = "Bearer ${identifier.token}";

      ScaffoldMessenger.of(context).showSnackBar(const SnackBar(
        content: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Padding(
              padding: EdgeInsets.all(5.0),
              child: Text("Booking..."),
            ),
            CircularProgressIndicator()
          ],
        ),
        duration: Duration(minutes: 1),
      ));

      var response = await request.send();
      if (response.statusCode == 200) {
        _showAndPop();
      } else {
        _showFail();
      }
    } 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('Interview booked successfully'),
      duration: Duration(seconds: 3),
    ));
  }

  void _showFail() {
    ScaffoldMessenger.of(context).hideCurrentSnackBar();
    ScaffoldMessenger.of(context).showSnackBar(const SnackBar(
      content: Text('There was an error occurred'),
      duration: Duration(seconds: 3),
    ));
  }

  void _selectDateTime() async {
    final selectedDate = await showDatePicker(
      context: context,
      initialDate: DateTime.now(),
      firstDate: DateTime(1900),
      lastDate: DateTime(2100),
    );

    if (selectedDate != null) {
      // ignore: use_build_context_synchronously
      final selectedTime = await showTimePicker(
        context: context,
        initialTime: TimeOfDay.now(),
      );

      if (selectedTime != null) {
        final dateTime = DateTime(
          selectedDate.year,
          selectedDate.month,
          selectedDate.day,
          selectedTime.hour,
          selectedTime.minute,
        );

        setState(() {
          _dateTime.text =
              "${dateTime.year} - ${dateTime.month} - ${dateTime.day} ${dateTime.hour}:${dateTime.minute}";
        });
      }
    }
  }
}
