import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:http/http.dart' as http;
import 'package:image_picker/image_picker.dart';
import 'package:hamlemuhcrm/core/constants/url_services_constant.dart';
import 'package:hamlemuhcrm/core/extensions/log_extension.dart';
import 'package:hamlemuhcrm/core/route/page_route.dart';
import 'package:hamlemuhcrm/features/auth/splash/view/splash_view.dart';
import 'package:hamlemuhcrm/features/profile/model/profile_constant_detail.dart';

import '../../auth/login/cubit/login_cubit.dart';
import '../model/profile_detail.dart';
import '../widgets/profile_update_bottom_sheet.dart';
import 'profile_view.dart';

mixin ProfileViewMixin on State<ProfileView> {
  final ImagePicker _imagePicker = ImagePicker();
  File? uploadimage;
  String fileName = "";
  bool success = false;

  Future<void> chooseImage() async {
    var chooseimage = await _imagePicker.pickImage(source: ImageSource.gallery);

    if (chooseimage == null) {
      // Kullanıcı resim seçmeyi iptal etti, işlemi sonlandırabilirsiniz.
      return;
    }

    setState(() {
      uploadimage = File(chooseimage.path);
      fileName = chooseimage.name;
    });
  }

  Future<void> uploadImage(
    File imageFile,
    String userId,
    String loginUserId,
    String loginUserType,
    String loginUserFirmId,
    String token,
    String userEmail,
    String oldImage,
  ) async {
    // API endpoint ve dosya adı
    final url = Uri.parse(URLAPIService.instance.addPhotoURL);
    final fileName = imageFile.path.split('/').last;

    // multipart/form-data isteği oluşturma
    final request = http.MultipartRequest('POST', url)
      ..fields['user_id'] = userId
      ..fields['loginuserid'] = loginUserId
      ..fields['loginusertype'] = loginUserType
      ..fields['login_userfirm_id'] = loginUserFirmId
      ..fields['token'] = token
      ..fields['user_email'] = userEmail
      ..fields['old_image'] = oldImage
      ..files.add(await http.MultipartFile.fromPath(
        'image',
        imageFile.path,
        filename: fileName,
      ));

    // isteği gönderme ve cevabı alma
    final response = await http.Response.fromStream(await request.send());

    // istek başarılıysa 200 döndürür
    if (response.statusCode == 200) {
      'Resim başarıyla yüklendi.'.log();
      response.body.log();
      success = true;
    } else {
      'Resim yüklenirken bir hata oluştu. Hata kodu: ${response.statusCode}'
          .log();
      success = false;
    }
  }

  late bool isFinish;

  @override
  void initState() {
    isFinish = false;
    super.initState();
    isFinish = true;
  }

  void appRefresh() {
    Navigator.pushReplacement(
        context, CustomPageRoute(child: const SplashView()));
  }

  Future<void> showProfileUpdateBottomSheet(BuildContext context) async {
    final data = await showModalBottomSheet<bool>(
      context: context,
      showDragHandle: true,
      scrollControlDisabledMaxHeightRatio: 0.7,
      builder: (context) {
        return Padding(
          padding: MediaQuery.of(context).viewInsets,
          child: ProfileUpdateBottomSheet(
            constantData: ProfileConstantDetail(
                email: context.read<LoginCubit>().email,
                fullName:
                    '${context.read<LoginCubit>().ad} ${context.read<LoginCubit>().soyad}',
                secondMail: context.read<LoginCubit>().bildirimMail),
            currentData: ProfileDetail(
                password: '**********',
                telNumber: context.read<LoginCubit>().ceptelefon),
          ),
        );
      },
    );

    if (data == null) return;

    if (data) return appRefresh();
  }
}
