<?php

namespace App\Filament\Resources;

use App\Filament\Resources\TelaResource\Pages;
use App\Filament\Resources\TelaResource\RelationManagers;
use App\Models\Tela;
use Filament\Forms;
use Filament\Forms\Form;
use Filament\Resources\Resource;
use Filament\Tables;
use Filament\Tables\Table;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\SoftDeletingScope;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\FileUpload;
use Filament\Forms\Components\TextInput;
use Filament\Forms\Components\DatePicker;
use Filament\Forms\Components\Textarea;
use Filament\Forms\Components\ColorPicker;
use Filament\Forms\Set; // Importa la clase Set

class TelaResource extends Resource
{
    protected static ?string $model = Tela::class;

    protected static ?string $navigationGroup = 'Gestión';
    protected static ?int $navigationSort = 1;
    protected static ?string $navigationIcon = 'heroicon-o-map';

    public static function form(Form $form): Form
    {
        return $form->schema([

            TextInput::make('codigo')->required()->unique(ignoreRecord: true),

            TextInput::make('tipo')
                ->label('Tipo de tela')
                ->required()
                ->helperText('Ej: Algodón, Poliéster, Denim'),



            ColorPicker::make('color')->default('#000000'),

            Select::make('proveedor_id')
                ->options(fn() => \App\Models\Proveedor::where('categoria', 'telas')->pluck('nombre', 'id')->toArray())
                ->searchable()
                ->preload()
                ->required(),

            TextInput::make('metros_comprados')->numeric()->required()->live(onBlur: true)->afterStateUpdated(function ($state, Forms\Set $set, $get) {
                    $valor_total = $get('valor_total');
                    $metros_comprados = $state;

                    // Establecer automáticamente metros disponibles igual a metros comprados al crear/editar
                    $set('metros_disponibles', $metros_comprados);

                    if ($valor_total && $metros_comprados) {
                        $costo_por_metro = $valor_total / $metros_comprados;
                        $set('costo_por_metro', $costo_por_metro);
                    }
                }),

            TextInput::make('valor_total')->numeric()->required()->prefix('$')->step(0.01)->live(onBlur: true)
                ->afterStateUpdated(function ($state, Forms\Set $set, $get) {
                    $metros_comprados = $get('metros_comprados');
                    $valor_total = $state;

                    if ($metros_comprados && $valor_total) {
                        $costo_por_metro = $valor_total / $metros_comprados;
                        $set('costo_por_metro', round($costo_por_metro, 2));
                    }
                }),

            TextInput::make('costo_por_metro')->numeric()->prefix('$')->readOnly()->dehydrated()->default(0)->step(0.01),

            TextInput::make('metros_disponibles')->numeric()->reactive()->disabled()->dehydrated()
                ->default(function ($get) {
                    return $get('metros_comprados');
                })->helperText('Se establece automáticamente igual a "Metros comprados" al crear.'),

            DatePicker::make('fecha_compra')->required()->default(now()),

            Textarea::make('observaciones')->columnSpanFull(),
        ]);
    }

    public static function table(Table $table): Table
    {
        return $table
            ->columns([

                Tables\Columns\TextColumn::make('codigo')->searchable(),
                Tables\Columns\TextColumn::make('tipo')->searchable(),
                Tables\Columns\TextColumn::make('color')->searchable(),
                Tables\Columns\TextColumn::make('proveedor.nombre')->searchable(),
                Tables\Columns\TextColumn::make('metros_comprados')->numeric(),
                Tables\Columns\TextColumn::make('metros_disponibles')->numeric(),
                Tables\Columns\TextColumn::make('valor_total')->money('USD')->sortable(),
                Tables\Columns\TextColumn::make('costo_por_metro')->money('USD')->sortable(),
                Tables\Columns\TextColumn::make('fecha_compra')->date()->sortable(),
            ])
            ->defaultSort('created_at', 'desc')
            ->filters([
                Tables\Filters\SelectFilter::make('tipo')
                    ->options([
                        'algodon' => 'Algodón',
                        'poliester' => 'Poliéster',
                        'denim' => 'Denim',
                    ]),
                Tables\Filters\SelectFilter::make('proveedor_id')
                    ->relationship('proveedor', 'nombre')
                    ->searchable()
                    ->preload(),
            ])
            ->actions([
                Tables\Actions\EditAction::make(),
                Tables\Actions\DeleteAction::make(),
            ])
            ->bulkActions([
                Tables\Actions\BulkActionGroup::make([
                    Tables\Actions\DeleteBulkAction::make(),
                ]),
            ]);
    }

    public static function getRelations(): array
    {
        return [
            //
        ];
    }

    public static function getPages(): array
    {
        return [
            'index' => Pages\ListTelas::route('/'),
            'create' => Pages\CreateTela::route('/create'),
            'edit' => Pages\EditTela::route('/{record}/edit'),
        ];
    }
}
