<?php

namespace App\Livewire\WhatsApp;

use App\Models\Role;
use App\Models\User;
use App\Models\WhatsAppGroup;
use App\Services\AttendanceProcessorService;
use App\Services\WhatsAppService;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Livewire\Component;

use App\Traits\WithToastNotifications;

class WhatsAppGatewayIndex extends Component
{
    use AuthorizesRequests, WithToastNotifications;

    // Config fields
    public string $provider = 'fonnte';
    public string $token = '';
    public bool $isTokenMasked = true;
    public int $minDelay = 5;
    public int $maxDelay = 15;

    // Connection Status
    public ?array $connectionStatus = null;
    public bool $isCheckingConnection = false;

    // Fetched Groups List from WA API
    public array $fetchedGroups = [];
    public bool $isFetchingGroups = false;

    // Form Field for Mapping Group WA Orang Tua
    public string $newTargetType = 'class'; // 'class', 'all_parents'
    public string $newClassName = '';
    public string $newGroupName = '';
    public string $newGroupTargetId = '';

    // Edit Group Mapping (inline edit saved groups)
    public ?int $editingGroupId = null;
    public string $editGroupName = '';
    public string $editGroupTargetId = '';

    // Test Broadcast Form
    public string $testTargetId = '';
    public string $testMessageTitle = 'UJI COBA NOTIFIKASI PRESENSI';
    public string $testMessageContent = 'Ini adalah pesan uji coba sistem presensi otomatis ke Group WA Orang Tua SMKN 1 Gunung Agung.';

    // CRUD Parent Phone Modal State
    public bool $showParentsModal = false;
    public ?string $selectedClassForParents = null;
    public string $parentSearch = '';

    // Editing Single Parent Form
    public ?int $editingUserId = null;
    public string $editStudentName = '';
    public string $editNipNis = '';
    public string $editParentPhone = '';
    public string $editClassName = '';

    public function mount(WhatsAppService $whatsAppService): void
    {
        $this->provider = config('services.whatsapp.provider', 'fonnte');
        $this->token = config('services.whatsapp.token', '');
        $this->minDelay = config('services.whatsapp.min_delay_seconds', 5);
        $this->maxDelay = config('services.whatsapp.max_delay_seconds', 15);
        $schoolName = \App\Models\SchoolSetting::get('school_name', 'SMKN 1 Gunung Agung');
        $this->testMessageContent = "Ini adalah pesan uji coba sistem presensi otomatis ke Group WA Orang Tua {$schoolName}.";
    }

    public function updatedNewClassName($value): void
    {
        if (!empty($value)) {
            // Hanya isi nama tampilan. Target ID HARUS diisi dari Fonnte (bukan nama teks)
            $this->newGroupName = "Group Orang Tua {$value}";
            // Kosongkan Target ID agar user memilih dari Fonnte atau isi manual ID @g.us
            $this->newGroupTargetId = '';
        }
    }

    public function updatedNewGroupTargetId($value): void
    {
        if (!empty($value) && !empty($this->fetchedGroups)) {
            foreach ($this->fetchedGroups as $g) {
                if ($g['id'] == $value) {
                    $this->newGroupName = $g['name'];
                    break;
                }
            }
        }
    }

    public function toggleTokenMask(): void
    {
        $this->isTokenMasked = !$this->isTokenMasked;
    }

    public function saveToken(): void
    {
        $this->authorize('create', User::class);

        $this->validate([
            'token' => ['required', 'string', 'min:10'],
        ], [
            'token.required' => 'Token API WA wajib diisi.',
            'token.min' => 'Token API WA minimal 10 karakter.',
        ]);

        $envPath = base_path('.env');
        if (file_exists($envPath)) {
            $envContent = file_get_contents($envPath);
            if (str_contains($envContent, 'WA_API_TOKEN=')) {
                $envContent = preg_replace('/WA_API_TOKEN=.*/', 'WA_API_TOKEN=' . $this->token, $envContent);
            } else {
                $envContent .= "\nWA_API_TOKEN=" . $this->token;
            }
            file_put_contents($envPath, $envContent);
        }

        config(['services.whatsapp.token' => $this->token]);

        session()->flash('toast', ['type' => 'success', 'message' => 'Token API WhatsApp Gateway berhasil disimpan!']);
    }

    public function checkConnection(WhatsAppService $whatsAppService): void
    {
        $this->authorize('create', User::class);
        $this->isCheckingConnection = true;
        
        config(['services.whatsapp.token' => $this->token]);

        $this->connectionStatus = $whatsAppService->checkConnection();
        $this->isCheckingConnection = false;

        if ($this->connectionStatus['success']) {
            $this->notifySuccess($this->connectionStatus['message']);
        } else {
            $this->notifyError($this->connectionStatus['message']);
        }
    }

    public function triggerDailyWaRecap(): void
    {
        $this->authorize('create', User::class);

        \Illuminate\Support\Facades\Artisan::call('wa:send-daily-recap', ['--force' => true]);

        $this->notifySuccess('🚀 Notifikasi Rekap WA Harian Otomatis berhasil dipicu! Laporan dikirimkan ke grup WA orang tua per kelas.');
    }

    public bool $manualInputMode = false;

    public function toggleManualInputMode(): void
    {
        $this->manualInputMode = !$this->manualInputMode;
    }

    public function fetchGroupsFromApi(WhatsAppService $whatsAppService): void
    {
        $this->authorize('create', User::class);
        $this->isFetchingGroups = true;

        $token = trim($this->token);
        if (empty($token)) {
            $this->isFetchingGroups = false;
            session()->flash('toast', ['type' => 'error', 'message' => 'Token API WA belum diisi. Silakan isi dan simpan Token di Langkah 1 terlebih dahulu.']);
            return;
        }

        config(['services.whatsapp.token' => $token]);

        $this->fetchedGroups = $whatsAppService->fetchGroups();
        $this->isFetchingGroups = false;

        if (!empty($this->fetchedGroups)) {
            $this->manualInputMode = false;
            session()->flash('toast', ['type' => 'success', 'message' => 'Berhasil mendeteksi ' . count($this->fetchedGroups) . ' Group WhatsApp di HP Sekolah. Silakan pilih dari dropdown di bawah.']);
        } else {
            session()->flash('toast', ['type' => 'error', 'message' => 'Tidak ditemukan group WA atau perangkat Fonnte belum terhubung (connect). Anda dapat mengklik tombol ketik manual di bawah.']);
        }
    }

    public function saveGroupMapping(): void
    {
        $this->authorize('create', User::class);

        $this->newClassName = trim($this->newClassName);
        $this->newGroupTargetId = trim($this->newGroupTargetId);
        $this->newGroupName = trim($this->newGroupName);

        $rules = [
            'newGroupName' => ['required', 'string', 'max:255'],
            'newGroupTargetId' => ['required', 'string', 'max:255', 'regex:/.+@g\.us$/'],
            'newTargetType' => ['required', 'in:class,all_parents,teachers'],
        ];

        if ($this->newTargetType === 'class') {
            $rules['newClassName'] = ['required', 'string', 'max:100'];
        }

        $this->validate($rules, [
            'newGroupName.required' => 'Nama Tampilan Group WA wajib diisi.',
            'newGroupTargetId.required' => 'Target Group WA (JID) wajib diisi.',
            'newGroupTargetId.regex' => 'Target Group WA harus berformat JID group, contoh: 120363...@g.us',
            'newClassName.required' => 'Nama kelas wajib diisi untuk mapping tipe kelas.',
        ]);

        WhatsAppGroup::updateOrCreate(
            [
                'target_type' => $this->newTargetType,
                'class_name' => $this->newTargetType === 'class' ? $this->newClassName : null,
            ],
            [
                'group_name' => $this->newGroupName,
                'group_target_id' => $this->newGroupTargetId,
                'is_active' => true,
            ]
        );

        session()->flash('toast', ['type' => 'success', 'message' => 'Group WA Orang Tua berhasil disimpan.']);
        $this->resetGroupForm();
    }

    public function deleteGroupMapping(int $id): void
    {
        $this->authorize('create', User::class);
        WhatsAppGroup::destroy($id);
        session()->flash('toast', ['type' => 'success', 'message' => 'Mapping Group WA berhasil dihapus.']);
    }

    public function openEditGroupMapping(int $id): void
    {
        $this->authorize('create', User::class);
        $group = WhatsAppGroup::findOrFail($id);
        $this->editingGroupId = $group->id;
        $this->editGroupName = $group->group_name;
        $this->editGroupTargetId = $group->group_target_id;
    }

    public function updateGroupMapping(): void
    {
        $this->authorize('create', User::class);

        $this->validate([
            'editGroupName' => ['required', 'string', 'max:255'],
            'editGroupTargetId' => ['required', 'string', 'max:255'],
        ], [
            'editGroupName.required' => 'Nama Group WA wajib diisi.',
            'editGroupTargetId.required' => 'Target ID Group WA wajib diisi (harus berformat @g.us dari Fonnte).',
        ]);

        WhatsAppGroup::where('id', $this->editingGroupId)->update([
            'group_name' => $this->editGroupName,
            'group_target_id' => $this->editGroupTargetId,
        ]);

        $this->editingGroupId = null;
        $this->editGroupName = '';
        $this->editGroupTargetId = '';
        session()->flash('toast', ['type' => 'success', 'message' => 'Target ID Group WA berhasil diperbarui!']);
    }

    public function cancelEditGroupMapping(): void
    {
        $this->editingGroupId = null;
        $this->editGroupName = '';
        $this->editGroupTargetId = '';
    }

    public function sendTestBroadcast(WhatsAppService $whatsAppService): void
    {
        $this->authorize('create', User::class);

        if (empty($this->token)) {
            $this->token = config('services.whatsapp.token') ?: env('WA_API_TOKEN', '');
        }

        if (empty($this->testTargetId)) {
            session()->flash('toast', ['type' => 'error', 'message' => 'Silakan pilih Group WA / No HP tujuan uji coba terlebih dahulu pada dropdown.']);
            return;
        }

        if (empty($this->token)) {
            session()->flash('toast', ['type' => 'error', 'message' => 'Token WA Gateway belum diisi. Masukkan Token API Fonnte Anda pada Langkah 1 lalu klik [💾 Simpan Token WA Permanen].']);
            return;
        }

        config(['services.whatsapp.token' => $this->token]);

        $sent = $whatsAppService->sendMessage($this->testTargetId, $this->testMessageTitle, $this->testMessageContent);

        if ($sent) {
            session()->flash('toast', ['type' => 'success', 'message' => "Pesan Uji Coba berhasil terkirim ke WhatsApp ({$this->testTargetId})!"]);
        } else {
            session()->flash('toast', ['type' => 'error', 'message' => 'Gagal mengirim pesan ke WhatsApp. Pastikan HP Sekolah sudah di-scan di Fonnte & Target ID valid.']);
        }
    }

    public function broadcastAllGroups(AttendanceProcessorService $processorService): void
    {
        $this->authorize('create', User::class);

        config(['services.whatsapp.token' => $this->token]);

        $date = now()->toDateString();
        $processorService->processUnprocessedLogs();
        $processorService->generateAlphaRecordsForDate($date);

        $sentCount = $processorService->broadcastDailySummaryToParentGroups($date);

        session()->flash('toast', [
            'type' => 'success',
            'message' => "Rekapitulasi presensi otomatis hari ini ({$date}) berhasil dikirim ke {$sentCount} Group WA Orang Tua!",
        ]);
    }

    // --- PARENT PHONE CRUD METHODS ---

    public function openParentsModal(?string $className = null): void
    {
        $this->selectedClassForParents = $className;
        $this->parentSearch = '';
        $this->editingUserId = null;
        $this->showParentsModal = true;
    }

    public function closeParentsModal(): void
    {
        $this->showParentsModal = false;
        $this->editingUserId = null;
    }

    public function openEditParentModal(int $userId): void
    {
        $currentUser = auth()->user();
        if (!$currentUser || (!$currentUser->isSuperAdmin() && !$currentUser->isAdminTU() && !$currentUser->hasRole('kepala_sekolah'))) {
            session()->flash('toast', ['type' => 'error', 'message' => 'Anda tidak memiliki hak akses untuk mengubah data ini.']);
            return;
        }

        $user = User::findOrFail($userId);
        
        $this->editingUserId = $user->id;
        $this->editStudentName = $user->name;
        $this->editNipNis = $user->nip_nis ?? '-';
        $this->editParentPhone = $user->phone_number ?? '';
        $this->editClassName = $user->class_name ?? '';
    }

    public function updateParentPhone(): void
    {
        $currentUser = auth()->user();
        if (!$currentUser || (!$currentUser->isSuperAdmin() && !$currentUser->isAdminTU() && !$currentUser->hasRole('kepala_sekolah'))) {
            session()->flash('toast', ['type' => 'error', 'message' => 'Anda tidak memiliki hak akses untuk mengubah data ini.']);
            return;
        }

        if (!$this->editingUserId) {
            return;
        }

        $this->validate([
            'editParentPhone' => ['nullable', 'string', 'max:20'],
            'editClassName' => ['nullable', 'string', 'max:50'],
        ]);

        $user = User::findOrFail($this->editingUserId);
        $user->update([
            'phone_number' => $this->editParentPhone,
            'class_name' => $this->editClassName,
        ]);

        $this->editingUserId = null;
        session()->flash('toast', ['type' => 'success', 'message' => "Nomor HP Orang Tua {$user->name} berhasil diperbarui!"]);
    }

    public function cancelEditParent(): void
    {
        $this->editingUserId = null;
    }

    private function resetGroupForm(): void
    {
        $this->newTargetType = 'class';
        $this->newClassName = '';
        $this->newGroupName = '';
        $this->newGroupTargetId = '';
    }

    public function sendDirectTestToParent(int $userId, WhatsAppService $whatsAppService): void
    {
        $this->authorize('create', User::class);
        $user = User::findOrFail($userId);

        if (empty($user->phone_number)) {
            session()->flash('toast', ['type' => 'error', 'message' => "Nomor HP Orang Tua {$user->name} belum terisi."]);
            return;
        }

        if (empty($this->token)) {
            $this->token = config('services.whatsapp.token') ?: env('WA_API_TOKEN', '');
        }

        if (empty($this->token)) {
            session()->flash('toast', ['type' => 'error', 'message' => 'Token WA Gateway belum diisi. Masukkan Token API Fonnte Anda pada Langkah 1 lalu klik [💾 Simpan Token WA Permanen].']);
            return;
        }

        config(['services.whatsapp.token' => $this->token]);

        $schoolName = \App\Models\SchoolSetting::get('school_name', 'SMKN 1 Gunung Agung');
        $title = "UJI COBA NOTIFIKASI WA ORANG TUA";
        $content = "Halo Bapak/Ibu Wali Murid dari {$user->name} ({$user->class_name}), ini adalah pesan uji coba sistem presensi otomatis {$schoolName}.";

        $sent = $whatsAppService->sendMessage($user->phone_number, $title, $content);

        if ($sent) {
            session()->flash('toast', ['type' => 'success', 'message' => "Pesan Uji Coba WA berhasil terkirim langsung ke No HP Orang Tua {$user->name} ({$user->phone_number})!"]);
        } else {
            session()->flash('toast', ['type' => 'error', 'message' => "Gagal mengirim pesan ke {$user->phone_number}. Pastikan HP Sekolah sudah di-scan di Fonnte & nomor WA aktif."]);
        }
    }

    public function render()
    {
        $this->authorize('viewAny', User::class);

        $savedGroups = WhatsAppGroup::latest()->get();
        $classList = User::whereNotNull('class_name')->where('class_name', '!=', '')->distinct()->pluck('class_name')->sort()->values();
        $studentsWithPhone = User::whereNotNull('phone_number')
            ->where('phone_number', '!=', '')
            ->orderBy('class_name')
            ->orderBy('name')
            ->get();

        // Query students for parents modal
        $parentsList = collect();
        if ($this->showParentsModal) {
            $siswaRoleId = Role::where('name', 'siswa')->first()?->id ?? 5;
            $query = User::where(function($q) use ($siswaRoleId) {
                $q->where('role_id', $siswaRoleId)
                  ->orWhere(function($sub) {
                      $sub->whereNotNull('class_name')->where('class_name', '!=', '');
                  });
            });

            if (!empty($this->selectedClassForParents)) {
                $className = trim($this->selectedClassForParents);
                $query->where(function($q) use ($className) {
                    $q->where('class_name', $className)
                      ->orWhere('class_name', 'like', $className . '%');
                });
            }

            if (!empty($this->parentSearch)) {
                $s = '%' . trim($this->parentSearch) . '%';
                $query->where(function ($q) use ($s) {
                    $q->where('name', 'like', $s)
                        ->orWhere('nip_nis', 'like', $s)
                        ->orWhere('phone_number', 'like', $s)
                        ->orWhere('class_name', 'like', $s);
                });
            }

            $parentsList = $query->orderBy('class_name')->orderBy('name')->get();
        }

        return view('livewire.whatsapp.whatsapp-gateway-index', [
            'savedGroups' => $savedGroups,
            'classList' => $classList,
            'studentsWithPhone' => $studentsWithPhone,
            'parentsList' => $parentsList,
        ])->layout('components.layouts.app');
    }
}
