<?php

use App\Enums\UserStatus;
use App\Enums\UserType;
use App\Models\User;
use Barryvdh\DomPDF\Facade\Pdf;
use League\Csv\Writer;
use Livewire\Volt\Component;
use Symfony\Component\HttpFoundation\StreamedResponse;

new class extends Component {
    public string $userType = 'all';
    public string $status = 'all';
    public string $dateFrom = '';
    public string $dateTo = '';

    public function exportCsv(): ?StreamedResponse
    {
        $count = $this->getFilteredUsers()->count();

        if ($count === 0) {
            $this->dispatch('notify', type: 'info', message: __('export.no_users_match'));

            return null;
        }

        $locale = auth()->user()->preferred_language ?? 'ar';

        return response()->streamDownload(function () use ($locale) {
            // UTF-8 BOM for Excel Arabic support
            echo "\xEF\xBB\xBF";

            $csv = Writer::createFromString();

            // Headers based on admin language
            $csv->insertOne([
                __('export.name', [], $locale),
                __('export.email', [], $locale),
                __('export.phone', [], $locale),
                __('export.user_type', [], $locale),
                __('export.id_number', [], $locale),
                __('export.status', [], $locale),
                __('export.created_at', [], $locale),
            ]);

            $this->getFilteredUsers()->cursor()->each(function ($user) use ($csv, $locale) {
                $csv->insertOne([
                    $user->user_type === UserType::Company ? $user->company_name : $user->full_name,
                    $user->email,
                    $user->phone,
                    __('export.type_'.$user->user_type->value, [], $locale),
                    $user->user_type === UserType::Company ? $user->company_cert_number : $user->national_id,
                    __('export.status_'.$user->status->value, [], $locale),
                    $user->created_at->format($locale === 'ar' ? 'd/m/Y' : 'm/d/Y'),
                ]);
            });

            echo $csv->toString();
        }, 'users-export-'.now()->format('Y-m-d').'.csv', [
            'Content-Type' => 'text/csv; charset=UTF-8',
        ]);
    }

    public function exportPdf(): ?StreamedResponse
    {
        $users = $this->getFilteredUsers()->get();

        if ($users->isEmpty()) {
            $this->dispatch('notify', type: 'info', message: __('export.no_users_match'));

            return null;
        }

        if ($users->count() > 500) {
            $this->dispatch('notify', type: 'warning', message: __('export.large_export_warning'));
        }

        $locale = auth()->user()->preferred_language ?? 'ar';

        $pdf = Pdf::loadView('pdf.users-export', [
            'users' => $users,
            'locale' => $locale,
            'generatedAt' => now(),
            'filters' => $this->getActiveFilters(),
            'totalCount' => $users->count(),
        ]);

        $pdf->setOption('isHtml5ParserEnabled', true);
        $pdf->setOption('defaultFont', 'DejaVu Sans');

        return response()->streamDownload(
            fn () => print($pdf->output()),
            'users-export-'.now()->format('Y-m-d').'.pdf'
        );
    }

    public function clearFilters(): void
    {
        $this->userType = 'all';
        $this->status = 'all';
        $this->dateFrom = '';
        $this->dateTo = '';
    }

    public function with(): array
    {
        return [
            'userTypes' => [
                'all' => __('export.all_types'),
                'individual' => __('export.type_individual'),
                'company' => __('export.type_company'),
            ],
            'statuses' => [
                'all' => __('export.all_statuses'),
                'active' => __('export.status_active'),
                'deactivated' => __('export.status_deactivated'),
            ],
            'previewCount' => $this->getFilteredUsers()->count(),
        ];
    }

    private function getFilteredUsers()
    {
        return User::query()
            ->when($this->userType !== 'all', fn ($q) => $q->where('user_type', $this->userType))
            ->when($this->status !== 'all', fn ($q) => $q->where('status', $this->status))
            ->when($this->dateFrom, fn ($q) => $q->whereDate('created_at', '>=', $this->dateFrom))
            ->when($this->dateTo, fn ($q) => $q->whereDate('created_at', '<=', $this->dateTo))
            ->whereIn('user_type', [UserType::Individual, UserType::Company])
            ->orderBy('created_at', 'desc');
    }

    private function getActiveFilters(): array
    {
        $filters = [];

        if ($this->userType !== 'all') {
            $filters['user_type'] = __('export.type_'.$this->userType);
        }

        if ($this->status !== 'all') {
            $filters['status'] = __('export.status_'.$this->status);
        }

        if ($this->dateFrom) {
            $filters['date_from'] = $this->dateFrom;
        }

        if ($this->dateTo) {
            $filters['date_to'] = $this->dateTo;
        }

        return $filters;
    }
}; ?>

<div>
    <div class="mb-6 flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
        <div>
            <flux:heading size="xl">{{ __('export.export_users') }}</flux:heading>
            <flux:text class="mt-1 text-zinc-500">{{ __('export.export_users_description') }}</flux:text>
        </div>
    </div>

    <div class="mb-6 rounded-lg border border-zinc-200 bg-white p-6">
        <flux:heading size="lg" class="mb-4">{{ __('export.filters_applied') }}</flux:heading>

        <div class="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-4">
            <div>
                <flux:select wire:model.live="userType" :label="__('export.user_type')">
                    @foreach ($userTypes as $value => $label)
                        <flux:select.option value="{{ $value }}">{{ $label }}</flux:select.option>
                    @endforeach
                </flux:select>
            </div>

            <div>
                <flux:select wire:model.live="status" :label="__('export.status')">
                    @foreach ($statuses as $value => $label)
                        <flux:select.option value="{{ $value }}">{{ $label }}</flux:select.option>
                    @endforeach
                </flux:select>
            </div>

            <div>
                <flux:input
                    wire:model.live="dateFrom"
                    type="date"
                    :label="__('export.date_from')"
                />
            </div>

            <div>
                <flux:input
                    wire:model.live="dateTo"
                    type="date"
                    :label="__('export.date_to')"
                />
            </div>
        </div>

        @if ($userType !== 'all' || $status !== 'all' || $dateFrom || $dateTo)
            <div class="mt-4">
                <flux:button wire:click="clearFilters" variant="outline" icon="x-mark" size="sm">
                    {{ __('export.clear_filters') }}
                </flux:button>
            </div>
        @endif
    </div>

    <div class="rounded-lg border border-zinc-200 bg-white p-6">
        <div class="flex flex-col items-center justify-between gap-4 sm:flex-row">
            <div>
                <flux:text class="text-zinc-600">
                    {{ __('export.total_records') }}: <span class="font-semibold text-zinc-900">{{ $previewCount }}</span>
                </flux:text>
            </div>

            <div class="flex gap-3">
                <flux:button
                    wire:click="exportCsv"
                    wire:loading.attr="disabled"
                    wire:target="exportCsv,exportPdf"
                    variant="primary"
                    icon="document-arrow-down"
                    :disabled="$previewCount === 0"
                >
                    <span wire:loading.remove wire:target="exportCsv">{{ __('export.export_csv') }}</span>
                    <span wire:loading wire:target="exportCsv">{{ __('export.exporting') }}</span>
                </flux:button>

                <flux:button
                    wire:click="exportPdf"
                    wire:loading.attr="disabled"
                    wire:target="exportCsv,exportPdf"
                    variant="outline"
                    icon="document-text"
                    class="!bg-zinc-700 !text-white hover:!bg-zinc-800"
                    :disabled="$previewCount === 0"
                >
                    <span wire:loading.remove wire:target="exportPdf">{{ __('export.export_pdf') }}</span>
                    <span wire:loading wire:target="exportPdf">{{ __('export.exporting') }}</span>
                </flux:button>
            </div>
        </div>

        @if ($previewCount === 0)
            <div class="mt-6 rounded-lg bg-zinc-50 p-8 text-center">
                <flux:icon name="users" class="mx-auto mb-4 h-12 w-12 text-zinc-400" />
                <flux:text class="text-zinc-500">{{ __('export.no_users_match') }}</flux:text>
            </div>
        @endif
    </div>
</div>
