<?php
/**
 * This file is part of the Wisewand WordPress plugin.
 *
 * @package Wisewand
 * @since 1.0.0
 * @license GPL-2.0-or-later
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see <https://www.gnu.org/licenses/>.
 */
namespace Wisewand\Admin;

// Exit if accessed directly
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

use Wisewand\Utils\Options;
use Wisewand\Utils\Wisewand_API_Client;
use Wisewand\Logging\Logger;
use Wisewand\Admin\Traits\AJAX_Security;

class Wisewand_Projects_Page {

	use AJAX_Security;

	private $options;
	private $logger;
	private $api_client;

	public function __construct( Options $options, Logger $logger ) {
		$this->options = $options;
		$this->logger  = $logger;

		// Ensure Wisewand_API_Client class is available
		if ( ! class_exists( 'Wisewand\\Utils\\Wisewand_API_Client' ) ) {
			$api_client_file = WISEWAND_PLUGIN_DIR . 'includes/Utils/Wisewand_API_Client.php';
			if ( file_exists( $api_client_file ) ) {
				require_once $api_client_file;
			}
		}

		// Initialize API client immediately
		$this->init_api_client();
	}

	public function init_api_client() {
		if ( class_exists( 'Wisewand\\Utils\\Wisewand_API_Client' ) ) {
			$api_key = Wisewand_API_Client::get_stored_api_key();
			if ( ! empty( $api_key ) ) {
				$this->api_client = new Wisewand_API_Client( $api_key, $this->logger );
			}
		}
	}

	public function render_page() {
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_die( esc_html__( 'You do not have sufficient permissions to access this page.', 'wisewand-ai-content-writer-seo-content-generator' ) );
		}

		$this->handle_form_actions();

		echo '<div class="wrap wisewand-projects">';
		echo '<h1>' . esc_html__( 'Wisewand Projects & Personas', 'wisewand-ai-content-writer-seo-content-generator' ) . '</h1>';

		if ( ! $this->is_api_configured() ) {
			$this->render_api_setup_notice();
			echo '</div>';
			return;
		}

		$this->render_tabs_interface();
		echo '</div>';
	}

	private function is_api_configured() {
		return Wisewand_API_Client::is_api_key_configured();
	}

	private function render_api_setup_notice() {
		?>
		<div class="notice notice-warning">
			<p>
				<strong><?php esc_html_e( 'Wisewand API Key Required', 'wisewand-ai-content-writer-seo-content-generator' ); ?></strong><br>
				<?php esc_html_e( 'Please configure your Wisewand API key to manage projects and personas.', 'wisewand-ai-content-writer-seo-content-generator' ); ?>
				<a href="<?php echo esc_url( admin_url( 'admin.php?page=wisewand-api-settings' ) ); ?>" class="button button-primary">
					<?php esc_html_e( 'Configure API Key', 'wisewand-ai-content-writer-seo-content-generator' ); ?>
				</a>
			</p>
		</div>
		<?php
	}

	private function render_tabs_interface() {
        // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Tab navigation from URL parameter, no action performed
		$active_tab = isset( $_GET['tab'] ) ? sanitize_key( wp_unslash( $_GET['tab'] ) ) : 'projects';
		?>
		<div class="wisewand-tabs-wrapper">
			<h2 class="nav-tab-wrapper">
				<a href="<?php echo esc_url( add_query_arg( 'tab', 'projects' ) ); ?>"
					class="nav-tab <?php echo esc_attr( $active_tab === 'projects' ? 'nav-tab-active' : '' ); ?>">
					<?php esc_html_e( 'Projects', 'wisewand-ai-content-writer-seo-content-generator' ); ?>
				</a>
				<a href="<?php echo esc_url( add_query_arg( 'tab', 'personas' ) ); ?>"
					class="nav-tab <?php echo esc_attr( $active_tab === 'personas' ? 'nav-tab-active' : '' ); ?>">
					<?php esc_html_e( 'Personas', 'wisewand-ai-content-writer-seo-content-generator' ); ?>
				</a>
				<a href="<?php echo esc_url( add_query_arg( 'tab', 'connections' ) ); ?>"
					class="nav-tab <?php echo esc_attr( $active_tab === 'connections' ? 'nav-tab-active' : '' ); ?>">
					<?php esc_html_e( 'Connections', 'wisewand-ai-content-writer-seo-content-generator' ); ?>
				</a>
			</h2>

			<div class="wisewand-tab-content">
				<?php
				switch ( $active_tab ) {
					case 'projects':
						$this->render_projects_tab();
						break;
					case 'personas':
						$this->render_personas_tab();
						break;
					case 'connections':
						$this->render_connections_tab();
						break;
				}
				?>
			</div>
		</div>
		<?php
	}

	private function render_projects_tab() {
		$projects_data = $this->fetch_projects();

		if ( is_wp_error( $projects_data ) ) {
			$this->render_api_error( $projects_data );
			return;
		}

		?>
		<div class="wisewand-projects-section">
			<div class="wisewand-section-header">
				<h3><?php esc_html_e( 'Your Wisewand Projects', 'wisewand-ai-content-writer-seo-content-generator' ); ?></h3>
				<button type="button" class="button button-primary" id="create-project">
					<?php esc_html_e( 'Create New Project', 'wisewand-ai-content-writer-seo-content-generator' ); ?>
				</button>
			</div>

			<?php if ( empty( $projects_data['projects'] ) ) : ?>
			<div class="wisewand-empty-state">
				<p><?php esc_html_e( 'No projects found. Create your first project to organize your content.', 'wisewand-ai-content-writer-seo-content-generator' ); ?></p>
			</div>
			<?php else : ?>
			<div class="wisewand-projects-grid">
				<?php foreach ( $projects_data['projects'] as $project ) : ?>
				<div class="wisewand-project-card" data-project-id="<?php echo esc_attr( $project['id'] ); ?>">
					<div class="wisewand-project-header">
						<h4><?php echo esc_html( $project['name'] ); ?></h4>
						<div class="wisewand-project-actions">
							<button type="button" class="button button-small wisewand-edit-project">
								<?php esc_html_e( 'Edit', 'wisewand-ai-content-writer-seo-content-generator' ); ?>
							</button>
						</div>
					</div>

					<?php if ( ! empty( $project['description'] ) ) : ?>
					<p class="wisewand-project-description"><?php echo esc_html( $project['description'] ); ?></p>
					<?php endif; ?>

					<div class="wisewand-project-meta">
						<?php if ( ! empty( $project['website_url'] ) ) : ?>
						<div class="wisewand-project-website">
							<strong><?php esc_html_e( 'Website:', 'wisewand-ai-content-writer-seo-content-generator' ); ?></strong>
							<a href="<?php echo esc_url( $project['website_url'] ); ?>" target="_blank">
								<?php echo esc_html( $project['website_url'] ); ?>
							</a>
						</div>
						<?php endif; ?>

						<?php if ( ! empty( $project['default_lang'] ) ) : ?>
						<div class="wisewand-project-lang">
							<strong><?php esc_html_e( 'Language:', 'wisewand-ai-content-writer-seo-content-generator' ); ?></strong>
							<?php echo esc_html( strtoupper( $project['default_lang'] ) ); ?>
						</div>
						<?php endif; ?>

						<div class="wisewand-project-created">
							<strong><?php esc_html_e( 'Created:', 'wisewand-ai-content-writer-seo-content-generator' ); ?></strong>
							<?php echo esc_html( gmdate( 'Y-m-d', strtotime( $project['created_at'] ) ) ); ?>
						</div>
					</div>
				</div>
				<?php endforeach; ?>
			</div>
			<?php endif; ?>
		</div>
		<?php
	}

	private function render_personas_tab() {
		$personas_data = $this->fetch_personas();

		if ( is_wp_error( $personas_data ) ) {
			$this->render_api_error( $personas_data );
			return;
		}

		?>
		<div class="wisewand-personas-section">
			<div class="wisewand-section-header">
				<h3><?php esc_html_e( 'Your Writing Personas', 'wisewand-ai-content-writer-seo-content-generator' ); ?></h3>
				<button type="button" class="button button-primary" id="create-persona">
					<?php esc_html_e( 'Create New Persona', 'wisewand-ai-content-writer-seo-content-generator' ); ?>
				</button>
			</div>

			<?php if ( empty( $personas_data['personas'] ) ) : ?>
			<div class="wisewand-empty-state">
				<p><?php esc_html_e( 'No personas found. Create writing personas to maintain consistent tone and style.', 'wisewand-ai-content-writer-seo-content-generator' ); ?></p>
			</div>
			<?php else : ?>
			<div class="wisewand-personas-grid">
				<?php foreach ( $personas_data['personas'] as $persona ) : ?>
				<div class="wisewand-persona-card" data-persona-id="<?php echo esc_attr( $persona['id'] ); ?>">
					<div class="wisewand-persona-header">
						<h4><?php echo esc_html( $persona['name'] ); ?></h4>
						<div class="wisewand-persona-actions">
							<button type="button" class="button button-small wisewand-edit-persona">
								<?php esc_html_e( 'Edit', 'wisewand-ai-content-writer-seo-content-generator' ); ?>
							</button>
							<button type="button" class="button button-small button-link-delete wisewand-delete-persona">
								<?php esc_html_e( 'Delete', 'wisewand-ai-content-writer-seo-content-generator' ); ?>
							</button>
						</div>
					</div>

					<?php if ( ! empty( $persona['description'] ) ) : ?>
					<p class="wisewand-persona-description"><?php echo esc_html( $persona['description'] ); ?></p>
					<?php endif; ?>

					<div class="wisewand-persona-meta">
						<?php if ( ! empty( $persona['tone'] ) ) : ?>
						<div class="wisewand-persona-tone">
							<strong><?php esc_html_e( 'Tone:', 'wisewand-ai-content-writer-seo-content-generator' ); ?></strong>
							<?php echo esc_html( $persona['tone'] ); ?>
						</div>
						<?php endif; ?>

						<?php if ( ! empty( $persona['style'] ) ) : ?>
						<div class="wisewand-persona-style">
							<strong><?php esc_html_e( 'Style:', 'wisewand-ai-content-writer-seo-content-generator' ); ?></strong>
							<?php echo esc_html( $persona['style'] ); ?>
						</div>
						<?php endif; ?>

						<?php if ( ! empty( $persona['voice'] ) ) : ?>
						<div class="wisewand-persona-voice">
							<strong><?php esc_html_e( 'Voice:', 'wisewand-ai-content-writer-seo-content-generator' ); ?></strong>
							<?php echo esc_html( $persona['voice'] ); ?>
						</div>
						<?php endif; ?>
					</div>

					<?php if ( ! empty( $persona['examples'] ) && is_array( $persona['examples'] ) ) : ?>
					<div class="wisewand-persona-examples">
						<strong><?php esc_html_e( 'Examples:', 'wisewand-ai-content-writer-seo-content-generator' ); ?></strong>
						<ul>
							<?php foreach ( array_slice( $persona['examples'], 0, 2 ) as $example ) : ?>
							<li><em>"<?php echo esc_html( wp_trim_words( $example, 10 ) ); ?>"</em></li>
							<?php endforeach; ?>
						</ul>
					</div>
					<?php endif; ?>
				</div>
				<?php endforeach; ?>
			</div>
			<?php endif; ?>
		</div>
		<?php
	}

	private function render_connections_tab() {
		$connections_data = $this->fetch_connections();

		if ( is_wp_error( $connections_data ) ) {
			$this->render_api_error( $connections_data );
			return;
		}

		?>
		<div class="wisewand-connections-section">
			<div class="wisewand-section-header">
				<h3><?php esc_html_e( 'Wisewand Connections', 'wisewand-ai-content-writer-seo-content-generator' ); ?></h3>
				<p class="description">
					<?php esc_html_e( 'Connections allow Wisewand to publish directly to your WordPress site and access internal linking data.', 'wisewand-ai-content-writer-seo-content-generator' ); ?>
				</p>
			</div>

			<?php if ( empty( $connections_data['connections'] ) ) : ?>
			<div class="wisewand-empty-state">
				<p><?php esc_html_e( 'No connections found. Connections are managed from your Wisewand dashboard.', 'wisewand-ai-content-writer-seo-content-generator' ); ?></p>
				<a href="https://wisewand.ai/dashboard/connections" target="_blank" class="button button-primary">
					<?php esc_html_e( 'Manage Connections', 'wisewand-ai-content-writer-seo-content-generator' ); ?>
				</a>
			</div>
			<?php else : ?>
			<div class="wisewand-connections-list">
				<?php foreach ( $connections_data['connections'] as $connection ) : ?>
				<div class="wisewand-connection-item">
					<div class="wisewand-connection-info">
						<h4><?php echo esc_html( $connection['name'] ?? 'Unnamed Connection' ); ?></h4>
						<?php if ( ! empty( $connection['url'] ) ) : ?>
						<p class="wisewand-connection-url"><?php echo esc_html( $connection['url'] ); ?></p>
						<?php endif; ?>
					</div>
					<div class="wisewand-connection-status">
						<span class="wisewand-status <?php echo esc_attr( $connection['status'] ?? 'unknown' ); ?>">
							<?php echo esc_html( ucfirst( $connection['status'] ?? 'Unknown' ) ); ?>
						</span>
					</div>
				</div>
				<?php endforeach; ?>
			</div>
			<?php endif; ?>
		</div>
		<?php
	}

	private function render_api_error( $error ) {
		?>
		<div class="notice notice-error">
			<p>
				<strong><?php esc_html_e( 'Wisewand API Error', 'wisewand-ai-content-writer-seo-content-generator' ); ?></strong><br>
				<?php echo esc_html( $error->get_error_message() ); ?>
			</p>
			<p>
				<button type="button" class="button wisewand-refresh-data">
					<?php esc_html_e( 'Retry', 'wisewand-ai-content-writer-seo-content-generator' ); ?>
				</button>
				<a href="<?php echo esc_url( admin_url( 'admin.php?page=wisewand-api-settings' ) ); ?>" class="button">
					<?php esc_html_e( 'Check API Settings', 'wisewand-ai-content-writer-seo-content-generator' ); ?>
				</a>
			</p>
		</div>
		<?php
	}

	private function fetch_projects() {
		if ( ! $this->api_client ) {
			return new \WP_Error(
				'wisewand_no_api_client',
				__( 'API client not initialized', 'wisewand-ai-content-writer-seo-content-generator' )
			);
		}

		$result = $this->api_client->list_projects( array( 'take' => 50 ) );

		if ( is_wp_error( $result ) ) {
			return $result;
		}

		return array(
			'projects' => $result['items'] ?? array(),
			'total'    => $result['count'] ?? 0,
		);
	}

	private function fetch_personas() {
		if ( ! $this->api_client ) {
			return new \WP_Error(
				'wisewand_no_api_client',
				__( 'API client not initialized', 'wisewand-ai-content-writer-seo-content-generator' )
			);
		}

		$result = $this->api_client->list_personas( array( 'take' => 50 ) );

		if ( is_wp_error( $result ) ) {
			return $result;
		}

		return array(
			'personas' => $result['items'] ?? array(),
			'total'    => $result['count'] ?? 0,
		);
	}

	private function fetch_connections() {
		if ( ! $this->api_client ) {
			return new \WP_Error(
				'wisewand_no_api_client',
				__( 'API client not initialized', 'wisewand-ai-content-writer-seo-content-generator' )
			);
		}

		$result = $this->api_client->list_connections( array( 'take' => 50 ) );

		if ( is_wp_error( $result ) ) {
			return $result;
		}

		return array(
			'connections' => $result['items'] ?? array(),
			'total'       => $result['count'] ?? 0,
		);
	}

	private function handle_form_actions() {
		// Handle any form submissions for creating/editing projects/personas
		if ( isset( $_POST['action'] ) ) {
			// Verify nonce before processing any POST actions
			check_admin_referer( 'wisewand_projects_action', 'wisewand_projects_nonce' );

			$action = sanitize_key( wp_unslash( $_POST['action'] ) );

			// Route to appropriate handler
			switch ( $action ) {
				case 'create_project':
					$this->handle_create_project();
					break;
				case 'update_project':
					$this->handle_update_project();
					break;
				case 'create_persona':
					$this->handle_create_persona();
					break;
				case 'update_persona':
					$this->handle_update_persona();
					break;
			}
		}
	}

	private function handle_create_project() {
		if ( ! current_user_can( 'manage_options' ) ) {
			add_settings_error(
				'wisewand_projects',
				'insufficient_permissions',
				__( 'Insufficient permissions', 'wisewand-ai-content-writer-seo-content-generator' ),
				'error'
			);
			return;
		}

		$project_data = array(
			'name'            => isset( $_POST['project_name'] ) ? sanitize_text_field( wp_unslash( $_POST['project_name'] ) ) : '',
			'description'     => isset( $_POST['project_description'] ) ? sanitize_textarea_field( wp_unslash( $_POST['project_description'] ) ) : '',
			'website_url'     => isset( $_POST['project_website_url'] ) ? esc_url_raw( wp_unslash( $_POST['project_website_url'] ) ) : '',
			'default_lang'    => isset( $_POST['project_default_lang'] ) ? sanitize_text_field( wp_unslash( $_POST['project_default_lang'] ) ) : 'fr',
			'default_country' => isset( $_POST['project_default_country'] ) ? sanitize_text_field( wp_unslash( $_POST['project_default_country'] ) ) : 'fr',
		);

		if ( empty( $project_data['name'] ) ) {
			add_settings_error(
				'wisewand_projects',
				'project_name_required',
				__( 'Project name is required', 'wisewand-ai-content-writer-seo-content-generator' ),
				'error'
			);
			return;
		}

		$result = $this->api_client->create_project( $project_data );

		if ( is_wp_error( $result ) ) {
			add_settings_error(
				'wisewand_projects',
				'project_creation_failed',
				sprintf(
					/* translators: %s: Error message describing why the project creation failed */
					__( 'Failed to create project: %s', 'wisewand-ai-content-writer-seo-content-generator' ),
					$result->get_error_message()
				),
				'error'
			);
			return;
		}

		add_settings_error(
			'wisewand_projects',
			'project_created',
			__( 'Project created successfully!', 'wisewand-ai-content-writer-seo-content-generator' ),
			'updated'
		);

		$this->logger->info(
			'Wisewand project created',
			array(
				'project_id'   => $result['id'] ?? 'unknown',
				'project_name' => $project_data['name'],
			)
		);
	}

	private function handle_create_persona() {
		if ( ! current_user_can( 'manage_options' ) ) {
			add_settings_error(
				'wisewand_projects',
				'insufficient_permissions',
				__( 'Insufficient permissions', 'wisewand-ai-content-writer-seo-content-generator' ),
				'error'
			);
			return;
		}

		$persona_data = array(
			'name'        => isset( $_POST['persona_name'] ) ? sanitize_text_field( wp_unslash( $_POST['persona_name'] ) ) : '',
			'description' => isset( $_POST['persona_description'] ) ? sanitize_textarea_field( wp_unslash( $_POST['persona_description'] ) ) : '',
			'tone'        => isset( $_POST['persona_tone'] ) ? sanitize_text_field( wp_unslash( $_POST['persona_tone'] ) ) : '',
			'style'       => isset( $_POST['persona_style'] ) ? sanitize_text_field( wp_unslash( $_POST['persona_style'] ) ) : '',
			'voice'       => isset( $_POST['persona_voice'] ) ? sanitize_text_field( wp_unslash( $_POST['persona_voice'] ) ) : '',
			'guidelines'  => isset( $_POST['persona_guidelines'] ) ? sanitize_textarea_field( wp_unslash( $_POST['persona_guidelines'] ) ) : '',
		);

		// Handle examples array
		if ( ! empty( $_POST['persona_examples'] ) ) {
			$examples = array_map( 'sanitize_textarea_field', map_deep( wp_unslash( $_POST['persona_examples'] ), 'wp_kses_post' ) );
			$examples = array_filter( $examples ); // Remove empty examples
			if ( ! empty( $examples ) ) {
				$persona_data['examples'] = $examples;
			}
		}

		if ( empty( $persona_data['name'] ) ) {
			add_settings_error(
				'wisewand_projects',
				'persona_name_required',
				__( 'Persona name is required', 'wisewand-ai-content-writer-seo-content-generator' ),
				'error'
			);
			return;
		}

		$result = $this->api_client->create_persona( $persona_data );

		if ( is_wp_error( $result ) ) {
			add_settings_error(
				'wisewand_projects',
				'persona_creation_failed',
				sprintf(
					/* translators: %s: Error message describing why the persona creation failed */
					__( 'Failed to create persona: %s', 'wisewand-ai-content-writer-seo-content-generator' ),
					$result->get_error_message()
				),
				'error'
			);
			return;
		}

		add_settings_error(
			'wisewand_projects',
			'persona_created',
			__( 'Persona created successfully!', 'wisewand-ai-content-writer-seo-content-generator' ),
			'updated'
		);

		$this->logger->info(
			'Wisewand persona created',
			array(
				'persona_id'   => $result['id'] ?? 'unknown',
				'persona_name' => $persona_data['name'],
			)
		);
	}

	// AJAX handlers for projects and personas
	public function ajax_get_project_details() {
		$this->verify_ajax_request( 'wisewand_projects', 'manage_options' );

		$project_id = isset( $_POST['project_id'] ) ? sanitize_text_field( wp_unslash( $_POST['project_id'] ) ) : '';
		if ( empty( $project_id ) ) {
			wp_send_json_error( array( 'message' => __( 'Project ID required', 'wisewand-ai-content-writer-seo-content-generator' ) ) );
		}

		if ( ! $this->api_client ) {
			wp_send_json_error( array( 'message' => __( 'API client not configured', 'wisewand-ai-content-writer-seo-content-generator' ) ) );
		}

		$result = $this->api_client->get_project( $project_id );

		if ( is_wp_error( $result ) ) {
			wp_send_json_error( array( 'message' => $result->get_error_message() ) );
		}

		wp_send_json_success( $result );
	}

	public function ajax_get_persona_details() {
		$this->verify_ajax_request( 'wisewand_projects', 'manage_options' );

		$persona_id = isset( $_POST['persona_id'] ) ? sanitize_text_field( wp_unslash( $_POST['persona_id'] ) ) : '';
		if ( empty( $persona_id ) ) {
			wp_send_json_error( array( 'message' => __( 'Persona ID required', 'wisewand-ai-content-writer-seo-content-generator' ) ) );
		}

		if ( ! $this->api_client ) {
			wp_send_json_error( array( 'message' => __( 'API client not configured', 'wisewand-ai-content-writer-seo-content-generator' ) ) );
		}

		$result = $this->api_client->get_persona( $persona_id );

		if ( is_wp_error( $result ) ) {
			wp_send_json_error( array( 'message' => $result->get_error_message() ) );
		}

		wp_send_json_success( $result );
	}

	public function ajax_delete_persona() {
		$this->verify_ajax_request( 'wisewand_projects', 'manage_options' );

		$persona_id = isset( $_POST['persona_id'] ) ? sanitize_text_field( wp_unslash( $_POST['persona_id'] ) ) : '';
		if ( empty( $persona_id ) ) {
			wp_send_json_error( array( 'message' => __( 'Persona ID required', 'wisewand-ai-content-writer-seo-content-generator' ) ) );
		}

		if ( ! $this->api_client ) {
			wp_send_json_error( array( 'message' => __( 'API client not configured', 'wisewand-ai-content-writer-seo-content-generator' ) ) );
		}

		$result = $this->api_client->delete_persona( $persona_id );

		if ( is_wp_error( $result ) ) {
			wp_send_json_error( array( 'message' => $result->get_error_message() ) );
		}

		$this->logger->info( 'Wisewand persona deleted', array( 'persona_id' => $persona_id ) );

		wp_send_json_success( array( 'message' => __( 'Persona deleted successfully', 'wisewand-ai-content-writer-seo-content-generator' ) ) );
	}
}