<?php

declare(strict_types=1);

namespace App\Filament\Resources\RationReports\Pages;

use App\Filament\Resources\RationReports\RationReportResource;
use App\Models\Report;
use App\Models\ReportRationWeekly;
use Filament\Actions\EditAction;
use Filament\Infolists\Components\RepeatableEntry;
use Filament\Infolists\Components\RepeatableEntry\TableColumn;
use Filament\Infolists\Components\TextEntry;
use Filament\Resources\Pages\ViewRecord;
use Filament\Schemas\Components\Section;
use Filament\Schemas\Schema;

class ViewRationReport extends ViewRecord
{
    protected static string $resource = RationReportResource::class;

    protected function getHeaderActions(): array
    {
        return [
            EditAction::make()->label('ویرایش جیره'),
        ];
    }

    public function mount(int|string $record): void
    {
        parent::mount($record);
        $this->getRecord()->load([
            'items.product', 'rationIngredients', 'feedingMeals', 'rationWeekly',
            'project', 'producer',
        ]);
    }

    public function infolist(Schema $schema): Schema
    {
        $record = $this->getRecord();
        $totalCost = $record->rationIngredients->sum(fn ($i) => (float) $i->quantity_per_unit * (float) $i->price_per_unit);
        $totalQty = $record->rationIngredients->sum('quantity_per_unit');
        $headCount = max(1, $record->items->count());
        $costPerHead = $headCount > 0 ? $totalCost / $headCount : 0;

        return $schema
            ->components([
                Section::make('اطلاعات کلی')
                    ->schema([
                        TextEntry::make('date')->label('تاریخ')->date('Y/m/d'),
                        TextEntry::make('project.name')->label('نام پروژه')->placeholder('-'),
                        TextEntry::make('products_list')
                            ->label('نام محصول تولیدی')
                            ->getStateUsing(fn () => $record->items->pluck('product.name')->filter()->join(', ') ?: '-'),
                        TextEntry::make('ration_type')->label('نوع جیره')->placeholder('-'),
                        TextEntry::make('producer.brand_name')->label('نام خدمات‌دهنده')->placeholder('-'),
                        TextEntry::make('workflow_status')
                            ->label('وضعیت')
                            ->badge()
                            ->formatStateUsing(fn (?string $state) => match ($state ?? '') {
                                Report::WORKFLOW_APPROVED => 'تایید',
                                Report::WORKFLOW_REJECTED => 'رد',
                                Report::WORKFLOW_NEEDS_EDIT => 'ویرایش',
                                default => 'انتظار',
                            }),
                        TextEntry::make('admin_reason')->label('دلیل ادمین')->placeholder('-')->columnSpanFull(),
                        TextEntry::make('desc')->label('یادداشت')->placeholder('-')->columnSpanFull(),
                    ])
                    ->columns(2),

                Section::make('آمار کلی')
                    ->schema([
                        TextEntry::make('_total_qty')
                            ->label('مجموع مقدار')
                            ->getStateUsing(fn () => number_format((float) $totalQty, 3)),
                        TextEntry::make('_cost_per_head')
                            ->label('هزینه هر راس')
                            ->getStateUsing(fn () => number_format($costPerHead, 0)),
                        TextEntry::make('_total_cost')
                            ->label('هزینه کل')
                            ->getStateUsing(fn () => number_format($totalCost, 0)),
                    ])
                    ->columns(3)
                    ->visible(fn () => $record->rationIngredients->isNotEmpty()),

                Section::make('ترکیبات جیره')
                    ->schema([
                        RepeatableEntry::make('rationIngredients')
                            ->label('')
                            ->table([
                                TableColumn::make('نام خوراک'),
                                TableColumn::make('واحد'),
                                TableColumn::make('مقدار'),
                                TableColumn::make('قیمت'),
                                TableColumn::make('کل'),
                            ])
                            ->schema([
                                TextEntry::make('name'),
                                TextEntry::make('unit'),
                                TextEntry::make('quantity_per_unit'),
                                TextEntry::make('price_per_unit'),
                                TextEntry::make('total_price'),
                            ]),
                    ])
                    ->visible(fn () => $record->rationIngredients->isNotEmpty()),

                Section::make('برنامه تغذیه روزانه')
                    ->schema([
                        RepeatableEntry::make('feedingMeals')
                            ->label('')
                            ->table([
                                TableColumn::make('ساعت'),
                                TableColumn::make('نام وعده'),
                                TableColumn::make('درصد'),
                            ])
                            ->schema([
                                TextEntry::make('meal_time'),
                                TextEntry::make('name'),
                                TextEntry::make('percent_of_total'),
                            ]),
                    ])
                    ->visible(fn () => $record->feedingMeals->isNotEmpty()),

                Section::make('برنامه هفتگی')
                    ->schema([
                        RepeatableEntry::make('rationWeekly')
                            ->label('')
                            ->table([
                                TableColumn::make('روز'),
                                TableColumn::make('فعال'),
                                TableColumn::make('وضعیت'),
                            ])
                            ->schema([
                                TextEntry::make('day_of_week')
                                    ->formatStateUsing(fn ($state) => ReportRationWeekly::dayNames()[$state] ?? $state),
                                TextEntry::make('is_active')
                                    ->formatStateUsing(fn ($state) => $state ? 'بله' : 'خیر'),
                                TextEntry::make('status')
                                    ->formatStateUsing(fn ($state) => ReportRationWeekly::statusOptions()[$state] ?? $state),
                            ]),
                    ])
                    ->visible(fn () => $record->rationWeekly->isNotEmpty()),

                Section::make('دستورات ویژه و پیوست‌ها')
                    ->schema([
                        TextEntry::make('water_temp')->label('دمای آب (°C)')->placeholder('-'),
                        TextEntry::make('water_per_unit_daily')->label('آب روزانه به ازای واحد (لیتر)')->placeholder('-'),
                        TextEntry::make('wait_between_meals_hours')->label('زمان انتظار بین وعده‌ها (ساعت)')->placeholder('-'),
                        TextEntry::make('mix_type')
                            ->label('نوع مخلوط')
                            ->formatStateUsing(fn (?string $state) => Report::mixTypeOptions()[$state] ?? $state ?? '-'),
                        TextEntry::make('warnings')->label('نکات و هشدارها')->placeholder('-')->columnSpanFull(),
                    ])
                    ->columns(2),
            ]);
    }
}
