<?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 Illuminate\Support\Str;

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

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

    protected static ?string $navigationGroup = 'Product Management';

    protected static ?int $navigationSort = 2;

    public static function form(Form $form): Form
    {
        return $form
            ->schema([
                Forms\Components\Section::make('Basic Information')
                    ->schema([
                        Forms\Components\Select::make('category_id')
                            ->relationship('category', 'name')
                            ->required()
                            ->searchable()
                            ->preload(),

                        Forms\Components\TextInput::make('name')
                            ->required()
                            ->maxLength(255)
                            ->live(onBlur: true)
                            ->afterStateUpdated(fn (string $operation, $state, Forms\Set $set) => 
                                $operation === 'create' ? $set('slug', Str::slug($state)) : null
                            ),

                        Forms\Components\TextInput::make('slug')
                            ->required()
                            ->maxLength(255)
                            ->unique(ignoreRecord: true)
                            ->readOnly(),

                        Forms\Components\TextInput::make('sku')
                            ->label('SKU')
                            ->maxLength(255)
                            ->unique(ignoreRecord: true),

                        Forms\Components\RichEditor::make('description')
                            ->columnSpanFull(),

                        Forms\Components\Textarea::make('features')
                            ->rows(3)
                            ->columnSpanFull(),
                    ])
                    ->columns(2),

                Forms\Components\Section::make('Pricing & Inventory')
                    ->schema([
                        Forms\Components\TextInput::make('price')
                            ->numeric()
                            ->prefix('GHS')
                            ->maxValue(999999.99),

                        Forms\Components\TextInput::make('stock')
                            ->numeric()
                            ->default(0)
                            ->required(),
                    ])
                    ->columns(2),

                Forms\Components\Section::make('Specifications')
                    ->schema([
                        Forms\Components\KeyValue::make('specifications')
                            ->keyLabel('Property')
                            ->valueLabel('Value')
                            ->reorderable(),

                        Forms\Components\TagsInput::make('sizes')
                            ->placeholder('Add sizes'),

                        Forms\Components\TagsInput::make('colors')
                            ->placeholder('Add colors'),
                    ])
                    ->columns(1),

                Forms\Components\Section::make('Media')
                    ->schema([
                        Forms\Components\FileUpload::make('featured_image')
                            ->label('Featured Image')
                            ->image()
                            ->disk('public')
                            ->visibility('public')
                            ->directory('products')
                            ->imageEditor()
                            ->required()
                            ->columnSpanFull(),

                        Forms\Components\TextInput::make('gallery_1_title')
                            ->label('Gallery 1 Title')
                            ->default('Available Colors')
                            ->maxLength(255)
                            ->columnSpanFull(),

                        Forms\Components\Repeater::make('gallery')
                            ->label('Gallery 1 - Images with Captions')
                            ->schema([
                                Forms\Components\FileUpload::make('image')
                                    ->label('Image')
                                    ->image()
                                    ->disk('public')
                                    ->visibility('public')
                                    ->directory('products/gallery')
                                    ->imageEditor()
                                    ->required()
                                    ->columnSpan(2),

                                Forms\Components\TextInput::make('caption')
                                    ->label('Caption (e.g., K100 SM EDEL WHITE)')
                                    ->maxLength(255)
                                    ->columnSpan(2),
                            ])
                            ->columns(2)
                            ->reorderable()
                            ->collapsible()
                            ->itemLabel(fn (array $state): ?string => $state['caption'] ?? 'Image ' . (isset($state['image']) ? '✓' : ''))
                            ->defaultItems(0)
                            ->maxItems(40)
                            ->columnSpanFull()
                            ->helperText('Main product gallery with captions'),

                        Forms\Components\TextInput::make('gallery_2_title')
                            ->label('Gallery 2 Title')
                            ->default('Texture Variations')
                            ->maxLength(255)
                            ->columnSpanFull(),

                        Forms\Components\Repeater::make('gallery_2')
                            ->label('Gallery 2 - Images with Captions')
                            ->schema([
                                Forms\Components\FileUpload::make('image')
                                    ->label('Image')
                                    ->image()
                                    ->disk('public')
                                    ->visibility('public')
                                    ->directory('products/gallery2')
                                    ->imageEditor()
                                    ->required()
                                    ->columnSpan(2),

                                Forms\Components\TextInput::make('caption')
                                    ->label('Caption')
                                    ->maxLength(255)
                                    ->columnSpan(2),
                            ])
                            ->columns(2)
                            ->reorderable()
                            ->collapsible()
                            ->itemLabel(fn (array $state): ?string => $state['caption'] ?? 'Image ' . (isset($state['image']) ? '✓' : ''))
                            ->defaultItems(0)
                            ->maxItems(40)
                            ->columnSpanFull()
                            ->helperText('Secondary gallery (optional) - e.g., textures, finishes, etc.'),

                        Forms\Components\TextInput::make('youtube_video_url')
                            ->label('YouTube Video URL')
                            ->url()
                            ->placeholder('https://www.youtube.com/watch?v=...')
                            ->helperText('Paste the full YouTube video URL. It will be embedded on the product page.')
                            ->columnSpanFull(),
                    ]),

                Forms\Components\Section::make('Settings')
                    ->schema([
                        Forms\Components\TextInput::make('order')
                            ->numeric()
                            ->default(0)
                            ->required(),

                        Forms\Components\Toggle::make('is_featured')
                            ->default(false),

                        Forms\Components\Toggle::make('is_active')
                            ->default(true)
                            ->required(),
                    ])
                    ->columns(3),
            ]);
    }

    public static function table(Table $table): Table
    {
        return $table
            ->columns([
                Tables\Columns\ImageColumn::make('featured_image')
                    ->label('Image')
                    ->disk('public')
                    ->circular(),

                Tables\Columns\TextColumn::make('name')
                    ->searchable()
                    ->sortable()
                    ->wrap(),

                Tables\Columns\TextColumn::make('category.name')
                    ->sortable()
                    ->searchable()
                    ->badge()
                    ->color('primary'),

                Tables\Columns\TextColumn::make('sku')
                    ->label('SKU')
                    ->searchable()
                    ->toggleable()
                    ->copyable(),

                Tables\Columns\TextColumn::make('price')
                    ->money('GHS')
                    ->sortable(),

                Tables\Columns\TextColumn::make('stock')
                    ->numeric()
                    ->sortable()
                    ->badge()
                    ->color(fn ($state) => $state > 0 ? 'success' : 'danger'),

                Tables\Columns\ImageColumn::make('gallery_preview')
                    ->label('Gallery')
                    ->disk('public')
                    ->circular()
                    ->stacked()
                    ->limit(3)
                    ->getStateUsing(function ($record) {
                        if (!is_array($record->gallery)) return [];
                        
                        return collect($record->gallery)->map(function ($item) {
                            if (is_array($item) && isset($item['image'])) {
                                return $item['image'];
                            }
                            if (is_string($item)) {
                                return $item;
                            }
                            return null;
                        })->filter()->take(3)->toArray();
                    })
                    ->toggleable(),

                Tables\Columns\TextColumn::make('gallery_count')
                    ->label('Images')
                    ->getStateUsing(fn ($record) => is_array($record->gallery) ? count($record->gallery) : 0)
                    ->badge()
                    ->color('info')
                    ->toggleable(),

                Tables\Columns\IconColumn::make('is_featured')
                    ->boolean()
                    ->sortable()
                    ->toggleable(),

                Tables\Columns\IconColumn::make('is_active')
                    ->boolean()
                    ->sortable(),

                Tables\Columns\TextColumn::make('created_at')
                    ->dateTime()
                    ->sortable()
                    ->toggleable(isToggledHiddenByDefault: true),
            ])
            ->filters([
                Tables\Filters\SelectFilter::make('category')
                    ->relationship('category', 'name')
                    ->preload(),

                Tables\Filters\TernaryFilter::make('is_featured')
                    ->label('Featured')
                    ->placeholder('All products')
                    ->trueLabel('Featured only')
                    ->falseLabel('Not featured'),

                Tables\Filters\TernaryFilter::make('is_active')
                    ->label('Active')
                    ->placeholder('All products')
                    ->trueLabel('Active only')
                    ->falseLabel('Inactive only'),

                Tables\Filters\Filter::make('out_of_stock')
                    ->query(fn ($query) => $query->where('stock', 0))
                    ->label('Out of Stock'),
            ])
            ->actions([
                Tables\Actions\ViewAction::make(),
                Tables\Actions\EditAction::make(),
                Tables\Actions\DeleteAction::make(),
            ])
            ->bulkActions([
                Tables\Actions\BulkActionGroup::make([
                    Tables\Actions\DeleteBulkAction::make(),
                ]),
            ])
            ->defaultSort('created_at', 'desc');
    }

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