<?php

declare(strict_types=1);

namespace FleekDash\Admin\Menu;

/**
 * Route Converter
 *
 * Handles conversion of WordPress routes to FleekDash routes
 *
 * @package FleekDash\Admin\Menu
 */
class RouteConverter
{
    /**
     * Check if an edit.php route should be intercepted
     *
     * @param string $target_path Target path
     * @return bool True if should intercept
     */
    public function shouldInterceptEditRoute(string $target_path): bool
    {
        if (strpos($target_path, 'edit.php') !== 0) {
            return false;
        }

        if ($this->isSimpleEditRoute($target_path)) {
            return true;
        }

        return false;
    }

    /**
     * Check if edit.php route is simple (only post_type) or complex
     *
     * @param string $target_path Target path
     * @return bool True if simple
     */
    public function isSimpleEditRoute(string $target_path): bool
    {
        static $routeCache = [];

        if (isset($routeCache[$target_path])) {
            return $routeCache[$target_path];
        }

        if (strpos($target_path, 'edit.php') !== 0) {
            $result = false;
        } elseif ($target_path === 'edit.php') {
            $result = true;
        } elseif (strpos($target_path, 'edit.php?') === 0) {
            $queryString = substr($target_path, 9);
            parse_str($queryString, $params);
            $result = empty($params) || (\count($params) === 1 && isset($params['post_type']));
        } else {
            $result = false;
        }

        $routeCache[$target_path] = $result;
        return $result;
    }

    /**
     * Handle Voxel theme specific routes
     *
     * @param string $slug Menu slug
     * @return array|null Route info or null
     */
    public function handleVoxelThemeRoute(string $slug): ?array
    {
        if (strpos($slug, 'vx-templates-post-type-') === 0) {
            $post_type = str_replace('vx-templates-post-type-', '', $slug);
            $base_fleekdash_url = \admin_url('admin.php?page=fleekdash');

            return [
                'target_path' => 'admin.php?page=edit-post-type-' . $post_type,
                'target_hash' => '',
                'url' => $base_fleekdash_url . '#/wp/admin.php?page=edit-post-type-' . urlencode($post_type),
                'is_wp_native' => true,
                'should_open_new_tab' => false
            ];
        }

        return null;
    }

    /**
     * Convert fleekdash-react slug to clean app route
     *
     * @param string $slug Menu slug
     * @return string Clean route
     */
    public function convertToCleanRoute(string $slug): string
    {
        if (strpos($slug, 'fleekdash-react-') === 0) {
            $clean_name = str_replace('fleekdash-react-', '', $slug);
            return 'apps/' . $clean_name;
        }
        return $slug;
    }

    /**
     * Convert WordPress route to appropriate FleekDash route
     *
     * @param string $target_path WordPress route path
     * @param string $target_hash Optional hash fragment
     * @return array Route information
     */
    public function convertWordPressRoute(string $target_path, string $target_hash = ''): array
    {
        $base = \admin_url('admin.php?page=fleekdash');

        $result = $this->tryConvertVoxelRoute($target_path, $base)
            ?? $this->tryConvertUploadRoute($target_path, $target_hash, $base)
            ?? $this->tryConvertPluginsRoute($target_path, $target_hash, $base)
            ?? $this->tryConvertSimplePageRoute($target_path, $base)
            ?? $this->tryConvertIndexRoute($target_path, $target_hash, $base)
            ?? $this->tryConvertEditRoute($target_path, $base);

        return $result ?? $this->buildDefaultWordPressIframeRoute($target_path, $target_hash, $base);
    }

    private function tryConvertVoxelRoute(string $target_path, string $base): ?array
    {
        if (strpos($target_path, 'admin.php?page=vx-templates-post-type-') !== 0) {
            return null;
        }
        $post_type = str_replace('admin.php?page=vx-templates-post-type-', '', $target_path);
        return [
            'url' => $base . '#/wp/admin.php?page=edit-post-type-' . urlencode($post_type),
            'route_type' => 'wordpress_iframe',
            'is_wp_native' => true,
            'target' => '_self'
        ];
    }

    private function tryConvertUploadRoute(string $target_path, string $target_hash, string $base): ?array
    {
        $result = null;

        if ($target_path === 'media-new.php') {
            $result = [
                'url' => $base . '#/media?intent=upload',
                'route_type' => 'react',
                'is_wp_native' => false,
                'target' => '_self',
            ];
        } elseif ($target_path === 'upload.php') {
            $result = [
                'url' => $base . '#/media',
                'route_type' => 'react',
                'is_wp_native' => false,
                'target' => '_self',
            ];
        } elseif (strpos($target_path, 'upload.php?') === 0) {
            $url = $base . '#/media?' . substr($target_path, 11);
            if ($target_hash) {
                $url .= '#' . $target_hash;
            }
            $result = [
                'url' => $url,
                'route_type' => 'react',
                'is_wp_native' => false,
                'target' => '_self',
            ];
        }

        return $result;
    }

    private function tryConvertPluginsRoute(string $target_path, string $target_hash, string $base): ?array
    {
        if ($target_path === 'plugins.php') {
            return [
                'url' => $base . '#/plugins',
                'route_type' => 'react',
                'is_wp_native' => false,
                'target' => '_self'
            ];
        }
        if (strpos($target_path, 'plugins.php?') === 0) {
            $hashPart = $target_hash ? $target_path . '#' . $target_hash : $target_path;
            return [
                'url' => $base . '#/plugins/' . $hashPart,
                'route_type' => 'react',
                'is_wp_native' => false,
                'target' => '_self'
            ];
        }
        return null;
    }

    private function tryConvertSimplePageRoute(string $target_path, string $base): ?array
    {
        $map = [
            'profile.php' => '#/settings/account',
            'users.php' => '#/users',
            'tools.php' => '#/integrations',
            'edit-comments.php' => '#/comments',
            'index.php' => '#/dashboard',
        ];
        return isset($map[$target_path])
            ? [
                'url' => $base . $map[$target_path],
                'route_type' => 'react',
                'is_wp_native' => false,
                'target' => '_self'
            ]
            : null;
    }

    private function tryConvertIndexRoute(string $target_path, string $target_hash, string $base): ?array
    {
        if (strpos($target_path, 'index.php?') !== 0) {
            return null;
        }
        $hashPart = $target_hash ? $target_path . '#' . $target_hash : $target_path;
        return [
            'url' => $base . '#/wp/' . $hashPart,
            'route_type' => 'wordpress_iframe',
            'is_wp_native' => true,
            'target' => '_self'
        ];
    }

    private function tryConvertEditRoute(string $target_path, string $base): ?array
    {
        if (!$this->shouldInterceptEditRoute($target_path)) {
            return null;
        }
        $pathSuffix = $this->getEditRoutePathSuffix($target_path);
        if ($pathSuffix === null) {
            return null;
        }
        return [
            'url' => $base . '#/' . ltrim($pathSuffix, '/'),
            'route_type' => 'react',
            'is_wp_native' => false,
            'target' => '_self'
        ];
    }

    private function getEditRoutePathSuffix(string $target_path): ?string
    {
        if ($target_path === 'edit.php') {
            return 'posts';
        }
        if (preg_match('/^edit\.php\?post_type=([a-zA-Z0-9_-]+)$/', $target_path, $matches)) {
            return 'posts?post_type=' . $matches[1];
        }
        return null;
    }

    private function buildDefaultWordPressIframeRoute(string $target_path, string $target_hash, string $base): array
    {
        $hashPart = $target_hash ? $target_path . '#' . $target_hash : $target_path;
        return [
            'url' => $base . '#/wp/' . $hashPart,
            'route_type' => 'wordpress_iframe',
            'is_wp_native' => true,
            'target' => '_self'
        ];
    }
}
