<?php

namespace App\Extensions\Installed\Importer\Livewire\Csv;

use Livewire\Component;
use Livewire\WithFileUploads;
use App\Extensions\Installed\Importer\Models\ImportJob;
use App\Extensions\Installed\Importer\Services\CsvImporter;
use Illuminate\Support\Facades\Storage;

class Upload extends Component
{
    use WithFileUploads;

    public $file;
    public $importType = 'customers';
    public $importName = '';

    protected array $defaultImportTypes = [
        'customers' => [
            'name' => 'Customers',
            'description' => 'Import client records and contact details.',
            'icon' => 'heroicon-o-user-group',
            'required_fields' => ['name', 'email'],
            'optional_fields' => ['company'],
        ],
        'departments' => [
            'name' => 'Departments',
            'description' => 'Import support departments and settings.',
            'icon' => 'heroicon-o-building-office-2',
            'required_fields' => ['department_name'],
            'optional_fields' => [
                'slug',
                'department_description',
                'department_email',
                'allows_high_priority',
                'cc_enabled',
                'is_public',
                'is_disabled',
                'soft_deleted',
                'created_at',
                'updated_at',
            ],
        ],
        'tickets' => [
            'name' => 'Tickets',
            'description' => 'Import support tickets and conversations.',
            'icon' => 'heroicon-o-lifebuoy',
            'required_fields' => ['subject', 'department_id or department_name'],
            'optional_fields' => [
                'user_id',
                'user_email',
                'public_name',
                'public_email',
                'message',
                'status',
                'priority',
                'department_id',
                'department_name',
                'assigned',
                'ip_address',
                'organize',
                'created_at',
                'updated_at',
            ],
        ],
        'responses' => [
            'name' => 'Responses',
            'description' => 'Import ticket replies and internal notes.',
            'icon' => 'heroicon-o-chat-bubble-left-right',
            'required_fields' => ['ticket_id', 'content'],
            'optional_fields' => [
                'ticket_number',
                'user_id',
                'employee_response',
                'is_employee',
                'is_note',
                'organize',
                'ip_address',
                'created_at',
                'updated_at',
            ],
        ],
    ];

    protected $rules = [
        'file' => 'required|file|mimes:csv,txt|max:10240', // 10MB max
        'importType' => 'required|in:customers,departments,tickets,responses',
        'importName' => 'nullable|string|max:255',
    ];

    public function uploadFile()
    {
        $this->validate();

        try {
            // Store the file
            $fileName = time() . '_' . $this->file->getClientOriginalName();
            $filePath = $this->file->storeAs('importer/uploads', $fileName);
            $fullPath = Storage::path($filePath);

            // Read CSV headers
            $importer = new CsvImporter($fullPath, $this->importType);
            $headers = $importer->getHeaders();

            // Count total rows (excluding header)
            $file = fopen($fullPath, 'r');
            $totalRows = 0;
            fgetcsv($file); // Skip header
            while (fgetcsv($file) !== false) {
                $totalRows++;
            }
            fclose($file);

            // Create import job
            $job = ImportJob::create([
                'name' => $this->importName ?: "Import {$this->importType} - " . now()->format('Y-m-d H:i'),
                'source' => 'csv',
                'type' => $this->importType,
                'status' => 'pending',
                'file_path' => $fullPath,
                'total_rows' => $totalRows,
                'options' => [
                    'delimiter' => ',',
                    'enclosure' => '"',
                    'skip_header' => true,
                    'headers' => $headers,
                ],
            ]);

            session()->flash('success', "File uploaded successfully! {$totalRows} rows detected.");

            return redirect()->route('extensions.importer.csv.mapping', ['jobId' => $job->id]);
        } catch (\Exception $e) {
            session()->flash('error', 'Upload failed: ' . $e->getMessage());
        }
    }

    public function render()
    {
        $configuredTypes = config('extensions.importer.import_types');
        $importTypes = is_array($configuredTypes)
            ? array_replace_recursive($this->defaultImportTypes, $configuredTypes)
            : $this->defaultImportTypes;

        $allowedOrder = ['customers', 'departments', 'tickets', 'responses'];

        $importTypes = array_filter(
            $importTypes,
            fn ($config, $key) => in_array($key, $allowedOrder, true),
            ARRAY_FILTER_USE_BOTH
        );

        $orderedTypes = [];
        foreach ($allowedOrder as $key) {
            if (isset($importTypes[$key])) {
                $orderedTypes[$key] = $importTypes[$key];
            }
        }
        $importTypes = $orderedTypes;

        if (!array_key_exists($this->importType, $importTypes)) {
            $this->importType = array_key_first($importTypes);
        }

        $maxFileSizeBytes = config('extensions.importer.max_file_size', 10 * 1024 * 1024);
        $maxFileSizeMB = max(1, round($maxFileSizeBytes / 1024 / 1024));

        $selectedType = $importTypes[$this->importType];

        return view('extension.importer::csv.upload', [
            'importTypes' => $importTypes,
            'selectedType' => $selectedType,
            'requiredFields' => $selectedType['required_fields'] ?? [],
            'optionalFields' => $selectedType['optional_fields'] ?? [],
            'maxFileSizeMB' => $maxFileSizeMB,
            'sources' => [
                'csv' => ['enabled' => true],
                'database' => ['enabled' => true],
            ],
        ])->layout('components.layouts.app', ['title' => 'CSV Upload', 'noPadding' => true]);
    }
}
