import 'dart:convert';

import 'package:dio/dio.dart';
import 'package:dropdown_button2/dropdown_button2.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:intl/intl.dart';
import 'package:hamlemuhcrm/core/extensions/log_extension.dart';
import 'package:hamlemuhcrm/core/widgets/not_permission_widget.dart';
import 'package:hamlemuhcrm/features/projects/widgets/employee_type_headline.dart';
import 'package:hamlemuhcrm/features/projects/widgets/multiselect_widgets/selected_employee_chip.dart';
import '../../../../core/extensions/image_enum_extension.dart';
import '../../model/projeler.dart';
import '../../../../data/dropdown_models/personal_getdata_api.dart';
import '../../../../core/constants/url_services_constant.dart';
import '../../../auth/login/cubit/login_cubit.dart';
import '../../cubit/project_cubit.dart';
import '../../../../core/constants/font_styles.dart';
import '../../../../core/extensions/responsive_extension.dart';

import '../../../../../core/constants/color_constants.dart';

class ProjectDetailPage extends StatefulWidget {
  final Projeler projeler;

  const ProjectDetailPage({super.key, required this.projeler});

  @override
  State<ProjectDetailPage> createState() => _ProjectDetailPageState();
}

class _ProjectDetailPageState extends State<ProjectDetailPage> {
  final tfProjeAd = TextEditingController();
  final tfAciklama = TextEditingController();

  String dbSaatbaslangic = '';
  String dbSaatbitis = '';
  String gosterilenSaatbaslangic = '';
  String gosterilenSaatbitis = '';
  DateTime birincidateTime = DateTime.now();
  DateTime ikincidateTime = DateTime.now();
  bool baslangicSecildi = false;
  bool tarihUygun = false;
  final DateFormat format = DateFormat.yMd('tr');

  List<String> _secilenPersonelList = [];
  List<String> _secilenAmirList = [];

  ///////////////////////////////////////////////////////////////////////

  String gonderilenfirmaID = "";
  String? _secilenFirma;
  var gelenFirmalar;
  final String baseURL = URLAPIService.baseURL;

  String kayitliFirma = "0";

  Future<void> firmaData(
      String userfirmid, String token, String loginuserid) async {
    var url = "$baseURL/mobil/api/dd/userfirme_gore_firma_dd_pdo.php";
    var veri = {
      "firma_firmuser_id": userfirmid,
      "token": token,
      "loginuserid": loginuserid
    };
    var cevapFirmalar = await Dio().post(url, data: FormData.fromMap(veri));
    if (cevapFirmalar.statusCode == 200) {
      setState(() {
        gelenFirmalar = json.decode(cevapFirmalar.data.toString()); //
        "gelenFirmalar = $gelenFirmalar".log();
      });
    } else {}
  }

  Widget firmalarDD() {
    List<FirmaDDModel> firmalar =
        List<FirmaDDModel>.from(gelenFirmalar['firmalar'].map(
      (i) {
        return FirmaDDModel.fromJSON(i);
      },
    ));
    firmalar.sort(
      (a, b) => a.firmaIsim.compareTo(b.firmaIsim),
    ); // DROPDOWN SIRALAMASI
    return DropdownButtonHideUnderline(
      child: DropdownButton2(
        hint: const Text(
          'Firma Seçiniz...',
          style: TextStyle(color: Colors.black54, fontSize: 13),
        ),
        isExpanded: true,
        items: firmalar.map((firmalar) {
          return DropdownMenuItem(
            value: firmalar.firmaId,
            child: Text(
                firmalar.firmaIsim.toString().length > 35
                    ? "${firmalar.firmaIsim.toString().substring(0, 34)}.. "
                    : firmalar.firmaIsim,
                style: FontStyles.instance.projectbxDdyazi),
          );
        }).toList(),
        value: _secilenFirma,
        buttonStyleData: ButtonStyleData(
          height: context.dynamicHeight(0.054),
          width: context.dynamicWidth(0.9),
          padding: const EdgeInsets.symmetric(horizontal: 10),
          decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(10),
              color: Colors.white,
              border: Border.all(color: Colors.grey.withOpacity(0.7))),
          elevation: 0,
        ),
        iconStyleData: IconStyleData(
          icon: const Icon(
            Icons.keyboard_arrow_down_outlined, //ilk icon
          ),
          openMenuIcon: const Icon(
              Icons.keyboard_arrow_left_outlined), //açıldıktan sonraki icon
          iconSize: 23,
          iconEnabledColor: ColorsConstants.instance.baseTheme,
          iconDisabledColor: Colors.white,
        ),
        dropdownStyleData: DropdownStyleData(
          maxHeight: context.dynamicHeight(0.17),
          isOverButton: false,
          padding: null,
          decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(10),
            color: ColorsConstants
                .instance.backgroundColor, //açılır menü arkaplan rengi
          ),
          elevation: 8,
          offset: const Offset(0, 0),
          scrollbarTheme: ScrollbarThemeData(
            thumbColor: MaterialStateColor.resolveWith((states) =>
                ColorsConstants
                    .instance.baseTheme), //dropdown scroll rengi değiştirme
            radius: const Radius.circular(10),
            thickness: MaterialStateProperty.all<double>(6),
            thumbVisibility: MaterialStateProperty.all<bool>(true),
          ),
        ),
        menuItemStyleData: const MenuItemStyleData(
          height: 35,
          padding: EdgeInsets.symmetric(horizontal: 14),
        ),
      ),
    );
  }

  //////////////////////////////////////////////////////////////////////////

  @override
  void initState() {
    isFinish = false;
    debugPrint('sayfa proje id : ${widget.projeler.projeId}');
    _degerleriAta();
    firmaData(context.read<LoginCubit>().userfirmId,
            context.read<LoginCubit>().token, context.read<LoginCubit>().id)
        .whenComplete(() {
      if (widget.projeler.projeFirmaId != '' &&
          widget.projeler.projeFirmaId != null) {
        _secilenFirma = widget.projeler.projeFirmaId;
      }
      isFinish = true;
    });
    super.initState();
  }

  void _degerleriAta() {
    tfProjeAd.text = widget.projeler.projeAd!;
    dbSaatbaslangic = widget.projeler.projeBaslangicTarihi!;
    String trTarihBaslangic = format.format(DateTime.parse(dbSaatbaslangic));
    gosterilenSaatbaslangic = trTarihBaslangic;
    dbSaatbitis = widget.projeler.projeBitisTarihi!;
    String trTarihBitis = format.format(DateTime.parse(dbSaatbitis));
    gosterilenSaatbitis = trTarihBitis;
    tfAciklama.text = widget.projeler.projeAciklama!;
    seciliSorumlulariEkle();
    seciliGorevlileriEkle();
    kayitliFirma = context.read<LoginCubit>().userfirmId;
  }

  @override
  void deactivate() {
    super.deactivate();
    context.read<ProjectCubit>().secilenPersonelAdlar.clear();
    context.read<ProjectCubit>().secilenPersonelIdler.clear();
    context.read<ProjectCubit>().secilenAmirAdlar.clear();
    context.read<ProjectCubit>().secilenAmirIdler.clear();
  }

  void seciliSorumlulariEkle() {
    if (widget.projeler.projeSorumluIsimler! != ',') {
      context.read<ProjectCubit>().secilenAmirAdlar =
          widget.projeler.projeSorumluIsimler!.split(',').toSet().toList();
    }

    if (widget.projeler.projeSorumlular != ',') {
      _secilenAmirList = widget.projeler.projeSorumlular!.split(',');
      context.read<ProjectCubit>().secilenAmirIdler =
          widget.projeler.projeSorumlular!.split(',');
    }
  }

  void seciliGorevlileriEkle() {
    if (widget.projeler.projeGorevliIsimler! != ',') {
      context.read<ProjectCubit>().secilenPersonelAdlar =
          widget.projeler.projeGorevliIsimler!.split(',').toSet().toList();
    }
    if (widget.projeler.projeGorevliler != ',') {
      _secilenPersonelList = widget.projeler.projeGorevliler!.split(',');
      context.read<ProjectCubit>().secilenPersonelIdler =
          widget.projeler.projeGorevliler!.split(',');
    }
  }

  bool isFinish = true;

  @override
  Widget build(BuildContext context) {
    return isFinish
        ? Scaffold(
            appBar: appBar(context),
            body: SingleChildScrollView(
              child: Column(
                children: [
                  SizedBox(
                      height: context.dynamicHeight(0.2),
                      child: ImageEnums.cproject.toPageImage),
                  SizedBox(
                    height: context.dynamicHeight(0.04),
                  ),
                  Padding(
                    padding: EdgeInsets.symmetric(
                        horizontal: context.dynamicWidth(0.07)),
                    child: Column(
                      children: [
                        Column(
                          children: [
                            _headLine(context, 'Firma'),
                            _emptySpace(context),
                            firmalarDD(),
                          ],
                        ),
                        _emptySpace(context),
                        Column(
                          children: [
                            _headLine(context, 'Proje Adı'),
                            _emptySpace(context),
                            _tfProjectContainer,
                          ],
                        ),
                        _emptySpace(context),
                        Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                _headLine(context, 'Başlangıç Tarihi'),
                                _emptySpace(context),
                                _timeContainer(
                                  Row(
                                    mainAxisAlignment:
                                        MainAxisAlignment.spaceBetween,
                                    children: [
                                      Text(
                                        gosterilenSaatbaslangic,
                                        style: FontStyles.instance.ddYazi,
                                      ),
                                      Icon(
                                        Icons.calendar_month_outlined,
                                        size: 23,
                                        color:
                                            ColorsConstants.instance.baseTheme,
                                      ),
                                    ],
                                  ),
                                ),
                              ],
                            ),
                            Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                _headLine(context, 'Bitiş Tarihi'),
                                _emptySpace(context),
                                _timeContainer(
                                  Row(
                                    mainAxisAlignment:
                                        MainAxisAlignment.spaceBetween,
                                    children: [
                                      Text(
                                        gosterilenSaatbitis,
                                        style: FontStyles.instance.ddYazi,
                                      ),
                                      Icon(
                                        Icons.calendar_month_outlined,
                                        size: 23,
                                        color:
                                            ColorsConstants.instance.baseTheme,
                                      ),
                                    ],
                                  ),
                                ),
                              ],
                            ),
                          ],
                        ),
                        _emptySpace(context),
                        Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                _headLine(context, 'Proje Sorumluları'),
                                _emptySpace(context),
                                _selectedEmployeeContainer(_secilenAmirList),
                              ],
                            ),
                            Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                _headLine(context, 'Proje Görevlileri'),
                                _emptySpace(context),
                                _selectedEmployeeContainer(
                                    _secilenPersonelList),
                              ],
                            ),
                          ],
                        ),
                        context.read<ProjectCubit>().secilenAmirIdler.isNotEmpty
                            ? Column(children: [
                                const EmployeeTypeHeadline(
                                    employeeType: "Sorumlular"),
                                SelectedEmployeeWidget(
                                    selectedLeaders: context
                                        .read<ProjectCubit>()
                                        .secilenAmirAdlar)
                              ])
                            : _emptySpace(context),
                        context
                                .read<ProjectCubit>()
                                .secilenPersonelIdler
                                .isNotEmpty
                            ? Column(children: [
                                const EmployeeTypeHeadline(
                                    employeeType: "Görevliler"),
                                SelectedEmployeeWidget(
                                    selectedLeaders: context
                                        .read<ProjectCubit>()
                                        .secilenPersonelAdlar),
                                const Divider(
                                  height: 20,
                                ),
                              ])
                            : SizedBox(height: context.dynamicHeight(0.02)),
                        Column(
                          children: [
                            _headLine(context, 'Açıklama'),
                            _emptySpace(context),
                            _descriptionContainer,
                          ],
                        ),
                        const NotPermissionWidget(moduleName: "Projeyi"),
                      ],
                    ),
                  ),
                ],
              ),
            ),
          )
        : const Scaffold();
  }

  AppBar appBar(BuildContext context) {
    return AppBar(
      backgroundColor: Colors.transparent,
      elevation: 0,
      title: Text(
          widget.projeler.projeAd!.length > 20
              ? widget.projeler.projeAd!.substring(0, 19)
              : widget.projeler.projeAd!,
          style: FontStyles.instance.appbarTitleStyle),
      centerTitle: true,
      actions: [
        IconButton(
            onPressed: () {},
            icon: const Icon(
              Icons.notifications_none_outlined,
              color: Colors.black,
            )),
      ],
      leading: IconButton(
          onPressed: () {
            Navigator.pop(context, true);
          },
          icon: const Icon(
            Icons.arrow_back_ios_new,
            color: Colors.black54,
            size: 20,
          )),
    );
  }

  Widget _timeContainer(Widget child) {
    return Container(
        height: context.dynamicHeight(0.05),
        width: context.dynamicWidth(0.4),
        padding: const EdgeInsets.symmetric(horizontal: 10),
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(10),
          color: Colors.white,
          border: Border.all(
            color: Colors.grey.withOpacity(0.6),
          ),
        ),
        child: child);
  }

  Widget get _tfProjectContainer => Container(
        height: context.dynamicHeight(0.05),
        width: context.dynamicWidth(0.88),
        padding: const EdgeInsets.symmetric(horizontal: 7),
        alignment: Alignment.centerLeft,
        decoration: BoxDecoration(
            color: Colors.white,
            border: Border.all(color: Colors.grey.shade400),
            borderRadius: BorderRadius.circular(10)),
        child: SingleChildScrollView(
          scrollDirection: Axis.horizontal,
          child: Text(
            widget.projeler.projeAd ?? "boş",
            style: FontStyles.instance.projectbxDdyazi,
          ),
        ),
      );

  Widget _selectedEmployeeContainer(List<String> list) => Container(
        height: context.dynamicHeight(0.055),
        width: context.dynamicWidth(0.40),
        padding: const EdgeInsets.symmetric(horizontal: 10),
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(10),
          color: list.isNotEmpty ? Colors.grey.shade200 : Colors.white,
          border: Border.all(
            color: Colors.grey.withOpacity(0.6),
          ),
        ),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Text(
              list.isNotEmpty ? 'Seçildi' : '',
              style: const TextStyle(fontSize: 13.5),
            ),
            Icon(
              Icons.arrow_drop_down_sharp,
              size: 23,
              color: ColorsConstants.instance.baseTheme,
            )
          ],
        ),
      );

  Widget get _descriptionContainer => Container(
        padding: const EdgeInsets.all(5),
        height: context.dynamicHeight(0.14),
        width: context.dynamicWidth(1),
        decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.circular(10),
            border: Border.all(color: Colors.grey.withOpacity(0.6))),
        child: SingleChildScrollView(
          child: Text(
            widget.projeler.projeAciklama ?? "boş",
            style: FontStyles.instance.projectbxDdyazi,
          ),
        ),
      );

  Widget _emptySpace(BuildContext context) {
    return SizedBox(
      height: context.dynamicHeight(0.01),
    );
  }

  Widget _headLine(BuildContext context, String title,
      {bool isRequired = true}) {
    return Row(
      children: [
        Text(
          title,
          style: FontStyles.instance.projectbxBaslik,
        ),
        isRequired
            ? Row(
                children: [
                  SizedBox(
                    width: context.dynamicWidth(0.01),
                  ),
                  Text(
                    '(zorunlu)',
                    style: FontStyles.instance.employeetbxRequired,
                  ),
                ],
              )
            : const SizedBox.shrink()
      ],
    );
  }
}
