import 'package:cross_file/cross_file.dart';
import 'package:dio/dio.dart';
import 'package:equatable/equatable.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:hoshan/core/utils/date_time.dart';
import 'package:hoshan/data/model/ticket_model.dart';
import 'package:hoshan/data/repository/ticket_repository.dart';
import 'package:persian_number_utility/persian_number_utility.dart';

part 'send_ticket_event.dart';
part 'send_ticket_state.dart';

class SendTicketBloc extends Bloc<SendTicketEvent, SendTicketState> {
  SendTicketBloc() : super(SendTicketInitial()) {
    on<SendTicketEvent>((event, emit) async {
      if (event is GetTickets) {
        try {
          final response = await TicketRepository.getTickets();

          emit(GetTicketsSuccess(tickets: response.tickets));
        } on DioException catch (e) {
          emit(const GetTicketsSuccess(tickets: []));
          if (kDebugMode) {
            print("Dio Error is : $e");
          }
        }
      }
      if (event is DeleteTicket) {
        final List<Tickets> updatedTickets = List.from(state.tickets);
        emit(SendTicketLoading(tickets: updatedTickets));

        try {
          await TicketRepository.deleteTickets(event.id);
          updatedTickets
              .firstWhere(
                (element) => element.date == event.date,
              )
              .tickets
              .removeWhere(
                (element) => element.id == event.id,
              );
          if (updatedTickets
              .firstWhere(
                (element) => element.date == event.date,
              )
              .tickets
              .isEmpty) {
            updatedTickets.removeWhere((element) => element.date == event.date);
          }
          emit(SendTicketSuccess(tickets: updatedTickets));
        } on DioException catch (e) {
          emit(GetTicketsSuccess(tickets: updatedTickets));
          if (kDebugMode) {
            print("Dio Error is : $e");
          }
        }
      }
      if (event is SendTicket) {
        // Create a modifiable copy of the tickets list
        final List<Tickets> updatedTickets = List.from(state.tickets);
        final ticket = Ticket(
            id: -1,
            text: event.text,
            role: 'user',
            localFile: event.file,
            createdAt: DateTimeUtils.getNow().toIso8601String());

        if (updatedTickets.isNotEmpty) {
          if (updatedTickets.last.tickets.isNotEmpty &&
              updatedTickets.last.tickets.last.createdAt != null) {
            final date = DateTimeUtils.convertStringIsoToDate(
                updatedTickets.last.tickets.last.createdAt!);
            final now = DateTimeUtils.getNow();
            final dateString = '${date.year}-${date.month}-${date.day}';
            final nowString = '${now.year}-${now.month}-${now.day}';
            if (dateString == nowString) {
              updatedTickets.last.tickets.add(ticket);
            } else {
              updatedTickets.add(Tickets(
                  date: DateTimeUtils.getNow().toPersianDateStr(),
                  tickets: [ticket]));
            }
          }
        } else {
          updatedTickets.add(Tickets(
              date: DateTimeUtils.getNow().toPersianDateStr(),
              tickets: [ticket]));
        }

        emit(SendTicketLoading(tickets: updatedTickets));

        try {
          final response = await TicketRepository.sendTickets(
              text: event.text, file: event.file);
          response.localFile = event.file;
          updatedTickets.last.tickets.last = response;
          emit(SendTicketSuccess(tickets: updatedTickets));
        } on DioException catch (e) {
          if (updatedTickets.last.tickets.isNotEmpty) {
            updatedTickets.last.tickets.last.id = -2;
          }

          emit(GetTicketsSuccess(tickets: updatedTickets));
          if (kDebugMode) {
            print("Dio Error is : $e");
          }
        }
      }
    });
  }
}
