<?php

namespace App\Filament\Resources\ClasaResource\Pages;

use App\Filament\Resources\ClasaResource;
use App\Models\Clasa;
use App\Models\Elev;
use Filament\Actions\Action;
use Filament\Forms;
use Filament\Notifications\Notification;
use Filament\Resources\Pages\Page;
use Illuminate\Support\Facades\Auth;
use Livewire\Features\SupportFileUploads\TemporaryUploadedFile;

class ImportElevi extends Page
{
    protected static string $resource = ClasaResource::class;
    protected static string $view = 'filament.pages.import-elevi';
    protected static ?string $title = 'Import elevi';

    public ?int $clasa_id = null;
    public ?array $preview = null;
    public ?string $filePath = null;
    public int $imported = 0;
    public int $skipped = 0;

    public function mount(): void
    {
        $this->clasa_id = request()->query('clasa_id');
    }

    protected function getFormSchema(): array
    {
        $user = Auth::user();
        $isAdmin = $user?->hasRole('admin');

        return [
            Forms\Components\Select::make('clasa_id')
                ->label('Clasa')
                ->options(fn() => Clasa::pluck('nume', 'id'))
                ->required()
                ->searchable()
                ->default($this->clasa_id),
            Forms\Components\FileUpload::make('csv_file')
                ->label('Fișier CSV')
                ->acceptedFileTypes(['text/csv', 'text/plain', 'application/vnd.ms-excel'])
                ->required()
                ->helperText('Format: nume, prenume, data_nasterii (DD.MM.YYYY), cnp, email_parinte, telefon_parinte. Prima linie = header.'),
        ];
    }

    public function preview(): void
    {
        $data = $this->form->getState();
        $this->clasa_id = $data['clasa_id'];

        $file = $data['csv_file'];
        $path = storage_path('app/public/' . $file);

        if (!file_exists($path)) {
            Notification::make()->title('Fișierul nu a fost găsit')->danger()->send();
            return;
        }

        $this->filePath = $path;
        $this->preview = $this->parseCsv($path, 10);
    }

    public function import(): void
    {
        if (!$this->filePath || !$this->clasa_id) {
            return;
        }

        $rows = $this->parseCsv($this->filePath);
        $this->imported = 0;
        $this->skipped = 0;

        foreach ($rows as $row) {
            if (empty($row['nume']) || empty($row['prenume'])) {
                $this->skipped++;
                continue;
            }

            Elev::create([
                'clasa_id' => $this->clasa_id,
                'nume' => trim($row['nume']),
                'prenume' => trim($row['prenume']),
                'data_nasterii' => $this->parseDate($row['data_nasterii'] ?? null),
                'cnp' => trim($row['cnp'] ?? ''),
                'email_parinte' => trim($row['email_parinte'] ?? ''),
                'telefon_parinte' => trim($row['telefon_parinte'] ?? ''),
            ]);
            $this->imported++;
        }

        @unlink($this->filePath);
        $this->preview = null;
        $this->filePath = null;

        Notification::make()
            ->title("Import finalizat: {$this->imported} elevi importați" . ($this->skipped > 0 ? ", {$this->skipped} săriți" : ''))
            ->success()
            ->send();
    }

    private function parseCsv(string $path, ?int $limit = null): array
    {
        $rows = [];
        $handle = fopen($path, 'r');

        $bom = fread($handle, 3);
        if ($bom !== "\xEF\xBB\xBF") {
            rewind($handle);
        }

        $firstLine = fgets($handle);
        $delimiter = str_contains($firstLine, ';') ? ';' : ',';
        rewind($handle);
        if ($bom === "\xEF\xBB\xBF") {
            fread($handle, 3);
        }

        $header = fgetcsv($handle, 0, $delimiter);
        if (!$header) {
            fclose($handle);
            return [];
        }

        $header = array_map(fn($h) => $this->normalizeHeader(trim($h)), $header);

        $count = 0;
        while (($line = fgetcsv($handle, 0, $delimiter)) !== false) {
            if (count($line) < 2) {
                continue;
            }
            $row = [];
            foreach ($header as $i => $key) {
                $row[$key] = $line[$i] ?? '';
            }
            $rows[] = $row;
            $count++;
            if ($limit && $count >= $limit) {
                break;
            }
        }

        fclose($handle);
        return $rows;
    }

    private function normalizeHeader(string $header): string
    {
        $header = mb_strtolower($header);
        $header = str_replace(['ă', 'â', 'î', 'ș', 'ț', 'ş', 'ţ'], ['a', 'a', 'i', 's', 't', 's', 't'], $header);

        $map = [
            'nume' => 'nume',
            'prenume' => 'prenume',
            'data nasterii' => 'data_nasterii',
            'data_nasterii' => 'data_nasterii',
            'cnp' => 'cnp',
            'email parinte' => 'email_parinte',
            'email_parinte' => 'email_parinte',
            'email' => 'email_parinte',
            'telefon parinte' => 'telefon_parinte',
            'telefon_parinte' => 'telefon_parinte',
            'telefon' => 'telefon_parinte',
        ];

        return $map[$header] ?? $header;
    }

    private function parseDate(?string $date): ?string
    {
        if (!$date || empty(trim($date))) {
            return null;
        }
        $date = trim($date);

        if (preg_match('/^\d{2}\.\d{2}\.\d{4}$/', $date)) {
            return \Carbon\Carbon::createFromFormat('d.m.Y', $date)->format('Y-m-d');
        }
        if (preg_match('/^\d{2}\/\d{2}\/\d{4}$/', $date)) {
            return \Carbon\Carbon::createFromFormat('d/m/Y', $date)->format('Y-m-d');
        }
        if (preg_match('/^\d{4}-\d{2}-\d{2}$/', $date)) {
            return $date;
        }

        return null;
    }
}
