<?php

namespace App\Filament\Resources\BtsPowerConsumptionResource\Pages;

use App\Filament\Resources\BtsPowerConsumptionResource;
use App\Models\BtsPowerConsumption;
use App\Jobs\ProcessBtsPowerConsumptionJob;
use Filament\Actions;
use Filament\Resources\Pages\ListRecords;
use Filament\Forms;
use Filament\Forms\Form;
use Filament\Notifications\Notification;
use Illuminate\Support\Facades\Response;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;

class ListBtsPowerConsumptions extends ListRecords
{
    protected static string $resource = BtsPowerConsumptionResource::class;

    protected function getHeaderActions(): array
    {
        return [
            // Actions\CreateAction::make(),
            Actions\Action::make('upload_file')
            ->label('Upload File')
            ->icon('heroicon-o-cloud-arrow-up')
            ->form([
                Forms\Components\Select::make('template_type')
                    ->label('Loại file')
                    ->options([
                        'full' => 'Trạm BTS có đủ các thành phần',
                        'no_cooling' => 'Trạm BTS không có Cooling',
                        'no_tx' => 'Trạm BTS không có TX',
                    ])
                    ->reactive()
                    ->afterStateUpdated(function (callable $set, $state) {
                        // Đặt default thresholds theo loại template
                        $defaults = match ($state) {
                            'full' => [
                                'low_medium' => ['min' => 0, 'max' => 9400],
                                'medium_high' => ['min' => 9400, 'max' => 20000],
                                'high' => ['min' => 20000, 'max' => 50000],
                                'extreme' => ['min' => 50000, 'max' => null],
                            ],
                            'no_cooling' => [
                                'low_medium' => ['min' => 0, 'max' => 6500],
                                'medium_high' => ['min' => 6500, 'max' => 15000],
                                'high' => ['min' => 15000, 'max' => 35000],
                                'extreme' => ['min' => 35000, 'max' => null],
                            ],
                            'no_tx' => [
                                'low_medium' => ['min' => 0, 'max' => 5500],
                                'medium_high' => ['min' => 5500, 'max' => 12000],
                                'high' => ['min' => 12000, 'max' => 25000],
                                'extreme' => ['min' => 25000, 'max' => null],
                            ],
                            default => [],
                        };
        
                        foreach ($defaults as $class => $values) {
                            $set("thresholds.$class.min", $values['min']);
                            $set("thresholds.$class.max", $values['max']);
                        }
                    })
                    ->required(),
        
                Forms\Components\Fieldset::make('Ngưỡng phân loại Power Consumption')
                    ->schema([
                        Forms\Components\Grid::make(3)
                            ->schema([
                                Forms\Components\Placeholder::make('class_header')->label('Power Consumption Class'),
                                Forms\Components\Placeholder::make('min_header')->label('Khoảng giá trị'),
                                Forms\Components\Placeholder::make('range_header')->label('(min, max]'),
                            ]),
        
                        // low_medium
                        Forms\Components\Grid::make(3)
                            ->schema([
                                Forms\Components\Placeholder::make('class_name_low')->label('low_medium'),
                                Forms\Components\TextInput::make('thresholds.low_medium.min')->numeric(),
                                Forms\Components\TextInput::make('thresholds.low_medium.max')->numeric(),
                            ]),
        
                        // medium_high
                        Forms\Components\Grid::make(3)
                            ->schema([
                                Forms\Components\Placeholder::make('class_name_medium')->label('medium_high'),
                                Forms\Components\TextInput::make('thresholds.medium_high.min')->numeric(),
                                Forms\Components\TextInput::make('thresholds.medium_high.max')->numeric(),
                            ]),
        
                        // high
                        Forms\Components\Grid::make(3)
                            ->schema([
                                Forms\Components\Placeholder::make('class_name_high')->label('high'),
                                Forms\Components\TextInput::make('thresholds.high.min')->numeric(),
                                Forms\Components\TextInput::make('thresholds.high.max')->numeric(),
                            ]),
        
                        // extreme
                        Forms\Components\Grid::make(3)
                            ->schema([
                                Forms\Components\Placeholder::make('class_name_extreme')->label('extreme'),
                                Forms\Components\TextInput::make('thresholds.extreme.min')->numeric(),
                                Forms\Components\TextInput::make('thresholds.extreme.max')
                                    ->disabled()
                                    ->placeholder('∞'),
                            ]),
                    ])
                    ->columns(1)
                    ->columnSpanFull(),
        
                Forms\Components\FileUpload::make('file')
                    ->label('File Excel')
                    ->acceptedFileTypes(['application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'])
                    ->required()
                    ->disk('local')
                    ->directory('bts-power')
                    ->preserveFilenames()
                    ->getUploadedFileNameForStorageUsing(function ($file) {
                        $name = pathinfo($file->getClientOriginalName(), PATHINFO_FILENAME);
                        $ext  = $file->getClientOriginalExtension();
                        $now = now()->format('Y_m_d_H_i_s');
                        return $name . '_' . $now . '.' . $ext;
                    }),
            ])
            ->action(fn (array $data) => $this->uploadFile($data)),
        
                Actions\Action::make('download_template')
                ->label('Download Template')
                ->icon('heroicon-o-document-arrow-down')
                ->form([
                    Forms\Components\Select::make('template_type')
                        ->label('Loại trạm BTS')
                        ->options([
                            'full' => 'Trạm BTS có đủ các thành phần',
                            'no_cooling' => 'Trạm BTS không có Cooling',
                            'no_tx' => 'Trạm BTS không có TX'
                        ])
                        ->required()
                        ->default('full')
                ])
                ->action(function (array $data) {
                    return $this->downloadTemplate($data['template_type']);
                }),
        ];
    }

    private function downloadTemplate(string $templateType)
    {
        try {
            $columns = $this->getTemplateColumns($templateType);
            
            // Tạo file Excel
            $filename = 'bts_template_' . $templateType . '_' . date('Y_m_d_H_i_s') . '.xlsx';
            
            // Tạo nội dung file
            $content = $this->generateExcelContent($columns);
            
            // Trả về file download
            return Response::streamDownload(function () use ($content) {
                echo $content;
            }, $filename, [
                'Content-Type' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
                'Content-Disposition' => 'attachment; filename="' . $filename . '"'
            ]);
        } catch (\Exception $e) {
            Notification::make()
                ->title('Lỗi tạo file')
                ->body('Không thể tạo file template: ' . $e->getMessage())
                ->danger()
                ->send();
        }
    }

    private function getTemplateColumns(string $templateType): array
    {
        switch ($templateType) {
            case 'full':
                return [
                    'STT',
                    'Radio_power_consumption_max',
                    'TX_power_consumption_max',
                    'Cooling_power_consumption_max',
                    'BTS_id',
                    'BTS_type',
                    'Radio_config_3G',
                    'Radio_config_4G',
                    'Radio_config_MIMO_4G',
                    'Radio_type',
                    'Radio_model_name',
                    'Radio_family_id',
                    'TX_type',
                    'TX_brand_name',
                    'TX_model_name',
                    'TX_family_id',
                    'Cooling_brand_name',
                    'Cooling_family_id',
                    'Radio_family_type',
                    'TX_family_type',
                    'Cooling_family_type',
                ];
                
            case 'no_cooling':
                return [
                    'STT',
                    'Radio_power_consumption_max',
                    'TX_power_consumption_max',
                    'BTS_id',
                    'BTS_type',
                    'Radio_config_3G',
                    'Radio_config_4G',
                    'Radio_config_MIMO_4G',
                    'Radio_type',
                    'Radio_model_name',
                    'Radio_family_id',
                    'TX_type',
                    'TX_brand_name',
                    'TX_model_name',
                    'TX_family_id',
                    'Radio_family_type',
                    'TX_family_type',
                ];
                
            case 'no_tx':
                return [
                    'STT',
                    'Radio_power_consumption_max',
                    'Cooling_power_consumption_max',
                    'BTS_id',
                    'BTS_type',
                    'Radio_config_3G',
                    'Radio_config_4G',
                    'Radio_config_MIMO_4G',
                    'Radio_type',
                    'Radio_model_name',
                    'Radio_family_id',
                    'Cooling_brand_name',
                    'Cooling_family_id',
                    'Radio_family_type',
                    'Cooling_family_type',
                ];
                
            default:
                return [];
        }
    }

    private function generateExcelContent(array $columns): string
    {
        // Tạo file tạm để tránh lỗi memory
        $tempFile = tempnam(sys_get_temp_dir(), 'bts_template');
        
        try {
            $spreadsheet = new \PhpOffice\PhpSpreadsheet\Spreadsheet();
            $worksheet = $spreadsheet->getActiveSheet();
            
            // Thêm headers
            $col = 'A';
            foreach ($columns as $header) {
                $worksheet->setCellValue($col . '1', $header);
                $col++;
            }
            
            // Tự động giãn column theo nội dung
            foreach (range('A', $col) as $columnID) {
                $worksheet->getColumnDimension($columnID)->setAutoSize(true);
            }
            
            // Lưu vào file tạm
            $writer = new \PhpOffice\PhpSpreadsheet\Writer\Xlsx($spreadsheet);
            $writer->setPreCalculateFormulas(false);
            $writer->save($tempFile);
            
            // Đọc nội dung file
            $content = file_get_contents($tempFile);
            
            return $content;
        } finally {
            // Xóa file tạm
            if (file_exists($tempFile)) {
                unlink($tempFile);
            }
        }
    }

    private function uploadFile(array $data)
    {
        try {
            // Lấy tên file từ đường dẫn
            $fileName = basename($data['file']);

            // Chuẩn bị thresholds để truyền sang job
            $thresholds = [
                'low_medium' => [
                    'min' => $data['thresholds']['low_medium']['min'] ?? 0,
                    'max' => $data['thresholds']['low_medium']['max'] ?? 9400,
                ],
                'medium_high' => [
                    'min' => $data['thresholds']['medium_high']['min'] ?? 9400,
                    'max' => $data['thresholds']['medium_high']['max'] ?? 20000,
                ],
                'high' => [
                    'min' => $data['thresholds']['high']['min'] ?? 20000,
                    'max' => $data['thresholds']['high']['max'] ?? 50000,
                ],
                'extreme' => [
                    'min' => $data['thresholds']['extreme']['min'] ?? 50000,
                    'max' => $data['thresholds']['extreme']['max'] ?? null,
                ],
            ];
            Log::info($thresholds);
            
            // Tạo record trong database (chỉ lưu các field có sẵn)
            $btsPowerConsumption = BtsPowerConsumption::create([
                'file_name' => $fileName,
                'file_type' => $data['template_type'],
                'status' => 'pending',
                'description' => 'File upload để tính BTS power consumption - Template: ' . $data['template_type'],
                'uploaded_by' => Auth::id(),
            ]);

            // Dispatch job để xử lý file (truyền thêm template_type và file_path)
            ProcessBtsPowerConsumptionJob::dispatch(
                $btsPowerConsumption->id, 
                $data['file'], 
                $data['template_type'],
                Auth::id(),
                $thresholds,
            );

            Notification::make()
                ->title('Upload thành công')
                ->body('File đã được upload và đang được xử lý. Vui lòng chờ...')
                ->success()
                ->send();

        } catch (\Exception $e) {
            Notification::make()
                ->title('Lỗi upload file')
                ->body('Không thể upload file: ' . $e->getMessage())
                ->danger()
                ->send();
        }
    }
}
