<?php

namespace Botble\JobBoard\Tables;

use Botble\Base\Enums\BaseStatusEnum;
use Botble\Base\Facades\Html;
use Botble\JobBoard\Models\Company;
use Botble\Media\Facades\RvMedia;
use Botble\Table\Abstracts\TableAbstract;
use Botble\Table\Actions\Action;
use Botble\Table\Actions\DeleteAction;
use Botble\Table\Actions\EditAction;
use Botble\Table\BulkActions\DeleteBulkAction;
use Botble\Table\Columns\Column;
use Botble\Table\Columns\CreatedAtColumn;
use Botble\Table\Columns\IdColumn;
use Botble\Table\Columns\NameColumn;
use Botble\Table\Columns\StatusColumn;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Builder as EloquentBuilder;
use Illuminate\Database\Eloquent\Relations\Relation;
use Illuminate\Database\Eloquent\Relations\Relation as EloquentRelation;
use Illuminate\Database\Query\Builder as QueryBuilder;
use Illuminate\Http\JsonResponse;

class CompanyTable extends TableAbstract
{
    public function setup(): void
    {
        $this
            ->model(Company::class)
            ->addActions([
                Action::make('analytics')->route('companies.analytics')->label(__('Analytics'))->color('info'),
                EditAction::make()->route('companies.edit'),
                DeleteAction::make()->route('companies.destroy'),
            ]);
    }

    public function ajax(): JsonResponse
    {
        $data = $this->table
            ->eloquent($this->query())
            ->editColumn('name', function (Company $item) {
                if (! $this->hasPermission('companies.edit')) {
                    return $item->name;
                }

                return Html::link(route('companies.edit', $item->getKey()), $item->name);
            })
            ->editColumn('logo', function (Company $item) {
                return Html::image(
                    RvMedia::getImageUrl($item->logo, 'thumb', false, RvMedia::getDefaultImage()),
                    $item->name,
                    ['width' => 50]
                );
            });

        return $this->toJson($data);
    }

    public function query(): Relation|Builder|QueryBuilder
    {
        $query = $this
            ->getModel()
            ->query()
            ->select([
                'id',
                'logo',
                'name',
                'created_at',
                'status',
            ]);

        return $this->applyScopes($query);
    }

    public function columns(): array
    {
        return [
            IdColumn::make(),
            Column::make('logo')
                ->title(__('Logo'))
                ->width(70),
            NameColumn::make(),
            CreatedAtColumn::make(),
            StatusColumn::make(),
        ];
    }

    public function buttons(): array
    {
        $buttons = $this->addCreateButton(route('companies.create'), 'companies.create');

        if ($this->hasPermission('import-companies.index')) {
            $buttons['import'] = [
                'link' => route('import-companies.index'),
                'text' => '<i class="fas fa-cloud-upload-alt"></i> ' . trans('plugins/job-board::import.company.name'),
                'class' => 'btn-warning',
            ];
        }

        if ($this->hasPermission('export-companies.index')) {
            $buttons['export'] = [
                'link' => route('export-companies.index'),
                'text' => '<i class="fas fa-cloud-download-alt"></i> ' . trans(
                    'plugins/job-board::export.companies.name'
                ),
                'class' => 'btn-warning',
            ];
        }

        return $buttons;
    }

    public function bulkActions(): array
    {
        return [
            DeleteBulkAction::make()->permission('companies.destroy'),
        ];
    }

    public function getBulkChanges(): array
    {
        return [
            'name' => [
                'title' => trans('core/base::tables.name'),
                'type' => 'text',
                'validate' => 'required|max:120',
            ],
            'status' => [
                'title' => trans('core/base::tables.status'),
                'type' => 'select',
                'choices' => BaseStatusEnum::labels(),
                'validate' => 'required|in:' . implode(',', BaseStatusEnum::values()),
            ],
            'created_at' => [
                'title' => trans('core/base::tables.created_at'),
                'type' => 'datePicker',
            ],
            'is_completed_profile' => [
                'title' => __('Is completed profile?'),
                'type' => 'select',
                'choices' => [
                    'completed' => __('Yes'),
                    'incomplete' => __('No'),
                ],
            ],
        ];
    }

    public function getOperationsHeading(): array
    {
        return [
            'operations' => [
                'title' => trans('core/base::tables.operations'),
                'width' => '300px',
                'class' => 'text-center',
                'orderable' => false,
                'searchable' => false,
                'exportable' => false,
                'printable' => false,
            ],
        ];
    }

    public function applyFilterCondition(
        EloquentBuilder|QueryBuilder|EloquentRelation $query,
        string $key,
        string $operator,
        ?string $value
    ): EloquentRelation|EloquentBuilder|QueryBuilder {
        if ($key == 'is_completed_profile') {
            switch ($value) {
                case 'completed':
                    // @phpstan-ignore-next-line
                    return $query->completedProfile();
                case 'incomplete':
                    // @phpstan-ignore-next-line
                    return $query->incompleteProfile();
            }
        }

        return parent::applyFilterCondition($query, $key, $operator, $value);
    }
}
