<?php

namespace GriffinForms\Admin\Html\Pages;

class Migration extends \GriffinForms\Admin\Html\Pages\Format
{
    protected $meta = 'migration';
    protected $registry;
    protected $notice_service;
    protected $installed_sources = [];
    protected $detected_sources = [];
    protected $state = 'select';
    protected $job_id = '';
    protected $rest_base = '';
    protected $rest_nonce = '';
    protected $selected_source = '';
    protected $entry_context = '';

    protected function setRegistry()
    {
        $this->registry = \GriffinForms\Includes\Migration\MigrationRegistry::getInstance();
    }

    protected function setNoticeService()
    {
        $this->notice_service = \GriffinForms\Includes\Migration\MigrationNotice::getInstance();
    }

    protected function setInstalledSources()
    {
        $this->installed_sources = $this->registry->getInstalledSources();
    }

    protected function setDetectedSources()
    {
        $this->detected_sources = $this->notice_service->getDetectedSources();
    }

    protected function setState()
    {
        $requested = isset($_GET['gf_migration']) ? sanitize_key(wp_unslash($_GET['gf_migration'])) : 'select';
        $allowed = ['select', 'running', 'results'];
        $this->state = in_array($requested, $allowed, true) ? $requested : 'select';
    }

    protected function setJobId()
    {
        $this->job_id = isset($_GET['job_id']) ? sanitize_key(wp_unslash($_GET['job_id'])) : '';
    }

    protected function setRestBase()
    {
        $this->rest_base = rest_url('griffinforms/v1');
    }

    protected function setRestNonce()
    {
        $this->rest_nonce = wp_create_nonce('wp_rest');
    }

    protected function setSelectedSource()
    {
        $this->selected_source = isset($_GET['source']) ? sanitize_key(wp_unslash($_GET['source'])) : '';
    }

    protected function setEntryContext()
    {
        $entry_context = isset($_GET['gf_from']) ? sanitize_key(wp_unslash($_GET['gf_from'])) : '';
        $this->entry_context = $entry_context === 'onboarding' ? 'onboarding' : '';
    }

    public function render(): void
    {
        $this->enqueueAssets();
        $this->renderMarkup();
    }

    protected function enqueueAssets(): void
    {
        $css_handle = 'griffinforms-migration-css';
        $css_url = $this->config->getRootUrl() . 'admin/css/griffinforms-migration.css';
        wp_enqueue_style($css_handle, $css_url, [], '1.0', 'all');

        $js_handle = 'griffinforms-migration-js';
        $js_url = $this->config->getRootUrl() . 'admin/js/griffinforms-migration.js';
        wp_enqueue_script($js_handle, $js_url, ['wp-api-fetch'], '1.0', true);

        wp_add_inline_script($js_handle, 'window.gfMigrationPage = ' . wp_json_encode($this->getJsConfig()) . ';', 'before');
    }

    protected function getJsConfig(): array
    {
        return [
            'state' => $this->state,
            'jobId' => $this->job_id,
            'selectedSource' => $this->selected_source,
            'restBase' => $this->rest_base,
            'restNonce' => $this->rest_nonce,
            'resultsUrlBase' => admin_url('admin.php?page=griffinforms-migration&gf_migration=results'),
            'runningUrlBase' => admin_url('admin.php?page=griffinforms-migration&gf_migration=running'),
            'allFormsUrl' => admin_url('admin.php?page=griffinforms-forms'),
            'strings' => [
                'startError' => __('Migration start request failed.', 'griffinforms-form-builder'),
                'progressError' => __('Migration progress request failed.', 'griffinforms-form-builder'),
                'selectOne' => __('Select at least one source form first.', 'griffinforms-form-builder'),
                'starting' => __('Starting migration job...', 'griffinforms-form-builder'),
                'runningWarning' => __('Migration is in progress. Leaving now may leave your forms in an incomplete state.', 'griffinforms-form-builder'),
                'retry' => __('Retry', 'griffinforms-form-builder'),
                'noData' => __('No migration result data was found for this job.', 'griffinforms-form-builder'),
                'migrationComplete' => __('Migration complete', 'griffinforms-form-builder'),
                'migrationIssues' => __('Migration completed with issues', 'griffinforms-form-builder'),
                'whatSkipped' => __('What wasn’t migrated?', 'griffinforms-form-builder'),
                'hideSkipped' => __('Hide skipped items', 'griffinforms-form-builder'),
                'goAllForms' => __('Go to All Forms', 'griffinforms-form-builder'),
                'migrated' => __('Migrated', 'griffinforms-form-builder'),
                'partial' => __('Partial', 'griffinforms-form-builder'),
                'error' => __('Error', 'griffinforms-form-builder'),
                'skipped' => __('Skipped', 'griffinforms-form-builder'),
            ],
        ];
    }

    protected function renderMarkup(): void
    {
        echo '<div class="wrap gf-migration-page gf-migration-state-' . esc_attr($this->state) . '">';
        echo '<h1>' . esc_html__('Import Forms from Another Plugin', 'griffinforms-form-builder') . '</h1>';
        if ($this->entry_context === 'onboarding') {
            echo '<p class="gf-migration-lead"><a href="' . esc_url(admin_url('admin.php?page=griffinforms-onboarding&step=starter&entry_source=manual')) . '">' . esc_html__('< Back to setup', 'griffinforms-form-builder') . '</a></p>';
        }
        echo '<div id="gf-migration-page-root">';

        if (empty($this->installed_sources)) {
            $this->renderEmptyState();
        } elseif ($this->state === 'running') {
            $this->renderRunningState();
        } elseif ($this->state === 'results') {
            $this->renderResultsState();
        } else {
            $this->renderSelectState();
        }

        echo '</div>';
        echo '</div>';
    }

    protected function renderEmptyState(): void
    {
        echo '<div class="gf-migration-empty">';
        echo '<p>' . esc_html__('No supported competitor plugins are currently detected on this site.', 'griffinforms-form-builder') . '</p>';
        echo '<p><a class="button" href="' . esc_url(admin_url('admin.php?page=griffinforms-forms')) . '">' . esc_html__('Back to All Forms', 'griffinforms-form-builder') . '</a></p>';
        echo '</div>';
    }

    protected function renderSelectState(): void
    {
        echo '<p class="gf-migration-lead">' . esc_html__('Select a plugin below, choose which forms to bring over, and click Start Migration. Your existing forms and data will not be affected.', 'griffinforms-form-builder') . '</p>';
        echo '<div class="gf-migration-shell" data-state="select">';
        echo '<div class="gf-migration-tabs" role="tablist">';

        $active_slug = $this->getActiveSourceSlug();
        $tab_index = 0;
        foreach ($this->installed_sources as $source) {
            $forms = $source->getForms();
            if (empty($forms)) {
                continue;
            }
            $is_active = $active_slug === $source->getSlug() || ($active_slug === '' && $tab_index === 0);
            $active = $is_active ? 'true' : 'false';
            $active_class = $is_active ? ' is-active' : '';
            $form_count = count($forms);
            echo '<button type="button" class="gf-migration-tab' . esc_attr($active_class) . '" role="tab" aria-selected="' . esc_attr($active) . '" data-source="' . esc_attr($source->getSlug()) . '">';
            echo '<span class="gf-migration-tab-label">' . esc_html($source->getLabel()) . '</span>';
            echo '<span class="gf-migration-tab-badge">' . absint($form_count) . '</span>';
            echo '</button>';
            $tab_index++;
        }
        echo '</div>';

        $panel_index = 0;
        foreach ($this->installed_sources as $source) {
            $forms = $source->getForms();
            if (empty($forms)) {
                continue;
            }
            $is_active = $active_slug === $source->getSlug() || ($active_slug === '' && $panel_index === 0);
            $panel_class = $is_active ? ' is-active' : '';
            $supports_submissions = $source->supportsSubmissions();
            $total_forms = count($forms);

            echo '<section class="gf-migration-panel' . esc_attr($panel_class) . '" data-source="' . esc_attr($source->getSlug()) . '" role="tabpanel">';
            $icon_url = $source->getLogoUrl();
            echo '<div class="gf-migration-panel-head">';
            if ($icon_url !== '') {
                echo '<img src="' . esc_url($icon_url) . '" alt="" class="gf-migration-panel-icon" aria-hidden="true">';
            }
            echo '<div>';
            echo '<h2 style="margin:0 0 4px;">' . esc_html($source->getLabel()) . '</h2>';
            echo '<p style="margin:0;color:#50575e;">' . esc_html(sprintf(_n('%d form detected.', '%d forms detected.', $total_forms, 'griffinforms-form-builder'), $total_forms)) . '</p>';
            echo '</div>';
            echo '</div>';

            echo '<div class="gf-migration-form-toolbar">';
            echo '<label><input type="checkbox" class="gf-migration-select-all" data-source="' . esc_attr($source->getSlug()) . '"> ' . esc_html__('Select all visible forms', 'griffinforms-form-builder') . '</label>';
            echo '</div>';

            echo '<ul class="gf-migration-form-list">';
            foreach ($forms as $form) {
                $title = (string) ($form['title'] ?? __('Untitled', 'griffinforms-form-builder'));
                $count = absint($form['field_count'] ?? 0);
                echo '<li class="gf-migration-form-row">';
                echo '<label>';
                echo '<input type="checkbox" class="gf-migration-form" data-source="' . esc_attr($source->getSlug()) . '" value="' . absint($form['source_id'] ?? 0) . '">';
                echo '<span class="gf-migration-form-title">' . esc_html($title) . '</span>';
                echo '<span class="gf-migration-form-count">' . esc_html(sprintf(__(' %d fields', 'griffinforms-form-builder'), $count)) . '</span>';
                echo '</label>';
                echo '</li>';
            }
            echo '</ul>';

            echo '<div class="gf-migration-footer">';
            echo '<div class="gf-migration-mode">';
            echo '<label><input type="radio" name="gf_migration_mode_' . esc_attr($source->getSlug()) . '" class="gf-migration-mode-radio" data-source="' . esc_attr($source->getSlug()) . '" value="all" checked> ' . esc_html(sprintf(__('Migrate all %d forms', 'griffinforms-form-builder'), $total_forms)) . '</label>';
            echo '<label><input type="radio" name="gf_migration_mode_' . esc_attr($source->getSlug()) . '" class="gf-migration-mode-radio" data-source="' . esc_attr($source->getSlug()) . '" value="selected"> ' . esc_html__('Migrate selected forms', 'griffinforms-form-builder') . '</label>';
            echo '</div>';
            if ($supports_submissions) {
                echo '<label class="gf-migration-submission-toggle"><input type="checkbox" class="gf-migration-import-submissions" data-source="' . esc_attr($source->getSlug()) . '" checked> ' . esc_html__('Also migrate submissions', 'griffinforms-form-builder') . '</label>';
            }
            echo '<div class="gf-migration-actions">';
            echo '<button type="button" class="button button-primary gf-migration-start" data-source="' . esc_attr($source->getSlug()) . '">' . esc_html__('Start Migration', 'griffinforms-form-builder') . '</button>';
            echo '</div>';
            echo '</div>';

            echo '<div class="gf-migration-inline-status" data-source="' . esc_attr($source->getSlug()) . '"></div>';
            echo '</section>';
            $panel_index++;
        }

        echo '</div>';
    }

    protected function getActiveSourceSlug(): string
    {
        if ($this->selected_source === '') {
            return '';
        }

        foreach ($this->installed_sources as $source) {
            if ($source->getSlug() !== $this->selected_source) {
                continue;
            }

            if (!empty($source->getForms())) {
                return $this->selected_source;
            }
        }

        return '';
    }

    protected function renderRunningState(): void
    {
        echo '<div class="gf-migration-running" data-job-id="' . esc_attr($this->job_id) . '">';
        echo '<p class="gf-migration-lead">' . esc_html__('Your migration job is running. Keep this page open until the results screen appears.', 'griffinforms-form-builder') . '</p>';
        echo '<div class="progress gf-migration-progress"><div class="progress-bar progress-bar-striped progress-bar-animated" role="progressbar" style="width:0%" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100"></div></div>';
        echo '<p class="gf-migration-progress-label">0% — 0 of 0 forms</p>';
        echo '<p class="gf-migration-animated-text"><span class="gf-migration-spinner" aria-hidden="true"></span><span class="gf-migration-animated-text-label">' . esc_html__('Reading your forms…', 'griffinforms-form-builder') . '</span></p>';
        echo '<div class="gf-migration-inline-status"></div>';
        echo '</div>';
    }

    protected function renderResultsState(): void
    {
        echo '<div class="gf-migration-results" data-job-id="' . esc_attr($this->job_id) . '">';
        echo '<div class="gf-migration-results-shell">';
        echo '<div class="gf-migration-results-header"></div>';
        echo '<div class="gf-migration-results-stats"></div>';
        echo '<div class="gf-migration-results-table-wrap"></div>';
        echo '<p class="gf-migration-results-actions"><a class="button button-primary" href="' . esc_url(admin_url('admin.php?page=griffinforms-forms')) . '">' . esc_html__('Go to All Forms', 'griffinforms-form-builder') . '</a></p>';
        echo '</div>';
        echo '</div>';
    }
}
