<?php

namespace App\Filament\Resources;

use App\Filament\Exports\StickerDetailExporter;
use App\Filament\Imports\StickerDetailImporter;
use App\Filament\Resources\StickerDetailResource\Pages;
use App\Filament\Resources\StickerDetailResource\RelationManagers;
use App\Models\ItemCharacteristic;
use App\Models\StickerDetail;
use App\Models\StickerStructureDetail;
use Filament\Tables\Actions\ExportAction;
use Filament\Tables\Actions\ImportAction;
use Filament\Facades\Filament;
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 Illuminate\Support\Facades\Schema;
use Closure;

class StickerDetailResource extends Resource
{
    protected static ?string $model = StickerDetail::class;

    protected static ?string $navigationIcon = 'heroicon-o-rectangle-stack';

    protected static ?string $navigationGroup = 'Customized Sticker Printing';

    public static function form(Form $form): Form
    {
        return $form
            ->schema([
                Forms\Components\Select::make('sticker_structure_detail_id')
                    ->label('Sticker ID')
                    ->reactive()
                    ->relationship('stickerStructureDetail', 'sticker_id')
                     ->options(function (callable $get) {
                        return StickerStructureDetail::pluck('sticker_id', 'id');
                    })
                    ->required()
                    ->afterStateUpdated(function (callable $get, callable $set) {
                        // if ($get('element_id')) {
                        //     return;
                        // }

                        $structureId = $get('sticker_structure_detail_id');
                        $set('design_element_type', null);
                        $set('element_id', null);

                        if (!$structureId) {
                            $set('element_id', null);
                            return;
                        }

                        $maxId = StickerDetail::where('sticker_structure_detail_id', $structureId)
                            ->max('element_id');

                        $nextId = $maxId ? ((int) $maxId + 1) : 1;

                        $formattedId = str_pad($nextId, 3, '0', STR_PAD_LEFT);

                        $set('element_id', $formattedId);
                    }),
                Forms\Components\Select::make('design_element_type')
                    ->label('Design Element Type')
                    ->reactive()
                    ->options([
                        'Text' => 'Text',
                        'Shape' => 'Shape',
                        'Image' => 'Image',
                        'QR' => 'QR',
                    ]),
                Forms\Components\TextInput::make('element_id')
                    ->label('Element ID')
                    ->readOnly()
                    ->reactive(),
                Forms\Components\Select::make('element_type')
                    ->label('Element Type')
                    ->options([
                        'Static' => 'Static',
                        'Dynamic' => 'Dynamic',
                    ]),
                Forms\Components\Select::make('characteristics_type')
                    ->label('Characteristics')
                    ->reactive()
                    ->options(
            collect(Schema::getColumnListing('item_characteristics'))
                        ->reject(fn ($column) => in_array($column, [
                            'id',
                            'plant_id',
                            'item_id',
                            'class',
                            'zz1_cn_bill_ord',
                            'created_at',
                            'updated_at',
                            'deleted_at',
                            'created_by',
                            'updated_by',
                        ]))
                        ->mapWithKeys(fn ($column) => [
                            $column => ucfirst(str_replace('_', ' ', $column))
                        ])
                        ->toArray()
                    ),
                Forms\Components\TextInput::make('string_value')
                    ->label('String Value')
                    ->reactive()
                    ->visible(fn ($get) => $get('design_element_type') == 'Text'),
                Forms\Components\TextInput::make('string_font')
                    ->label('String Font')
                    ->reactive()
                    ->visible(fn ($get) => $get('design_element_type') == 'Text'),
                Forms\Components\TextInput::make('string_size')
                    ->label('String Size')
                    ->reactive()
                    ->visible(fn ($get) => $get('design_element_type') == 'Text'),
                Forms\Components\Select::make('element_colour')
                    ->label('Element Colour')
                    ->options([
                        '' => 'Default (Black)',
                        '#000000' => 'Black',
                        '#FFFFFF' => 'White',
                        '#FF0000' => 'Red',
                        '#00FF00' => 'Lime',
                        '#0000FF' => 'Blue',
                        '#FFFF00' => 'Yellow',
                        '#00FFFF' => 'Cyan',
                        '#FF00FF' => 'Magenta',
                        '#800000' => 'Maroon',
                        '#808000' => 'Olive',
                        '#008000' => 'Green',
                        '#800080' => 'Purple',
                        '#008080' => 'Teal',
                        '#808080' => 'Gray',
                        '#C0C0C0' => 'Silver',
                        '#FFA500' => 'Orange',
                        '#FFC0CB' => 'Pink',
                        '#A52A2A' => 'Brown',
                        '#87CEEB' => 'Sky Blue',
                    ])
                    ->nullable()
                    ->reactive(),
                Forms\Components\Select::make('string_align')
                    ->label('String Align')
                    ->options([
                        'Left' => 'Left',
                        'Right' => 'Right',
                        'Center' => 'Center',
                    ])
                    ->reactive()
                    ->visible(fn ($get) => $get('design_element_type') == 'Text'),
                Forms\Components\TextInput::make('string_x_value')
                    ->label('String X Value')
                    ->reactive()
                    ->visible(fn ($get) => $get('design_element_type') == 'Text'),
                Forms\Components\TextInput::make('string_y_value')
                    ->label('String Y Value')
                    ->reactive()
                    ->visible(fn ($get) => $get('design_element_type') == 'Text'),
                Forms\Components\Select::make('shape_name')
                    ->label('Shape Name')
                    ->reactive()
                    ->options([
                        'Line' => 'Line',
                        'Rectangle' => 'Rectangle',
                        'CurvedRectangle' => 'CurvedRectangle',
                    ])
                    ->visible(fn ($get) => $get('design_element_type') == 'Shape'),
                Forms\Components\TextInput::make('shape_pen_size')
                    ->label('Shape Pen Size')
                    ->reactive()
                    ->visible(fn ($get) => $get('design_element_type') == 'Shape'),
                Forms\Components\TextInput::make('curve_radius')
                    ->label('Curve Radius')
                    ->reactive()
                    ->visible(fn ($get) => $get('shape_name') == 'CurvedRectangle'),
                Forms\Components\TextInput::make('shape_x1_value')
                    ->label('Shape X1 Value')
                    ->reactive()
                    ->visible(fn ($get) => $get('design_element_type') == 'Shape'),
                Forms\Components\TextInput::make('shape_y1_value')
                    ->label('Shape Y1 Value')
                    ->reactive()
                    ->visible(fn ($get) => $get('design_element_type') == 'Shape'),
                Forms\Components\TextInput::make('shape_x2_value')
                    ->label('Shape X2 Value')
                    ->reactive()
                    ->visible(fn ($get) => $get('design_element_type') == 'Shape'),
                Forms\Components\TextInput::make('shape_y2_value')
                    ->label('Shape Y2 Value')
                    ->reactive()
                    ->visible(fn ($get) => $get('design_element_type') == 'Shape'),
                // Forms\Components\FileUpload::make('image_path')
                //     ->label('Image')
                //     ->image()
                //     ->directory('sticker-images')
                //     ->visibility('public')
                //     ->preserveFilenames(false)
                //     ->required(false)
                //     ->reactive()
                //     ->visible(fn ($get) => $get('design_element_type') == 'Image'),
                // Forms\Components\TextInput::make('image_type')
                //     ->label('Image Type')
                //     ->reactive()
                //     ->visible(fn ($get) => $get('design_element_type') == 'Image'),
                Forms\Components\TextInput::make('image_x')
                    ->label('Image X')
                    ->reactive()
                    ->visible(fn ($get) => $get('design_element_type') == 'Image'),
                Forms\Components\TextInput::make('image_y')
                    ->label('Image Y')
                    ->reactive()
                    ->visible(fn ($get) => $get('design_element_type') == 'Image'),
                Forms\Components\TextInput::make('image_width')
                    ->label('Image Width')
                    ->reactive()
                    ->visible(fn ($get) => $get('design_element_type') == 'Image'),
                Forms\Components\TextInput::make('image_height')
                    ->label('Image Height')
                    ->reactive()
                    ->visible(fn ($get) => $get('design_element_type') == 'Image'),
                Forms\Components\TextInput::make('qr_value')
                    ->label('QR Value')
                    ->reactive()
                    ->visible(fn ($get) => $get('design_element_type') == 'QR'),
                Forms\Components\TextInput::make('qr_align')
                    ->label('QR Align')
                    ->reactive()
                    ->visible(fn ($get) => $get('design_element_type') == 'QR'),
                Forms\Components\TextInput::make('qr_size')
                    ->label('QR Size')
                    ->reactive()
                    ->visible(fn ($get) => $get('design_element_type') == 'QR'),
                Forms\Components\TextInput::make('qr_x_value')
                    ->label('QR X Value')
                    ->reactive()
                    ->visible(fn ($get) => $get('design_element_type') == 'QR'),
                Forms\Components\TextInput::make('qr_y_value')
                    ->label('QR Y Value')
                    ->reactive()
                    ->visible(fn ($get) => $get('design_element_type') == 'QR'),
                Forms\Components\Hidden::make('created_by')
                    ->label('created_by')
                    ->default(Filament::auth()->user()?->name),
                Forms\Components\Hidden::make('updated_by')
                    ->label('updated_by')
                    ->default(Filament::auth()->user()?->name),
            ]);
    }

    public static function table(Table $table): Table
    {
        return $table
            ->columns([
                Tables\Columns\TextColumn::make('No.')
                    ->label('No.')
                    ->getStateUsing(function ($record, $livewire, $column, $rowLoop) {
                        $paginator = $livewire->getTableRecords();
                        $perPage = method_exists($paginator, 'perPage') ? $paginator->perPage() : 10;
                        $currentPage = method_exists($paginator, 'currentPage') ? $paginator->currentPage() : 1;

                        return ($currentPage - 1) * $perPage + $rowLoop->iteration;
                    }),
                Tables\Columns\TextColumn::make('stickerStructureDetail.sticker_id')
                    ->label('Sticker ID')
                    ->sortable()
                    ->alignCenter(),
                Tables\Columns\TextColumn::make('design_element_type')
                    ->label('Design Element Type')
                    ->alignCenter(),
                Tables\Columns\TextColumn::make('element_id')
                    ->label('Element ID')
                    ->alignCenter(),
                Tables\Columns\TextColumn::make('element_type')
                    ->label('Element Type')
                    ->alignCenter(),
                Tables\Columns\TextColumn::make('characteristics_type')
                    ->label('Characteristics Type')
                    ->alignCenter(),
                Tables\Columns\TextColumn::make('string_value')
                    ->label('String Value')
                    ->alignCenter(),
                Tables\Columns\TextColumn::make('string_font')
                    ->label('String Font')
                    ->alignCenter(),
                Tables\Columns\TextColumn::make('string_size')
                    ->label('String Size')
                    ->alignCenter(),
                // Tables\Columns\TextColumn::make('element_colour')
                //     ->label('Element Colour')
                //     ->alignCenter(),
                Tables\Columns\TextColumn::make('string_align')
                    ->label('String Align')
                    ->alignCenter(),
                Tables\Columns\TextColumn::make('string_x_value')
                    ->label('String X Value')
                    ->alignCenter(),
                Tables\Columns\TextColumn::make('string_y_value')
                    ->label('String Y Value')
                    ->alignCenter(),
                Tables\Columns\TextColumn::make('shape_name')
                    ->label('Shape Name')
                    ->alignCenter(),
                Tables\Columns\TextColumn::make('shape_pen_size')
                    ->label('Shape Pen Size')
                    ->alignCenter(),
                Tables\Columns\TextColumn::make('curve_radius')
                    ->label('Curve Radius'),
                Tables\Columns\TextColumn::make('shape_x1_value')
                    ->label('Shape X1 Value')
                    ->alignCenter(),
                Tables\Columns\TextColumn::make('shape_y1_value')
                    ->label('Shape Y1 Value')
                    ->alignCenter(),
                Tables\Columns\TextColumn::make('shape_x2_value')
                    ->label('Shape X2 Value')
                    ->alignCenter(),
                Tables\Columns\TextColumn::make('shape_y2_value')
                    ->label('Shape Y2 Value')
                    ->alignCenter(),
                Tables\Columns\TextColumn::make('image_x')
                    ->label('Image X')
                    ->alignCenter(),
                Tables\Columns\TextColumn::make('image_y')
                    ->label('Image Y')
                    ->alignCenter(),
                Tables\Columns\TextColumn::make('image_width')
                    ->label('Image Width')
                    ->alignCenter(),
                Tables\Columns\TextColumn::make('image_height')
                    ->label('Image Height')
                    ->alignCenter(),
                Tables\Columns\TextColumn::make('qr_value')
                    ->label('QR Value')
                    ->alignCenter(),
                Tables\Columns\TextColumn::make('qr_align')
                    ->label('QR Align')
                    ->alignCenter(),
                Tables\Columns\TextColumn::make('qr_size')
                    ->label('QR Size')
                    ->alignCenter(),
                Tables\Columns\TextColumn::make('qr_x_value')
                    ->label('QR X Value')
                    ->alignCenter(),
                Tables\Columns\TextColumn::make('qr_y_value')
                    ->label('QR Y Value')
                    ->alignCenter(),
                Tables\Columns\TextColumn::make('created_at')
                    ->label('Created At')
                    ->alignCenter()
                    ->dateTime()
                    ->sortable()
                    ->toggleable(isToggledHiddenByDefault: true),
                Tables\Columns\TextColumn::make('created_by')
                    ->label('Created By')
                    ->alignCenter(),
                Tables\Columns\TextColumn::make('updated_at')
                    ->label('Updated At')
                    ->alignCenter()
                    ->dateTime()
                    ->sortable()
                    ->toggleable(isToggledHiddenByDefault: true),
                Tables\Columns\TextColumn::make('deleted_at')
                    ->dateTime()
                    ->sortable()
                    ->toggleable(isToggledHiddenByDefault: true),
            ])
            ->filters([
                Tables\Filters\TrashedFilter::make(),
            ])
            ->actions([
                Tables\Actions\ViewAction::make(),
                Tables\Actions\EditAction::make(),
            ])
            ->bulkActions([
                Tables\Actions\BulkActionGroup::make([
                    Tables\Actions\DeleteBulkAction::make(),
                    Tables\Actions\ForceDeleteBulkAction::make(),
                    Tables\Actions\RestoreBulkAction::make(),
                ]),
            ])
            ->headerActions([
                ImportAction::make()
                    ->label('Import Sticker Details')
                    ->color('warning')
                    ->importer(StickerDetailImporter::class)
                    ->visible(function() {
                        return Filament::auth()->user()->can('view import sticker details');
                    }),
                ExportAction::make()
                    ->label('Export Sticker Details')
                    ->color('warning')
                    ->exporter(StickerDetailExporter::class)
                    ->visible(function() {
                        return Filament::auth()->user()->can('view export sticker details');
                    }),
            ]);
    }

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

    public static function getPages(): array
    {
        return [
            'index' => Pages\ListStickerDetails::route('/'),
            'create' => Pages\CreateStickerDetail::route('/create'),
            'view' => Pages\ViewStickerDetail::route('/{record}'),
            'edit' => Pages\EditStickerDetail::route('/{record}/edit'),
        ];
    }

    public static function getEloquentQuery(): Builder
    {
        return parent::getEloquentQuery()
            ->withoutGlobalScopes([
                SoftDeletingScope::class,
            ]);
    }
}
