<?php

namespace App\Livewire;

use App\Services\TextbookApiService;
use Filament\Tables;
use Filament\Tables\Table;
use Filament\Livewire\Concerns\InteractsWithTables;
use Livewire\Component;
use Illuminate\Database\Eloquent\Model;

class TextbookTable extends Component implements Tables\Contracts\HasTable
{
    use InteractsWithTables;

    public function render()
    {
        return view('livewire.textbook-table');
    }

    public function table(Table $table): Table
    {
        return $table
            ->query(function () {
                // 返回空查询，实际数据通过 getTableRecords 提供
                return \App\Models\Textbook::query()->whereRaw('1=0');
            })
            ->columns([
                Tables\Columns\TextColumn::make('id')
                    ->label('ID')
                    ->sortable(),

                Tables\Columns\TextColumn::make('series.name')
                    ->label('系列')
                    ->searchable(),

                Tables\Columns\TextColumn::make('official_title')
                    ->label('官方书名')
                    ->searchable()
                    ->wrap(),

                Tables\Columns\TextColumn::make('stage')
                    ->label('学段')
                    ->formatStateUsing(function ($state): string {
                        return match ($state) {
                            'primary' => '小学',
                            'junior' => '初中',
                            'senior' => '高中',
                            default => $state,
                        };
                    })
                    ->badge()
                    ->color('info'),

                Tables\Columns\TextColumn::make('grade')
                    ->label('年级')
                    ->formatStateUsing(function ($state): string {
                        return $state ? "{$state}年级" : '-';
                    }),

                Tables\Columns\TextColumn::make('semester')
                    ->label('学期')
                    ->formatStateUsing(function ($state): string {
                        return match ($state) {
                            1 => '上学期',
                            2 => '下学期',
                            default => '-',
                        };
                    })
                    ->badge()
                    ->color('success'),

                Tables\Columns\TextColumn::make('naming_scheme')
                    ->label('体系')
                    ->formatStateUsing(function ($state): string {
                        return match ($state) {
                            'new' => '新体系',
                            'old' => '旧体系',
                            default => $state,
                        };
                    })
                    ->badge(),

                Tables\Columns\TextColumn::make('status')
                    ->label('状态')
                    ->formatStateUsing(function ($state): string {
                        return match ($state) {
                            'draft' => '草稿',
                            'published' => '已发布',
                            'archived' => '已归档',
                            default => $state,
                        };
                    })
                    ->badge()
                    ->color(function ($state): string {
                        return match ($state) {
                            'draft' => 'gray',
                            'published' => 'success',
                            'archived' => 'danger',
                            default => 'gray',
                        };
                    }),

                Tables\Columns\TextColumn::make('created_at')
                    ->label('创建时间')
                    ->dateTime()
                    ->sortable()
                    ->toggleable(isToggledHiddenByDefault: true),

                Tables\Columns\TextColumn::make('updated_at')
                    ->label('更新时间')
                    ->dateTime()
                    ->sortable()
                    ->toggleable(isToggledHiddenByDefault: true),
            ])
            ->filters([
                Tables\Filters\SelectFilter::make('stage')
                    ->label('学段')
                    ->options([
                        'primary' => '小学',
                        'junior' => '初中',
                        'senior' => '高中',
                    ]),

                Tables\Filters\SelectFilter::make('status')
                    ->label('状态')
                    ->options([
                        'draft' => '草稿',
                        'published' => '已发布',
                        'archived' => '已归档',
                    ]),
            ])
            ->actions([
                Tables\Actions\EditAction::make()
                    ->label('编辑'),

                Tables\Actions\Action::make('delete')
                    ->label('删除')
                    ->color('danger')
                    ->icon('heroicon-o-trash')
                    ->requiresConfirmation()
                    ->modalHeading('删除教材')
                    ->modalDescription('确定要删除这个教材吗？此操作无法撤销。')
                    ->action(function (Model $record) {
                        // 在Livewire组件中，模型正确传递
                        \Log::info('Livewire delete triggered', [
                            'record_id' => $record->id,
                            'record_class' => get_class($record)
                        ]);

                        try {
                            $apiService = app(TextbookApiService::class);
                            $deleted = $apiService->deleteTextbook($record->id);

                            \Log::info('Delete API result', [
                                'deleted' => $deleted,
                                'record_id' => $record->id
                            ]);

                            if ($deleted) {
                                \Filament\Notifications\Notification::make()
                                    ->title('成功')
                                    ->body('教材删除成功。')
                                    ->success()
                                    ->send();
                            } else {
                                \Filament\Notifications\Notification::make()
                                    ->title('错误')
                                    ->body('删除失败，请重试。')
                                    ->danger()
                                    ->send();
                            }
                        } catch (\Exception $e) {
                            \Log::error('Delete error', [
                                'error' => $e->getMessage(),
                                'record_id' => $record->id
                            ]);
                            \Filament\Notifications\Notification::make()
                                ->title('错误')
                                ->body('删除失败：' . $e->getMessage())
                                ->danger()
                                ->send();
                        }
                    }),

                Tables\Actions\Action::make('view_catalog')
                    ->label('查看目录')
                    ->icon('heroicon-o-list-bullet')
                    ->url(fn(Model $record): string =>
                        route('filament.admin.resources.textbook-catalogs.index', ['tableFilters[textbook_id][value]' => $record->id])
                    ),
            ])
            ->bulkActions([
                Tables\Actions\BulkActionGroup::make([
                    Tables\Actions\DeleteBulkAction::make()
                        ->label('批量删除'),
                ]),
            ])
            ->defaultSort('sort_order')
            ->paginated([10, 25, 50, 100]);
    }

    public function getTableRecords(): array
    {
        // 从 API 获取数据
        $apiService = app(TextbookApiService::class);
        $result = $apiService->getTextbooks();

        $records = [];
        foreach ($result['data'] ?? [] as $item) {
            $model = new \App\Models\Textbook();
            // 使用 setAttribute 确保属性正确设置
            foreach ($item as $key => $value) {
                $model->setAttribute($key, $value);
            }
            $model->exists = true;
            $model->id = $item['id'];

            // 设置关联
            if (isset($item['series'])) {
                $seriesModel = new \App\Models\TextbookSeries();
                foreach ($item['series'] as $key => $value) {
                    $seriesModel->setAttribute($key, $value);
                }
                $seriesModel->exists = true;
                $model->setRelation('series', $seriesModel);
            }

            $records[] = $model;
        }

        return $records;
    }
}
