<?php

namespace RadiusTheme\RadiusBooking\Blocks;

use RadiusTheme\RadiusBooking\Assets\Vite;
use RadiusTheme\RadiusBooking\Controllers\ServiceController;
use RadiusTheme\RadiusBooking\Helpers\SettingsHelper;

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

class BlockManager {

	public function __construct() {
		add_action( 'init', array( $this, 'register_blocks' ) );
		add_action( 'enqueue_block_editor_assets', array( $this, 'enqueue_editor_assets' ) );
		add_filter( 'block_categories_all', array( $this, 'register_block_category' ) );
	}

	/**
	 * Register custom block category.
	 *
	 * @param array $categories Existing block categories.
	 *
	 * @return array
	 */
	public function register_block_category( $categories ) {
		return array_merge(
			array(
				array(
					'slug'  => 'radius-booking',
					'title' => esc_html__( 'Radius Booking', 'radius-booking' ),
					'icon'  => 'calendar',
				),
			),
			$categories
		);
	}

	/**
	 * Register Gutenberg blocks.
	 *
	 * @return void
	 */
	public function register_blocks() {
		register_block_type(
			'radius-booking/appointment-form',
			array(
				'render_callback' => array( $this, 'render_appointment_form' ),
			)
		);

		register_block_type(
			'radius-booking/service-list',
			array(
				'attributes'      => array(
					'layout'             => array(
						'type'    => 'string',
						'default' => 'grid',
					),
					'columns'            => array(
						'type'    => 'number',
						'default' => 3,
					),
					'perPage'            => array(
						'type'    => 'number',
						'default' => 9,
					),
					'category'           => array(
						'type'    => 'string',
						'default' => '',
					),
					'showImage'          => array(
						'type'    => 'boolean',
						'default' => true,
					),
					'showPrice'          => array(
						'type'    => 'boolean',
						'default' => true,
					),
					'showDuration'       => array(
						'type'    => 'boolean',
						'default' => true,
					),
					'showCategory'       => array(
						'type'    => 'boolean',
						'default' => true,
					),
					'showDescription'    => array(
						'type'    => 'boolean',
						'default' => true,
					),
					'showCategoryFilter' => array(
						'type'    => 'boolean',
						'default' => true,
					),
					'showStaff'          => array(
						'type'    => 'boolean',
						'default' => true,
					),
					'buttonText'         => array(
						'type'    => 'string',
						'default' => 'Book Now',
					),
					'primaryColor'       => array(
						'type'    => 'string',
						'default' => '#0040ff',
					),
					'cardBgColor'        => array(
						'type'    => 'string',
						'default' => '#ffffff',
					),
					'cardBorderColor'    => array(
						'type'    => 'string',
						'default' => '#e5e7eb',
					),
					'cardBorderRadius'   => array(
						'type'    => 'number',
						'default' => 12,
					),
					'cardGap'            => array(
						'type'    => 'number',
						'default' => 24,
					),
					'imageHeight'        => array(
						'type'    => 'number',
						'default' => 192,
					),
					'titleColor'         => array(
						'type'    => 'string',
						'default' => '#111827',
					),
					'titleFontSize'      => array(
						'type'    => 'number',
						'default' => 18,
					),
					'descColor'          => array(
						'type'    => 'string',
						'default' => '#6b7280',
					),
					'priceColor'         => array(
						'type'    => 'string',
						'default' => '',
					),
					'buttonBgColor'      => array(
						'type'    => 'string',
						'default' => '',
					),
					'buttonTextColor'    => array(
						'type'    => 'string',
						'default' => '#ffffff',
					),
					'buttonBorderRadius' => array(
						'type'    => 'number',
						'default' => 8,
					),
					'filterActiveBg'     => array(
						'type'    => 'string',
						'default' => '',
					),
					'filterActiveText'   => array(
						'type'    => 'string',
						'default' => '#ffffff',
					),
					'paginationActiveBg' => array(
						'type'    => 'string',
						'default' => '',
					),
					'paginationActiveText' => array(
						'type'    => 'string',
						'default' => '#ffffff',
					),
				),
				'render_callback' => array( $this, 'render_service_list' ),
			)
		);
	}

	/**
	 * Enqueue block editor scripts.
	 *
	 * @return void
	 */
	public function enqueue_editor_assets() {
		$assets_dir = RADIUS_BOOKING_DIR . '/build';
		$assets_url = RADIUS_BOOKING_BUILD;

		$vite = new Vite(
			$assets_dir,
			$assets_url,
			array(
				'preload-js-chunks'  => true,
				'preload-css-chunks' => true,
			)
		);

		$vite->enqueue(
			'src/blocks/index.js',
			array(
				'handle'              => 'radius-booking-blocks',
				'script-dependencies' => array( 'wp-blocks', 'wp-element', 'wp-block-editor', 'wp-components', 'wp-i18n', 'wp-server-side-render' ),
				'style-dependencies'  => array(),
			)
		);

		wp_localize_script(
			'radius-booking-blocks',
			'rtrbBlockData',
			array(
				'categories' => $this->get_categories_for_editor(),
			)
		);
	}

	/**
	 * Get service categories for the block editor.
	 *
	 * @return array
	 */
	private function get_categories_for_editor() {
		$categories = array(
			array(
				'value' => '',
				'label' => __( 'All Categories', 'radius-booking' ),
			),
		);

		try {
			$services = ( new ServiceController() )->fetchAllServices();
			if ( is_array( $services ) ) {
				foreach ( $services as $cat ) {
					if ( ! empty( $cat['id'] ) && ! empty( $cat['name'] ) ) {
						$categories[] = array(
							'value' => (string) $cat['id'],
							'label' => $cat['name'],
						);
					}
				}
			}
		} catch ( \Exception $e ) { // phpcs:ignore Generic.CodeAnalysis.EmptyStatement.DetectedCatch
			// Silently fail.
		}

		return $categories;
	}

	/**
	 * Render the Appointment Form block on the frontend.
	 *
	 * @return string
	 */
	public function render_appointment_form() {
		return do_shortcode( '[radius_booking_form]' );
	}

	/**
	 * Render the Service List block on the frontend.
	 *
	 * @param array $attributes Block attributes.
	 *
	 * @return string
	 */
	public function render_service_list( $attributes ) {
		// Editor preview — render static HTML preview.
		if ( defined( 'REST_REQUEST' ) && REST_REQUEST ) {
			return $this->render_service_list_preview( $attributes );
		}

		$layout   = esc_attr( $attributes['layout'] ?? 'grid' );
		$columns  = esc_attr( $attributes['columns'] ?? 3 );
		$per_page = esc_attr( $attributes['perPage'] ?? 9 );
		$category = esc_attr( $attributes['category'] ?? '' );

		$shortcode = "[rtrb_service_list layout=\"{$layout}\" columns=\"{$columns}\" per_page=\"{$per_page}\" category=\"{$category}\"]";
		$html      = do_shortcode( $shortcode );

		// Inject block style/display data attributes into the mount div.
		$block_styles = wp_json_encode(
			array(
				'primaryColor'       => $attributes['primaryColor'] ?? '#0040ff',
				'cardBgColor'        => $attributes['cardBgColor'] ?? '#ffffff',
				'cardBorderColor'    => $attributes['cardBorderColor'] ?? '#e5e7eb',
				'cardBorderRadius'   => ( $attributes['cardBorderRadius'] ?? 12 ) . 'px',
				'cardGap'            => ( $attributes['cardGap'] ?? 24 ) . 'px',
				'imageHeight'        => ( $attributes['imageHeight'] ?? 192 ) . 'px',
				'titleColor'         => $attributes['titleColor'] ?? '#111827',
				'titleFontSize'      => ( $attributes['titleFontSize'] ?? 18 ) . 'px',
				'descColor'          => $attributes['descColor'] ?? '#6b7280',
				'priceColor'         => $attributes['priceColor'] ?? '',
				'buttonBgColor'      => $attributes['buttonBgColor'] ?? '',
				'buttonTextColor'    => $attributes['buttonTextColor'] ?? '#ffffff',
				'buttonBorderRadius' => ( $attributes['buttonBorderRadius'] ?? 8 ) . 'px',
				'filterActiveBg'     => $attributes['filterActiveBg'] ?? '',
				'filterActiveText'   => $attributes['filterActiveText'] ?? '#ffffff',
				'paginationActiveBg'   => $attributes['paginationActiveBg'] ?? '',
				'paginationActiveText' => $attributes['paginationActiveText'] ?? '#ffffff',
			)
		);

		$display_options = wp_json_encode(
			array(
				'showImage'          => $attributes['showImage'] ?? true,
				'showPrice'          => $attributes['showPrice'] ?? true,
				'showDuration'       => $attributes['showDuration'] ?? true,
				'showCategory'       => $attributes['showCategory'] ?? true,
				'showDescription'    => $attributes['showDescription'] ?? true,
				'showCategoryFilter' => $attributes['showCategoryFilter'] ?? true,
				'showStaff'          => $attributes['showStaff'] ?? true,
				'buttonText'         => $attributes['buttonText'] ?? 'Book Now',
			)
		);

		// Add style data attributes to the shortcode's mount div.
		$html = str_replace(
			'class="rtrb-service-list"',
			'class="rtrb-service-list" data-elementor-styles="' . esc_attr( $block_styles ) . '" data-elementor-display="' . esc_attr( $display_options ) . '"',
			$html
		);

		return $html;
	}
	/**
	 * Static HTML preview for the Service List in the block editor.
	 *
	 * @param array $attributes Block attributes.
	 *
	 * @return string
	 */
	private function render_service_list_preview( $attributes ) {
		$layout       = $attributes['layout'] ?? 'grid';
		$columns      = (int) ( $attributes['columns'] ?? 3 );
		$per_page     = (int) ( $attributes['perPage'] ?? 9 );
		$cat_filter   = $attributes['category'] ?? '';
		$show_image   = $attributes['showImage'] ?? true;
		$show_price   = $attributes['showPrice'] ?? true;
		$show_dur     = $attributes['showDuration'] ?? true;
		$show_cat     = $attributes['showCategory'] ?? true;
		$show_desc    = $attributes['showDescription'] ?? true;
		$btn_text     = $attributes['buttonText'] ?? 'Book Now';
		$primary      = $attributes['primaryColor'] ?? '#0040ff';
		$card_bg      = $attributes['cardBgColor'] ?? '#ffffff';
		$card_border  = $attributes['cardBorderColor'] ?? '#e5e7eb';
		$card_radius  = ( $attributes['cardBorderRadius'] ?? 12 ) . 'px';
		$gap          = ( $attributes['cardGap'] ?? 24 ) . 'px';
		$img_h        = ( $attributes['imageHeight'] ?? 192 ) . 'px';
		$title_color  = $attributes['titleColor'] ?? '#111827';
		$title_fs     = ( $attributes['titleFontSize'] ?? 18 ) . 'px';
		$desc_color   = $attributes['descColor'] ?? '#6b7280';
		$price_color  = $attributes['priceColor'] ?: $primary;
		$btn_bg       = $attributes['buttonBgColor'] ?: $primary;
		$btn_color    = $attributes['buttonTextColor'] ?? '#ffffff';
		$btn_radius   = ( $attributes['buttonBorderRadius'] ?? 8 ) . 'px';

		// Fetch real services.
		try {
			$all_services = ( new ServiceController() )->fetchAllServices();
		} catch ( \Exception $e ) {
			$all_services = array();
		}

		// Flatten services from categories.
		$services = array();
		if ( is_array( $all_services ) ) {
			foreach ( $all_services as $cat ) {
				if ( empty( $cat['services'] ) || ! is_array( $cat['services'] ) ) {
					continue;
				}
				foreach ( $cat['services'] as $svc ) {
					if ( isset( $svc['is_visible'] ) && '1' !== (string) $svc['is_visible'] ) {
						continue;
					}
					if ( $cat_filter && isset( $cat['id'] ) && (string) $cat['id'] !== (string) $cat_filter ) {
						continue;
					}
					$svc['category_name'] = $cat['name'] ?? '';
					$services[]           = $svc;
				}
			}
		}

		$services = array_slice( $services, 0, $per_page );

		if ( empty( $services ) ) {
			return '<div style="text-align:center;padding:40px;color:#6b7280;">' . esc_html__( 'No services found.', 'radius-booking' ) . '</div>';
		}

		$html = '<div style="font-family:-apple-system,BlinkMacSystemFont,\'Segoe UI\',Roboto,sans-serif;">';

		if ( 'list' === $layout ) {
			// List layout
			$html .= '<div style="display:flex;flex-direction:column;gap:' . esc_attr( $gap ) . ';">';
			foreach ( $services as $svc ) {
				$html .= '<div style="display:flex;border:1px solid ' . esc_attr( $card_border ) . ';border-radius:' . esc_attr( $card_radius ) . ';background:' . esc_attr( $card_bg ) . ';overflow:hidden;">';

				if ( $show_image ) {
					if ( ! empty( $svc['picture_full_path'] ) ) {
						$html .= '<div style="width:200px;flex-shrink:0;"><img src="' . esc_url( $svc['picture_full_path'] ) . '" alt="' . esc_attr( $svc['name'] ?? '' ) . '" style="width:100%;height:100%;object-fit:cover;" /></div>';
					} else {
						$html .= '<div style="width:200px;flex-shrink:0;background:#f3f4f6;display:flex;align-items:center;justify-content:center;">';
						$html .= '<svg width="40" height="40" viewBox="0 0 24 24" fill="none" stroke="#c4cdd5" stroke-width="1.5"><rect x="3" y="3" width="18" height="18" rx="2"/><circle cx="8.5" cy="8.5" r="1.5"/><path d="m21 15-5-5L5 21"/></svg>';
						$html .= '</div>';
					}
				}

				$html .= '<div style="flex:1;padding:16px;display:flex;align-items:center;justify-content:space-between;gap:16px;">';
				$html .= '<div>';
				if ( $show_cat && ! empty( $svc['category_name'] ) ) {
					$html .= '<span style="display:inline-block;font-size:11px;font-weight:500;padding:2px 8px;border-radius:99px;background:' . esc_attr( $primary ) . '1a;color:' . esc_attr( $primary ) . ';margin-bottom:6px;">' . esc_html( $svc['category_name'] ) . '</span>';
				}
				$html .= '<div style="font-weight:600;font-size:' . esc_attr( $title_fs ) . ';color:' . esc_attr( $title_color ) . ';margin-bottom:4px;">' . esc_html( $svc['name'] ?? '' ) . '</div>';
				if ( $show_desc && ! empty( $svc['description'] ) ) {
					$html .= '<div style="font-size:13px;color:' . esc_attr( $desc_color ) . ';margin-bottom:6px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;max-width:400px;">' . esc_html( wp_strip_all_tags( $svc['description'] ) ) . '</div>';
				}
				$html .= '<div style="display:flex;align-items:center;gap:10px;">';
				if ( $show_price && isset( $svc['price'] ) ) {
					$html .= '<span style="font-size:16px;font-weight:700;color:' . esc_attr( $price_color ) . ';">' . esc_html( get_rtrb_currency_symbol() . number_format( (float) $svc['price'], 2 ) ) . '</span>';
				}
				if ( $show_dur && ! empty( $svc['duration'] ) ) {
					$mins = (int) round( (int) $svc['duration'] / 60 );
					$dur  = $mins >= 60 ? floor( $mins / 60 ) . 'h' . ( $mins % 60 ? ' ' . ( $mins % 60 ) . 'min' : '' ) : $mins . ' min';
					$html .= '<span style="font-size:12px;color:#9ca3af;">' . esc_html( $dur ) . '</span>';
				}
				$html .= '</div>';
				$html .= '</div>';
				$html .= '<button style="flex-shrink:0;padding:10px 20px;font-size:13px;font-weight:600;border:none;border-radius:' . esc_attr( $btn_radius ) . ';background:' . esc_attr( $btn_bg ) . ';color:' . esc_attr( $btn_color ) . ';cursor:pointer;">' . esc_html( $btn_text ) . '</button>';
				$html .= '</div>';

				$html .= '</div>';
			}
			$html .= '</div>';
		} else {
			// Grid layout
			$col_template = '1fr';
			if ( $columns >= 2 ) {
				$col_template = 'repeat(' . $columns . ', 1fr)';
			}

			$html .= '<div style="display:grid;grid-template-columns:' . esc_attr( $col_template ) . ';gap:' . esc_attr( $gap ) . ';">';
			foreach ( $services as $svc ) {
				$html .= '<div style="border:1px solid ' . esc_attr( $card_border ) . ';border-radius:' . esc_attr( $card_radius ) . ';background:' . esc_attr( $card_bg ) . ';overflow:hidden;">';

				if ( $show_image ) {
					if ( ! empty( $svc['picture_full_path'] ) ) {
						$html .= '<div style="height:' . esc_attr( $img_h ) . ';overflow:hidden;"><img src="' . esc_url( $svc['picture_full_path'] ) . '" alt="' . esc_attr( $svc['name'] ?? '' ) . '" style="width:100%;height:100%;object-fit:cover;" /></div>';
					} else {
						$html .= '<div style="height:' . esc_attr( $img_h ) . ';background:#f3f4f6;display:flex;align-items:center;justify-content:center;">';
						$html .= '<svg width="40" height="40" viewBox="0 0 24 24" fill="none" stroke="#c4cdd5" stroke-width="1.5"><rect x="3" y="3" width="18" height="18" rx="2"/><circle cx="8.5" cy="8.5" r="1.5"/><path d="m21 15-5-5L5 21"/></svg>';
						$html .= '</div>';
					}
				}

				$html .= '<div style="padding:16px;">';
				if ( $show_cat && ! empty( $svc['category_name'] ) ) {
					$html .= '<span style="display:inline-block;font-size:11px;font-weight:500;padding:2px 8px;border-radius:99px;background:' . esc_attr( $primary ) . '1a;color:' . esc_attr( $primary ) . ';margin-bottom:6px;">' . esc_html( $svc['category_name'] ) . '</span>';
				}
				$html .= '<div style="font-weight:600;font-size:' . esc_attr( $title_fs ) . ';color:' . esc_attr( $title_color ) . ';margin-bottom:4px;">' . esc_html( $svc['name'] ?? '' ) . '</div>';
				if ( $show_desc && ! empty( $svc['description'] ) ) {
					$html .= '<div style="font-size:13px;color:' . esc_attr( $desc_color ) . ';margin-bottom:8px;overflow:hidden;display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical;">' . esc_html( wp_strip_all_tags( $svc['description'] ) ) . '</div>';
				}
				$html .= '<div style="display:flex;align-items:center;gap:10px;margin-bottom:12px;">';
				if ( $show_price && isset( $svc['price'] ) ) {
					$html .= '<span style="font-size:16px;font-weight:700;color:' . esc_attr( $price_color ) . ';">' . esc_html( get_rtrb_currency_symbol() . number_format( (float) $svc['price'], 2 ) ) . '</span>';
				}
				if ( $show_dur && ! empty( $svc['duration'] ) ) {
					$mins = (int) round( (int) $svc['duration'] / 60 );
					$dur  = $mins >= 60 ? floor( $mins / 60 ) . 'h' . ( $mins % 60 ? ' ' . ( $mins % 60 ) . 'min' : '' ) : $mins . ' min';
					$html .= '<span style="font-size:12px;color:#9ca3af;">' . esc_html( $dur ) . '</span>';
				}
				$html .= '</div>';
				$html .= '<button style="width:100%;padding:10px;font-size:13px;font-weight:600;border:none;border-radius:' . esc_attr( $btn_radius ) . ';background:' . esc_attr( $btn_bg ) . ';color:' . esc_attr( $btn_color ) . ';cursor:pointer;">' . esc_html( $btn_text ) . '</button>';
				$html .= '</div>';

				$html .= '</div>';
			}
			$html .= '</div>';
		}

		$html .= '</div>';

		return $html;
	}
}
