<?php

namespace Spatie\Mailcoach\Livewire\Mailers;

use Filament\Actions\Action;
use Filament\Actions\ActionGroup;
use Filament\Actions\Concerns\InteractsWithActions;
use Filament\Tables\Columns\IconColumn;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Table;
use Illuminate\Support\HtmlString;
use Spatie\Mailcoach\Domain\Audience\Models\EmailList;
use Spatie\Mailcoach\Domain\Settings\Models\Mailer;
use Spatie\Mailcoach\Domain\Shared\Traits\UsesMailcoachModels;
use Spatie\Mailcoach\Livewire\TableComponent;

class MailersComponent extends TableComponent
{
    use InteractsWithActions;
    use UsesMailcoachModels;

    public function table(Table $table): Table
    {
        return parent::table($table)
            ->query(self::getMailerClass()::query())
            ->recordUrl(fn (Mailer $record) => route('mailers.edit', $record))
            ->emptyStateIcon('heroicon-s-envelope-open')
            ->emptyStateDescription(__mc('You have not added any mailer yet.'))
            ->emptyStateActions([
                Action::make('mailer-docs')
                    ->url('https://mailcoach.app/resources/learn-mailcoach/getting-started/using-an-external-mailer')
                    ->openUrlInNewTab()
                    ->label(__mc('Learn more about mailers'))
                    ->link(),
                Action::make('configuration-docs')
                    ->url('https://mailcoach.app/resources/learn-mailcoach/getting-started/configuring-mail-providers')
                    ->openUrlInNewTab()
                    ->label(__mc('Configuring providers'))
                    ->link(),
            ])
            ->defaultSort('name')
            ->columns([
                TextColumn::make('name')
                    ->label(__mc('Name'))
                    ->extraAttributes(['class' => 'link'])
                    ->sortable(),
                TextColumn::make('transport')
                    ->label(__mc('Transport'))
                    ->sortable(),
                IconColumn::make('ready_for_use')->boolean(),
                IconColumn::make('default')->boolean(),
            ])
            ->recordActions($this->recordActions());
    }

    public function getTitle(): string
    {
        return __mc('Mailers');
    }

    public function getLayout(): string
    {
        return 'mailcoach::app.layouts.settings';
    }

    public function getLayoutData(): array
    {
        return [
            'title' => __mc('Mailers'),
            'create' => 'mailer',
            'createText' => __mc('Create mailer'),
        ];
    }

    protected function recordActions(): array
    {
        return [
            ActionGroup::make([
                Action::make('make-default')
                    ->label(__mc('Make default'))
                    ->icon('heroicon-s-check-circle')
                    ->requiresConfirmation()
                    ->hidden(fn (Mailer $record) => $record->default)
                    ->action(fn (Mailer $record) => $this->markMailerDefault($record)),
                Action::make('delete')
                    ->label(__mc('Delete'))
                    ->icon('heroicon-s-trash')
                    ->color('danger')
                    ->requiresConfirmation()
                    ->modalHeading(fn (Mailer $record) => __mc('Delete :resource', ['resource' => __mc('mailer')]))
                    ->modalDescription(fn (Mailer $record) => new HtmlString(__mc('Are you sure you want to delete :resource<br/><strong>:name</strong>?', [
                        'resource' => __mc('mailer'),
                        'name' => $record->name,
                    ])))
                    ->action(fn (Mailer $record) => $this->deleteMailer($record)),
            ]),
        ];
    }

    public function markMailerDefault(Mailer $mailer)
    {
        if (! $mailer->ready_for_use) {
            notifyError(__mc('Mailer :mailer is not ready for use', ['mailer' => $mailer->name]));

            return;
        }

        self::getMailerClass()::query()->update(['default' => false]);

        $mailer->update(['default' => true]);

        notify(__mc('Mailer :mailer marked as default', ['mailer' => $mailer->name]));
    }

    public function deleteMailer(Mailer $mailer): void
    {
        $configName = $mailer->configName();

        $mailer->delete();

        self::getEmailListClass()::each(function (EmailList $emailList) use ($configName) {
            if ($emailList->campaign_mailer === $configName) {
                $emailList->campaign_mailer = null;
            }

            if ($emailList->automation_mailer === $configName) {
                $emailList->automation_mailer = null;
            }

            if ($emailList->transactional_mailer === $configName) {
                $emailList->transactional_mailer = null;
            }

            $emailList->save();
        });

        notify(__mc('Mailer :mailer successfully deleted', ['mailer' => $mailer->name]));
    }
}
