<?php

namespace App\Http\Livewire;

use App\Models\invoice\Invoice;
use Closure;
use Livewire\Component;
use Filament\Tables;
use Filament\Forms;
use Filament\Tables\Filters\Filter;
use Filament\Tables\Filters\SelectFilter;
use Filament\Notifications\Notification;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\HtmlString;

class Invoicetable extends Component implements Tables\Contracts\HasTable
{
    use Tables\Concerns\InteractsWithTable;
    public $test;
    protected function getTableQuery(): Builder
    {
      $query = Invoice::with('status')->orderBy('created_at', 'desc');
        return $query;
    }

    protected function getTableColumns(): array
    {
        return [
            Tables\Columns\TextColumn::make('invoiceName')->label(new HtmlString(nl2br("Invoice \n No")))->sortable(['invoiceNo']),
            Tables\Columns\TextColumn::make('debtorCode')->label(new HtmlString(nl2br("Debtor \n Code")))->sortable(),
            Tables\Columns\TextColumn::make('debtorName')->label(new HtmlString(nl2br("Customer \n Name")))->sortable(),
            Tables\Columns\TextColumn::make('totalQuantity')->label(new HtmlString(nl2br("Total \n Quantity")))->sortable(),
            Tables\Columns\TextColumn::make('totalAmount')->label(new HtmlString(nl2br("Total \n Amount (RM)")))->sortable(),
            Tables\Columns\TextColumn::make('statusID')->sortable()->label('Status')
                ->view('tables.columns.status-id'),
            Tables\Columns\TextColumn::make('date')->sortable(),
        ];
    }

    protected function getTableFilters(): array
    {
        return [
            Filter::make('created_at')
                ->form([
                    Forms\Components\DatePicker::make('created_from'),
                    Forms\Components\DatePicker::make('created_until'),
                ])
                ->query(function (Builder $query, array $data): Builder {
                    return $query
                        ->when(
                            $data['created_from'],
                            fn (Builder $query, $data): Builder => $query->whereDate('date', '>=', $data),
                        )
                        ->when(
                            $data['created_until'],
                            fn (Builder $query, $data): Builder => $query->whereDate('date', '<=', $data),
                        );
                }),

                SelectFilter::make('status')
                ->options([
                    '1' => 'Draft',
                    '2' => 'Submitted',
                ])
                ->attribute('statusID')
        ];
    }

    protected function getTableActions(): array
    {
        $data_id = (fn (Invoice $record) => $record->id);
        $data_name =(fn (Invoice $record) => $record->invoiceNo);
        return [
            Tables\Actions\ActionGroup::make([
                Tables\Actions\EditAction::make()
                    ->visible(fn (Invoice $record) => $record->statusID != '2' &&
                        auth()->user()->can('invoice-edit', $record))
                    ->url(fn (Invoice $record): string => route('admin.invoice.edit', $record->id)),
                // dd($this),

                Tables\Actions\Action::make('Delete')
                ->extraAttributes(fn (Invoice $record) => [
                    'class' => 'delete btn btn-danger-light-danger btn-active-danger',
                    'data-id' => $data_id($record),
                    'data-name' => $data_name($record),
                ])
                ->icon('heroicon-s-trash')
                ->color('danger')
                ->visible(fn (Invoice $record) => auth()->user()->can('invoice-delete', $record)),
            ]),
        ];
    }

    protected function getTableRecordUrlUsing(): ?Closure
    {
        return fn (Invoice $record): string => route('admin.invoice.show', $record->id);
    }

    protected function isTablePaginationEnabled(): bool
    {
        return true;
    }

    protected function getTableRecordsPerPageSelectOptions(): array
    {
        return [5, 10, 25, 50];
    }

    public function isTableSearchable(): bool
    {
        return true;
    }
    protected function applySearchToTableQuery(Builder $query): Builder
    {
        if (filled($searchQuery = $this->getTableSearchQuery())) {
            $query->whereIn('id', Invoice::search($searchQuery)->keys());
        }

        return $query;
    }


    public function render()
    {
        return view('livewire.invoicetable');
    }
}
