<?php

declare(strict_types=1);

namespace CloudXM\NFe\Admin\Pages;

use CloudXM\NFe\Admin\HasTemplate;
use CloudXM\NFe\Persistence\NfeEmissionsRepository;
use CloudXM\NFe\Services\NFeFileStorageService;

/**
 * NFe Invoices Admin Page
 *
 * Displays a paginated table of successful NFe emissions with filtering and download capabilities
 */
class NFeInvoicesPage
{
    use HasTemplate;

    public function __construct(
        private NfeEmissionsRepository $emissionRepo,
        private NFeFileStorageService $fileStorage
    ) {
        add_action('admin_enqueue_scripts', [$this, 'enqueueAdminAssets']);
    }

    public function enqueueAdminAssets(string $hook): void
    {
        if (strpos($hook, 'cloudxm-nfe') === false) {
            return;
        }

        wp_enqueue_script(
            'cloudxm-nfe-admin-invoices',
            CLOUDXM_NFE_URL . 'assets/js/admin-nfe-invoices.js',
            ['jquery'],
            CLOUDXM_NFE_VERSION,
            true
        );

        wp_enqueue_style(
            'cloudxm-nfe-admin-invoices',
            CLOUDXM_NFE_URL . 'assets/css/admin-nfe-invoices.css',
            [],
            CLOUDXM_NFE_VERSION
        );

        wp_localize_script('cloudxm-nfe-admin-invoices', 'cloudxm_nfe_invoices', [
            'ajax_url' => admin_url('admin-ajax.php'),
            'nonce' => wp_create_nonce('nfe_invoices'),
            'action_list' => 'nfe_get_invoices',
            'action_download' => 'nfe_download_file',
            'action_bulk_download' => 'nfe_bulk_download',
            'i18n' => [
                'no_invoices' => __('No invoices found matching the current filters.', 'woocommerce-cloudxm-nfe'),
                'bulk_warning' => __('Warning: This operation will download %d files and may take a considerable amount of time. The query is extensive due to the applied filters. Do you want to continue?', 'woocommerce-cloudxm-nfe'),
                'error_getting_ids' => __('Error getting invoice list.', 'woocommerce-cloudxm-nfe'),
                'network_error' => __('Network error. Please try again.', 'woocommerce-cloudxm-nfe'),
                'error_loading' => __('Error loading invoices. Showing local data.', 'woocommerce-cloudxm-nfe'),
                'network_error_local' => __('Network error. Showing local data.', 'woocommerce-cloudxm-nfe'),
                'view_details' => __('View Details', 'woocommerce-cloudxm-nfe'),
                'xml' => __('XML', 'woocommerce-cloudxm-nfe'),
                'pdf' => __('PDF', 'woocommerce-cloudxm-nfe'),
                'not_issued_yet' => __('Not issued yet', 'woocommerce-cloudxm-nfe'),
                'cancel_schedule' => __('Cancel Schedule', 'woocommerce-cloudxm-nfe'),
                'item' => __('item', 'woocommerce-cloudxm-nfe'),
                'items' => __('items', 'woocommerce-cloudxm-nfe'),
                'loading_details' => __('Loading invoice details...', 'woocommerce-cloudxm-nfe'),
                'failed_details' => __('Failed to load details.', 'woocommerce-cloudxm-nfe'),
                'network_error_simple' => __('Network error.', 'woocommerce-cloudxm-nfe'),
                'order' => __('Order', 'woocommerce-cloudxm-nfe'),
                'nfe_number' => __('NFe Number', 'woocommerce-cloudxm-nfe'),
                'access_key' => __('Access Key', 'woocommerce-cloudxm-nfe'),
                'protocol' => __('Protocol', 'woocommerce-cloudxm-nfe'),
                'status' => __('Status', 'woocommerce-cloudxm-nfe'),
                'environment' => __('Environment', 'woocommerce-cloudxm-nfe'),
                'total_value' => __('Total Value', 'woocommerce-cloudxm-nfe'),
                'icms_value' => __('ICMS Value', 'woocommerce-cloudxm-nfe'),
                'icms_rate' => __('ICMS Rate', 'woocommerce-cloudxm-nfe'),
                'emission_date' => __('Emission Date', 'woocommerce-cloudxm-nfe'),
                'cancellation_date' => __('Cancellation Date', 'woocommerce-cloudxm-nfe'),
                'cancellation_reason' => __('Cancellation Reason', 'woocommerce-cloudxm-nfe'),
                'cancellation_protocol' => __('Cancellation Protocol', 'woocommerce-cloudxm-nfe'),
                'request_date' => __('Request Date', 'woocommerce-cloudxm-nfe'),
                'error_message' => __('Error Message', 'woocommerce-cloudxm-nfe'),
                'scheduled_timezone' => __('Timezone', 'woocommerce-cloudxm-nfe'),
                // Scheduled invoice actions
                'issue_now' => __('Issue Now', 'woocommerce-cloudxm-nfe'),
                'reschedule' => __('Reschedule', 'woocommerce-cloudxm-nfe'),
                'cancel_invoice' => __('Cancel', 'woocommerce-cloudxm-nfe'),
                'confirm_issue' => __('Are you sure you want to issue this invoice now?', 'woocommerce-cloudxm-nfe'),
                'datetime_required' => __('Scheduled date/time is required', 'woocommerce-cloudxm-nfe'),
                'reason_required' => __('Cancellation reason is required', 'woocommerce-cloudxm-nfe'),
                'processing' => __('Processing...', 'woocommerce-cloudxm-nfe'),
                'error' => __('An error occurred. Please try again.', 'woocommerce-cloudxm-nfe'),
            ],
        ]);
    }

    /**
     * Render the invoices page
     */
    public function render(): void
    {
        // Check user capabilities
        if (!current_user_can('manage_options')) {
            wp_die(__('You do not have sufficient permissions to access this page.', 'woocommerce-cloudxm-nfe'));
        }

        $perPage = 20;
        $currentPage = 1;
        $offset = 0;
        $initialRows = $this->emissionRepo->findByConditions([], $perPage, $offset);
        $initialInvoices = [];
        foreach ($initialRows as $invoice) {
            $initialInvoices[] = $this->formatInvoiceForDisplay($invoice);
        }
        $totalItems = $this->emissionRepo->countByConditions([]);
        $initialPagination = [
            'current_page' => $currentPage,
            'total_pages' => (int) ceil($totalItems / $perPage),
            'total_items' => $totalItems,
            'items_shown' => count($initialInvoices),
        ];

        // Prepare data for template
        $data = [
            'page_title' => __('NFe Invoices', 'woocommerce-cloudxm-nfe'),
            'initial_invoices' => $initialInvoices,
            'initial_pagination' => $initialPagination,
        ];

        // Load template
        $this->loadTemplate('admin/pages/nfe-invoices', $data);
    }

    private function formatInvoiceForDisplay(array $invoice): array
    {
        $status = strtolower($invoice['status'] ?? '');
        $hasIssuedDocument = !empty($invoice['invoice_number']) || !empty($invoice['access_key']);
        $isCancelledScheduled = $status === 'cancelled' && !$hasIssuedDocument;
        $canDownloadRemote = !empty($invoice['invoice_id']) && (
            in_array($status, ['issued', 'authorized'], true) ||
            ($status === 'cancelled' && $hasIssuedDocument)
        );

        $xmlExists = $canDownloadRemote || (!empty($invoice['xml_file_path']) && $this->fileStorage->fileExists($invoice['xml_file_path']));
        $pdfExists = $canDownloadRemote || (!empty($invoice['pdf_file_path']) && $this->fileStorage->fileExists($invoice['pdf_file_path']));

        $isScheduled = in_array($status, ['scheduled', 'async_pending'], true);
        $allowedActions = $this->parseAllowedActions($invoice['allowed_actions'] ?? null);
        if ($isCancelledScheduled || $status === 'cancelled' || $status === 'failed') {
            $allowedActions = [];
        }
        if ($isCancelledScheduled) {
            $xmlExists = false;
            $pdfExists = false;
        }

        $dateFormatted = '-';
        $dateTypeLabel = __('Emission Date', 'woocommerce-cloudxm-nfe');
        $dateValue = $invoice['emission_date'] ?? '';

        if ($isScheduled) {
            // For scheduled invoices, prefer scheduled_for_local from emission table
            $dateValue = $invoice['scheduled_for_local'] ?? '';
            if (empty($dateValue)) {
                // Fallback to order meta
                $orderId = (int) ($invoice['order_id'] ?? 0);
                $order = wc_get_order($orderId);
                if ($order) {
                    $dateValue = $order->get_meta('_cloudxm_nfe_scheduled_at');
                }
            }
            if (empty($dateValue)) {
                // Final fallback to created_at
                $dateValue = $invoice['created_at'] ?? '';
            }
            // Use explicit Portuguese label
            $dateTypeLabel = 'Data de Agendamento';
            if ($dateValue) {
                $dateFormatted = wp_date(get_option('date_format') . ' ' . get_option('time_format'), strtotime($dateValue));
            }
        } elseif ($dateValue) {
            $dateFormatted = wp_date(get_option('date_format'), strtotime($dateValue));
        }

        $orderUrl = admin_url('post.php?post=' . (int) $invoice['order_id'] . '&action=edit');

        $value = $invoice['total_value'] ?? '-';
        if (is_numeric($value)) {
            $value = 'R$ ' . number_format((float) $value, 2, ',', '.');
        }

        $displayNumber = $invoice['invoice_number'] ?? '';
        if ($displayNumber === '') {
            $displayNumber = $isScheduled || $isCancelledScheduled
                ? __('Not issued yet', 'woocommerce-cloudxm-nfe')
                : '-';
        }

        return [
            'id' => (int) ($invoice['id'] ?? 0),
            'invoice_id' => $invoice['invoice_id'] ?? '',
            'access_key' => $invoice['access_key'] ?? '',
            'invoice_number' => $invoice['invoice_number'] ?? '',
            'display_number' => $displayNumber,
            'order_id' => (int) ($invoice['order_id'] ?? 0),
            'order_url' => $orderUrl,
            'emission_date' => $dateValue,
            'emission_date_formatted' => $dateFormatted,
            'date_type_label' => $dateTypeLabel,
            'value' => $value,
            'status' => $invoice['status'] ?? '',
            'status_label' => $isCancelledScheduled
                ? __('Cancelled', 'woocommerce-cloudxm-nfe')
                : $this->getStatusLabel(strtolower($invoice['status'] ?? '')),
            'environment' => $invoice['environment'] ?? '',
            'environment_label' => \CloudXM\NFe\Config\Configuration::getEnvironmentLabel($invoice['environment'] ?? ''),
            'xml_exists' => $xmlExists,
            'pdf_exists' => $pdfExists,
            'xml_file_path' => $invoice['xml_file_path'] ?? '',
            'pdf_file_path' => $invoice['pdf_file_path'] ?? '',
            'is_cancelled_scheduled' => $isCancelledScheduled,
            'is_scheduled' => $isScheduled,
            'allowed_actions' => $allowedActions,
        ];
    }

    private function parseAllowedActions(string|array|null $allowedActions): array
    {
        if (is_array($allowedActions)) {
            return array_values(array_filter(array_map('strval', $allowedActions)));
        }

        if (is_string($allowedActions) && $allowedActions !== '') {
            $decoded = json_decode($allowedActions, true);
            if (is_array($decoded)) {
                return array_values(array_filter(array_map('strval', $decoded)));
            }
        }

        return [];
    }

    private function getStatusLabel(string $status): string
    {
        // Handle empty or invalid status values
        if (empty($status) || $status === '0') {
            return __('Unknown', 'woocommerce-cloudxm-nfe');
        }

        return match ($status) {
            'issued'        => __('Issued', 'woocommerce-cloudxm-nfe'),
            'authorized'    => __('Authorized', 'woocommerce-cloudxm-nfe'),
            'processing'    => __('Processing', 'woocommerce-cloudxm-nfe'),
            'cancelled'     => __('Cancelled', 'woocommerce-cloudxm-nfe'),
            'failed'        => __('Failed', 'woocommerce-cloudxm-nfe'),
            'pending'       => __('Pending', 'woocommerce-cloudxm-nfe'),
            'draft'         => __('Draft', 'woocommerce-cloudxm-nfe'),
            'scheduled'     => __('Scheduled', 'woocommerce-cloudxm-nfe'),
            'async_pending' => __('Async Pending', 'woocommerce-cloudxm-nfe'),
            default         => ucfirst($status),
        };
    }
}
