<?php

namespace App\Filament\Resources;

use App\Filament\Resources\ProductResource\Pages;
use App\Models\Product;
use Filament\Forms;
use Filament\Forms\Form;
use Filament\Resources\Resource;
use Filament\Tables;
use Filament\Tables\Table;
use pxlrbt\FilamentExcel\Actions\Tables\ExportAction;
use pxlrbt\FilamentExcel\Actions\Tables\ExportBulkAction;
use pxlrbt\FilamentExcel\Exports\ExcelExport;

class ProductResource extends Resource
{
    protected static ?string $model = Product::class;

    protected static ?string $navigationIcon = 'heroicon-o-cube';
    protected static ?string $navigationGroup = 'فاکتورها';
    protected static ?string $navigationLabel = 'کالا و خدمات';
    protected static ?string $modelLabel = 'کالا/خدمت';
    protected static ?string $pluralModelLabel = 'کالا و خدمات';
    protected static ?int $navigationSort = 2;

    public static function form(Form $form): Form
    {
        return $form->schema([
            Forms\Components\TextInput::make('name')->label('نام')->required()->maxLength(255),
            Forms\Components\TextInput::make('unit')->label('واحد')->placeholder('عدد / ساعت / کیلو'),
            Forms\Components\TextInput::make('default_price')->label('قیمت پیش‌فرض')->numeric()->default(0)->required(),
            Forms\Components\Toggle::make('is_service')->label('خدمت است؟'),
            Forms\Components\Toggle::make('is_active')->label('فعال')->default(true),
            Forms\Components\Textarea::make('description')->label('توضیحات')->columnSpanFull(),
        ])->columns(2);
    }

    public static function table(Table $table): Table
    {
        return $table
            ->columns([
                Tables\Columns\TextColumn::make('name')->label('نام')->searchable()->sortable(),
                Tables\Columns\TextColumn::make('unit')->label('واحد'),
                Tables\Columns\TextColumn::make('default_price')->label('قیمت پیش‌فرض')->money('IRR')->sortable(),
                Tables\Columns\IconColumn::make('is_service')->label('خدمت')->boolean(),
                Tables\Columns\IconColumn::make('is_active')->label('فعال')->boolean(),
            ])
            ->filters([
                Tables\Filters\TernaryFilter::make('is_active')->label('فعال'),
                Tables\Filters\TernaryFilter::make('is_service')->label('خدمت'),
            ])
            ->actions([Tables\Actions\EditAction::make()])
            ->bulkActions([
                Tables\Actions\BulkActionGroup::make([
                    Tables\Actions\DeleteBulkAction::make(),
                    ExportBulkAction::make()->exports([ExcelExport::make()->fromTable()->withFilename('products')]),
                ]),
            ])
            ->headerActions([
                ExportAction::make()->label('خروجی اکسل')->exports([ExcelExport::make()->fromTable()]),
            ]);
    }

    public static function getPages(): array
    {
        return [
            'index' => Pages\ManageProducts::route('/'),
        ];
    }
}
