<?php

namespace App\Livewire\Automation;

use App\Models\Automation;
use Livewire\Component;

class Index extends Component
{
    public bool   $panelOpen  = false;
    public string $activeType = '';

    public string $f_minutes_before     = '30';
    public string $f_send_time          = '08:00';
    public string $f_send_day           = '1';
    public string $f_delay_minutes      = '30';
    public string $f_days_before        = '7';
    public string $f_days_inactive      = '3';
    public string $f_days_since_contact = '14';
    public string $f_min_slot_minutes   = '60';

    public function openPanel(string $type): void
    {
        $types = config('automations.types');
        $this->activeType = $type;
        $automation = $this->getRecord($type);
        $cfg = $automation?->config ?? $types[$type]['defaults'] ?? [];

        $this->f_minutes_before     = (string) ($cfg['minutes_before']     ?? 30);
        $this->f_send_time          = $cfg['send_time']                    ?? '08:00';
        $this->f_send_day           = (string) ($cfg['send_day']           ?? 1);
        $this->f_delay_minutes      = (string) ($cfg['delay_minutes']      ?? 30);
        $this->f_days_before        = (string) ($cfg['days_before']        ?? 7);
        $this->f_days_inactive      = (string) ($cfg['days_inactive']      ?? 3);
        $this->f_days_since_contact = (string) ($cfg['days_since_contact'] ?? 14);
        $this->f_min_slot_minutes   = (string) ($cfg['min_slot_minutes']   ?? 60);

        $this->panelOpen = true;
    }

    public function closePanel(): void
    {
        $this->panelOpen  = false;
        $this->activeType = '';
    }

    public function save(): void
    {
        $types = config('automations.types');
        $type  = $this->activeType;
        if (!isset($types[$type])) return;

        $user       = auth()->user();
        $def        = $types[$type];
        $isPro      = $user->isInternalUser() || $user->hasFeature('automations');
        $isFreeType = (bool) ($def['is_free'] ?? false);

        if (!$isFreeType && !$isPro) {
            $this->closePanel();
            return;
        }

        Automation::updateOrCreate(
            ['user_id' => $user->id, 'type' => $type],
            [
                'name'   => $def['name'],
                'active' => true,
                'config' => $this->buildConfig($type),
            ]
        );

        $this->closePanel();
    }

    public function toggle(string $type): void
    {
        $types = config('automations.types');
        if (!isset($types[$type])) return;

        $user       = auth()->user();
        $def        = $types[$type];
        $isPro      = $user->isInternalUser() || $user->hasFeature('automations');
        $isFreeType = (bool) ($def['is_free'] ?? false);

        if (!$isFreeType && !$isPro) return;

        $record = $this->getRecord($type);

        if ($record) {
            $record->update(['active' => !$record->active]);
        } else {
            Automation::create([
                'user_id' => $user->id,
                'type'    => $type,
                'name'    => $def['name'],
                'active'  => true,
                'config'  => $def['defaults'],
            ]);
        }
    }

    public function delete(string $type): void
    {
        Automation::where('user_id', auth()->id())
            ->where('type', $type)
            ->delete();
    }

    private function getRecord(string $type): ?Automation
    {
        return Automation::where('user_id', auth()->id())
            ->where('type', $type)
            ->first();
    }

    private function buildConfig(string $type): array
    {
        return match ($type) {
            'event_reminder' => [
                'minutes_before' => (int) $this->f_minutes_before,
            ],
            'daily_agenda' => [
                'send_time'     => $this->f_send_time,
                'weekdays_only' => false,
            ],
            'weekly_overview' => [
                'send_day'  => (int) $this->f_send_day,
                'send_time' => $this->f_send_time,
            ],
            'event_followup' => [
                'delay_minutes' => (int) $this->f_delay_minutes,
            ],
            'birthday_reminder' => [
                'days_before' => (int) $this->f_days_before,
            ],
            'no_activity_reminder' => [
                'days_inactive' => (int) $this->f_days_inactive,
            ],
            'daily_summary' => [
                'send_time' => $this->f_send_time,
            ],
            'contact_followup' => [
                'days_since_contact' => (int) $this->f_days_since_contact,
            ],
            'free_slots_report' => [
                'send_day'         => (int) $this->f_send_day,
                'send_time'        => $this->f_send_time,
                'min_slot_minutes' => (int) $this->f_min_slot_minutes,
            ],
            default => [],
        };
    }

    public function render()
    {
        $user    = auth()->user();
        $isPro   = $user->isInternalUser() || $user->hasFeature('automations');
        $records = Automation::where('user_id', $user->id)
            ->get()
            ->keyBy('type');

        return view('livewire.automation.index', [
            'types'   => config('automations.types'),
            'records' => $records,
            'isPro'   => $isPro,
        ])->layout('layouts.app');
    }
}
