<?php

namespace Drupal\abinbev_gmap\Form;

use Drupal\abinbev_gmap\PlaceInfoService;
use Drupal\Core\Ajax\AjaxResponse;
use Drupal\Core\Ajax\OpenDialogCommand;
use Drupal\Core\Ajax\OpenModalDialogCommand;
use Drupal\Core\Cache\CacheBackendInterface;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\Response;

/**
 * Configure settings for GMAP module.
 */
class LocationEditForm extends FormBase {


  /**
   * @var \Drupal\abinbev_gmap\PlaceInfoService $placeInfoService ;
   */
  private $placeInfoService;

  private $cache;
  /**
   * CustomService constructor.
   */
  public function __construct(PlaceInfoService $placeInfoService, CacheBackendInterface $cache) {
    $this->placeInfoService = $placeInfoService;
    $this->cache = $cache;
  }

  public static function create(ContainerInterface $container) {
    return new static(
      $container->get('place_info_service'),
      $container->get('cache.discovery')
    );
  }

  /**
   * {@inheritdoc}
   */
  public function getFormId() {
    return 'abinbev_location_edit_form';
  }


  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state, $id = NULL) {
    if (!empty($id)) {
//      $place = ['x1', 'Rose & Crown',	'Buckinghamshire, Hollybush Hill',	'SL2 4PW'];
//      $placeValues = $this->placeInfoService->getPlaceInfoFromGoogleByAdress($place);
//
//      kint($placeValues);
//      exit;
      $placeValues = $this->placeInfoService->getSelectedPlaces($id);

      $lat = $placeValues[0]->lat ?? '';
      $lon = $placeValues[0]->lon ?? '';
      $title = $placeValues[0]->title ?? '';

      $form['#prefix'] = '<div class="container edit-location-form"><div class="row"><div class="col-12 col-md-6">';
      $form['#suffix'] = '</div><div class="col-12 col-md-6"><div id="map" data-lat="' . $lat . '" data-lon="' . $lon . '" data-title="' . $title . '">MAP</div></div></div></div>';
      $weight = 3;
      foreach ($placeValues[0] as $key => $value) {
        $disabled = FALSE;
        if ($key == 'id') {
          $disabled = TRUE;
          $weight = 3;
        }

        $type = 'textfield';
        if ($key == 'full_info' || $key == 'place_id') {
          $type = 'textarea';
        }
        if ($key == 'place_id' || $key == 'poc_id') {
          $disabled = TRUE;
        }

        if ($key == 'title') {
          $weight = 1;
        }
        if ($key == 'lat' || $key == 'lon') {
          $weight = 2;
        }
        if ($key == 'category') {
          $weight = 2;
        }

        if ($key == 'status') {
          $type = 'select';
          $options = [
            'Published' => 'Published',
            'Failed' => 'Failed',
            'Unpublished' => 'Unpublished',
          ];
          $weight = 2;
          $form[$key] = [
            '#type' => $type,
            '#title' => strtoupper(str_replace('_', ' ', $key)),
            '#default_value' => $value,
            '#disabled' => $disabled,
            '#options' => $options,
            '#weight' => $weight,
          ];
        }

        else {
          $form[$key] = [
            '#type' => $type,
            '#title' => strtoupper(str_replace('_', ' ', $key)),
            '#default_value' => $value,
            '#disabled' => $disabled,
            '#weight' => $weight++,
          ];
        }
      }

      $adr = $placeValues[0]->full_info ? json_decode($placeValues[0]->full_info, TRUE) : '';
      $formatted_address = '';
      if (!empty($adr)) {
        $formatted_address = $adr['formatted_address'];
      }

      $form['address'] = [
        '#type' => 'textfield',
        '#title' => 'Address',
        '#default_value' => $formatted_address,
        '#weight' => 1,
      ];
    }
    else {
      $fields = [
        'poc_id',
        'title',
        'address',
        'lat',
        'lon',
        'category'
      ];
      $required = [
        'title',
        'address',
        'poc_id',
      ];

      foreach ($fields as $field) {
        $required_val = FALSE;
        if (in_array($field, $required)) {
          $required_val = TRUE;
        }

        $form[$field] = [
          '#type' => 'textfield',
          '#title' => strtoupper(str_replace('_', ' ', $field)),
          '#weight' => 1,
          '#required' => $required_val ?? FALSE,
        ];
      }
      $form['status'] = [
        '#type' => 'select',
        '#title' => 'Status',
        '#options' => [
          'Published' => 'Published',
          'Failed' => 'Failed',
          'Unpublished' => 'Unpublished',
        ],
        '#default_value' => 'Published',
        '#weight' => 1,
      ];
    }

    if ($id) {
      $form['save'] = [
        '#type' => 'submit',
        '#value' => 'Save',
        '#weight' => 100,
        '#attributes' => [
          'class' => [
            'button',
            'button--action',
            'button--primary',
            'button--small',
          ],
        ],
      ];
    }

    $form['request_google'] = [
      '#type' => 'submit',
      '#value' => t('Request Google'),
      '#submit' => ['::updateInfoFromGoogleSubmit'],
      '#weight' => 100,
      '#attributes' => [
        'class' => [
          'button',
          'button--action',
          'button--secondary',
          'button--small',
        ],
      ],
    ];


    if (!empty($id)) {
      $form['remove_location'] = [
        '#type' => 'submit',
        '#value' => 'Delete',
        '#ajax' => [
          'callback' => [$this, 'deleteLocationSubmit'],
        ],
        '#weight' => 100,
        '#attributes' => [
          'class' => [
            'button',
            'button--action',
            'button--danger',
            'button--small',
          ],
        ],
      ];
    }

    $form['close'] = [
      '#type' => 'submit',
      '#value' => t('Cancel'),
      '#submit' => ['::cancelEdit'],
      '#weight' => 100,
      '#attributes' => [
        'class' => [
          'button',
          'button--action',
          'button--warning',
          'button--small',
        ],
      ],
    ];

    $form['#attached']['library'][] = 'abinbev_gmap/edit_location_form';


    return $form;
  }

  public function cancelEdit(array &$form, FormStateInterface $form_state) {
    $form_state->setRedirect('abinbev_gmap.location_dashboard');
  }

  public function deleteLocationSubmit(array &$form, FormStateInterface $form_state) {
    $id = $form_state->getValue('title');
    $delete_form = \Drupal::formBuilder()
      ->getForm('Drupal\abinbev_gmap\Form\ConfirmDeleteForm', $id);
    $title = t("Delete Location?");
    $response = new AjaxResponse();
    $response->addCommand(new OpenModalDialogCommand($title, $delete_form, ['width' => '300']));
    return $response;
  }

  /**
   * @param array $form
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *
   * @return void
   */
  public function updateInfoFromGoogleSubmit(array &$form, FormStateInterface $form_state) {
    $values = $form_state->getValues();
    $result = $this->placeInfoService->getPlaceInfoFromGoogleByAdress($values['address']);

    if (!empty($result)) {
      $place_id = $result[0]['place_id'];
      $place = $this->placeInfoService->getPlaceInfoFromGoogle($place_id);

      if (!empty($place['place_id'])) {

        $save_values = [
          'place_id' => $place_id,
          'title' => $values['title'],
          'poc_id' => $values['poc_id'],
          //'address' => $values['address'],
          'lat' => $place['geometry']['location']['lat'] ?? 0,
          'lon' => $place['geometry']['location']['lng'] ?? 0,
          'full_info' => json_encode($place),
          'category' => $values['category'] ?? '',
          'status' => 'Published',

        ];

        //\Drupal::logger('placeId')->debug('<pre>' . print_r($values['place_id'], 1) . '</pre>');

        if (isset($values['place_id']) && !empty($values['place_id']) && $values['place_id'] != $values['title']) {
          $this->placeInfoService->saveData($place_id, $save_values, TRUE);
        }
        if (isset($values['place_id']) && !empty($values['place_id']) || !empty($values['place_id']) && $values['place_id'] == $values['title']) {
          $this->placeInfoService->saveData($place_id, $save_values, TRUE);
        }

        if (!isset($values['place_id']) || empty($values['place_id'])) {
          $this->placeInfoService->saveData($place_id, $save_values, FALSE);
        }

        if (!empty($values['place_id'])) {
          \Drupal::messenger()->addMessage('Location\'s been updated successfully');
        }
        else {
          \Drupal::messenger()->addMessage('Location\'s Been Added Successfully');
        }
      }
      //$cid = 'all_map_info:' . implode(',', [$values['id']]);
      //$this->cache->invalidate($cid);

      $view = \Drupal\views\Views::getView('gmap_locations_list');
      $view->storage->invalidateCaches();
    }
  }

  /**
   * @param array $form
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *
   * @return void
   */
  public function validateForm(array &$form, FormStateInterface $form_state) {

  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $values = $form_state->getValues();
    $isPlace = TRUE;

    \Drupal::service('cache_tags.invalidator')->invalidateTags(['map_place_info']);
    $this->placeInfoService->saveData($values['place_id'], $values, $isPlace);
    \Drupal::messenger()->addMessage('Location updated successfully');
    $form_state->setRedirect('abinbev_gmap.location_dashboard');
    $view = \Drupal\views\Views::getView('gmap_locations_list');
    $view->storage->invalidateCaches();
  }

}
