<?php

namespace App\Filament\Resources\TextbookResource\Pages;

use App\Filament\Resources\TextbookResource;
use App\Services\TextbookApiService;
use Filament\Actions;
use Filament\Resources\Pages\ListRecords;
use Illuminate\Contracts\Pagination\Paginator;
use Illuminate\Pagination\LengthAwarePaginator;

class ManageTextbooks extends ListRecords
{
    protected static string $resource = TextbookResource::class;

    protected function getHeaderActions(): array
    {
        return [
            Actions\CreateAction::make()
                ->label('新建教材'),
        ];
    }

    protected function paginateTableQuery(\Illuminate\Database\Eloquent\builder $query): Paginator
    {
        return $this->getTableRecords();
    }

    public function getTableRecords(): Paginator
    {
        $apiService = app(TextbookApiService::class);
        $page = request()->get('page', 1);
        $perPage = $this->getTableRecordsPerPage();
        $filters = request()->input('tableFilters', []);

        $params = [
            'page' => $page,
            'per_page' => $perPage,
            'stage' => $filters['stage']['value'] ?? null,
            'grade' => $filters['grade']['value'] ?? null,
            'semester' => $filters['semester']['value'] ?? null,
            'naming_scheme' => $filters['naming_scheme']['value'] ?? null,
            'status' => $filters['status']['value'] ?? null,
            'keyword' => $filters['keyword']['value'] ?? null,
        ];

        $params = array_filter($params, fn ($value) => $value !== null && $value !== '');

        \Log::info('ManageTextbooks::getTableRecords called', [
            'page' => $page,
            'perPage' => $perPage
        ]);

        $result = $apiService->getTextbooks($params);

        \Log::info('API result', [
            'total' => $result['meta']['total'] ?? 0,
            'count' => count($result['data'] ?? [])
        ]);

        $records = collect($result['data'] ?? [])->map(function ($item) {
            $model = new \App\Models\Textbook();
            // 直接设置属性
            foreach ($item as $key => $value) {
                $model->setAttribute($key, $value);
            }
            $model->exists = true;
            // 确保ID被正确设置
            if (isset($item['id'])) {
                $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);
            }
            return $model;
        });

        return new LengthAwarePaginator(
            $records,
            $result['meta']['total'] ?? 0,
            $perPage,
            $page,
            ['path' => request()->url()]
        );
    }
}
