import { takeEvery, all, call, put } from 'redux-saga/effects';
import { customerSlice, transRoutesSlice } from './../store';
import { CustomerService, TransRoutesService } from './../services';
import moment from 'moment';

const { createCustomer, createCustomerFailure, updateCustomer, updateCustomerFailure, deleteCustomer, deleteCustomerFailure } = customerSlice.actions;
const { fetchAllRoutesSuccess, fetchAllTomorrowRoutesSuccess, fetchAllHisotryRoutesSuccess } = transRoutesSlice.actions;

function* uploadFormFiles(customerId, customerName, formFiles) {
    if (!formFiles || !customerId) return;
    for (const { file, fileType } of formFiles) {
      if (file) {
        try {
          const fd = new FormData();
          fd.append('file', file);
          yield call(CustomerService.uploadCustomerFile, fd, customerId, customerName || '', fileType);
        } catch (err) {
          console.error(`Error uploading ${fileType}:`, err);
        }
      }
    }
  }

function* createCustomerSaga(action) {
    try {
      const customer = yield call(CustomerService.createNewCustomer, action.payload.data);
      const client = yield call(CustomerService.createNewClient, action.payload.dataForLegacy);
      if (action.payload.avatar) {
        if (customer?.data?.id) {
          CustomerService.uploadAvatar(customer.data.id, action.payload.avatar)
        }
      }
      // Upload form files after customer is created
      if (customer?.data?.id && action.payload.formFiles) {
        yield* uploadFormFiles(customer.data.id, action.payload.data?.name || '', action.payload.formFiles);
      }
    } catch(ex) {
      yield put(createCustomerFailure(ex));
    }
  }

function* updateCustomerSaga(action) {
  try {
    yield call(CustomerService.updateCustomer, action.payload.id, action.payload.data);
    // const targetClients = yield call(CustomerService.getClientsByNameOrEmail, action.payload.currentCustomer.email);
    // console.log(targetClients.data);
    // if (targetClients?.data?.length > 0) {
    //   yield call(CustomerService.updateClient, targetClients?.data[0]?.id, action.payload.dataForLegacy);
    // }
    if (action.payload.avatar) {
      CustomerService.uploadAvatar(action.payload.id, action.payload.avatar)
    }

    // Find and update routes that contain this customer
    try {
      const routes = yield call(TransRoutesService.getAllRoutesOnAndAfterToday);
      const customerId = action.payload.id;
      const updatedCustomerData = action.payload.data;
      
      // Find routes that contain this customer
      const routesToUpdate = routes.data.filter(route => 
        route.route_customer_list.some(customer => customer.customer_id === customerId)
      );

      if (routesToUpdate.length > 0) {
        // Build all updated route objects
        const updatePayloads = routesToUpdate.map(route => {
          const updatedCustomerList = route.route_customer_list.map(customer => {
            if (customer.customer_id === customerId) {
              return {
                ...customer,
                customer_name: updatedCustomerData.name || customer.customer_name,
                customer_address: updatedCustomerData.address1 || updatedCustomerData.address2 || updatedCustomerData.address3 || updatedCustomerData.address4 || updatedCustomerData.address5 || customer.customer_address,
                customer_phone: updatedCustomerData.mobile_phone || updatedCustomerData.phone || customer.customer_phone,
                customer_special_needs: updatedCustomerData.special_needs || customer.customer_special_needs,
                customer_note: updatedCustomerData.note || customer.customer_note,
                customer_language: updatedCustomerData.language || customer.customer_language,
                customer_type: updatedCustomerData.type || customer.customer_type,
                customer_table_id: updatedCustomerData.table_id || customer.customer_table_id,
                customer_group: updatedCustomerData.groups ? updatedCustomerData.groups[0] : customer.customer_group
              };
            }
            return customer;
          });

          return {
            id: route.id,
            data: { ...route, route_customer_list: updatedCustomerList, updatedAt: new Date(), updatedBy: 'admin' }
          };
        });

        // Batch update all routes in parallel instead of sequentially
        yield call(() => Promise.all(updatePayloads.map(p => TransRoutesService.updateRoute(p.id, p.data))));

        // Refetch only today's routes to update the store
        try {
          const date = new Date();
          const dateText = ((date.getMonth() > 8) ? (date.getMonth() + 1) : ('0' + (date.getMonth() + 1))) + '/' + ((date.getDate() > 9) ? date.getDate() : ('0' + date.getDate())) + '/' + date.getFullYear();
          const todayRoutes = (yield call(TransRoutesService.getAll, dateText)).data;
          yield put(fetchAllRoutesSuccess(todayRoutes));
        } catch (refetchError) {
          console.error('Error refetching routes:', refetchError);
        }
      }
    } catch (routeUpdateError) {
      console.error('Error updating routes with customer info:', routeUpdateError);
      // Don't fail the customer update if route update fails
    }
  } catch(ex) {
    yield put(updateCustomerFailure(ex));
  }
}

function* deleteCustomerSaga(action) {
  try {
    yield call(CustomerService.deleteCustomer, action.payload.id, action.payload.data);
    // yield call(CustomerService.deleteCustomer, action.payload.id, action.payload.dataForLegacy)
  } catch(ex) {
    yield put(deleteCustomerFailure(ex));
  }
}

export function* customerEffect() {
  yield all([
    yield takeEvery(createCustomer.type, createCustomerSaga),
    yield takeEvery(updateCustomer.type, updateCustomerSaga),
    yield takeEvery(deleteCustomer.type, deleteCustomerSaga)
  ])
};