<?php

namespace App\Filament\Reports;

use App\Models\Land;
use EightyNine\Reports\Components\Text;
use EightyNine\Reports\Report;
use EightyNine\Reports\Components\Body;
use EightyNine\Reports\Components\Header;
use Filament\Forms\Form;
use Filament\Forms\Components\DatePicker;
use Filament\Forms\Components\Select;
use Illuminate\Support\Carbon;
use App\Models\Setting;

class AllLandsReport extends Report
{
    protected static ?string $navigationIcon = 'heroicon-o-cube';

    public static function getNavigationLabel(): string
    {
        return "تقرير جميع الأراضي";
    }

    public function getTitle(): string
    {
        return "تقرير جميع الأراضي";
    }

    protected static ?int $navigationSort = 4;

    protected static ?string $navigationGroup = 'التقارير';

    public function header(Header $header): Header
    {
        return $header
            ->schema([
                Header\Layout\HeaderRow::make()
                    ->schema([
                        Text::make("تقرير جميع الأراضي")
                            ->fontXl()
                            ->fontBold()
                            ->primary(),
                        Text::make("عرض تفاصيل مجمعة لجميع الأراضي مع إمكانية الفلترة حسب الأرض المحددة.")
                            ->fontSm()
                            ->secondary(),
                    ])
                    ->alignBottom(),
            ]);
    }

    function getCarbonInstancesFromDateString(?string $dateString): array
    {
        if (!$dateString) {
            return [null, null];
        }

        $dates = explode(" - ", $dateString);

        try {
            $from = Carbon::createFromFormat("d/m/Y", $dates[0]);
            $to = Carbon::createFromFormat("d/m/Y", $dates[1]);
        } catch (\Exception $e) {
            return [null, null];
        }

        return [$from, $to];
    }

    public function body(Body $body): Body
    {
        return $body
            ->schema([
                Body\Layout\BodyColumn::make()
                    ->schema([
                        Body\Table::make()
                            ->columns([
                                Body\TextColumn::make('land_name')->label("اسم الأرض"),
                                Body\TextColumn::make('total_equip_cost')->label("إجمالي تكلفة المعدات")->formatStateUsing(fn ($state) => number_format($state, 0,'.', ',')),
                                Body\TextColumn::make('total_expenses')->label("إجمالي المصروفات")->formatStateUsing(fn ($state) => number_format($state, 0,'.', ',')),
                                Body\TextColumn::make('total_attendance_cost')->label("إجمالي تكلفة العمالة")->formatStateUsing(fn ($state) => number_format($state, 0,'.', ',')),
                                Body\TextColumn::make('total_sales')->label("إجمالي الأصناف")->formatStateUsing(fn ($state) => number_format($state, 0,'.', ',')),
                                Body\TextColumn::make('grand_total')->label("الإجمالي الكلي")->formatStateUsing(fn ($state) => number_format($state, 0,'.', ',')),
                                Body\TextColumn::make('total_mony_import')->label("إجمالي الوارد")->formatStateUsing(fn ($state) => number_format($state, 0,'.', ',')),
                                Body\TextColumn::make('final')->label("أرباح الأرض")->formatStateUsing(fn ($state) => number_format($state, 0,'.', ',')),
                            ])
                            ->data(
                                function (?array $filters) {
                                    if (empty($filters['date']) && !empty($filters['from_date']) && !empty($filters['to_date'])) {
                                        $filters['date'] = Carbon::parse($filters['from_date'])->format('d/m/Y') . ' - ' . Carbon::parse($filters['to_date'])->format('d/m/Y');
                                    }

                                    [$startDate, $endDate] = $this->getCarbonInstancesFromDateString($filters['date'] ?? null);

                                    if (!$startDate || !$endDate) {
                                        return collect([]);
                                    }

                                    // Get selected lands
                                    $landsQuery = Land::query();

                                    if (!empty($filters['land_id']) && is_array($filters['land_id'])) {
                                        $landsQuery->whereIn('id', $filters['land_id']);
                                    }

                                    $lands = $landsQuery->with([
                                        'equipWorks' => function ($query) use ($startDate, $endDate) {
                                            $query->whereBetween('date', [$startDate, $endDate]);
                                        },
                                        'monyExports' => function ($query) use ($startDate, $endDate) {
                                            $query->whereBetween('date', [$startDate, $endDate]);
                                        },
                                        'attendances' => function ($query) use ($startDate, $endDate) {
                                            $query->whereBetween('date', [$startDate, $endDate]);
                                        },
                                        'sales.products',
                                        'monyImports',
                                    ])->get();

                                    $totals = [
                                        'total_equip_cost' => 0,
                                        'total_expenses' => 0,
                                        'total_attendance_cost' => 0,
                                        'total_sales' => 0,
                                        'total_mony_import' => 0,
                                        'grand_total' => 0,
                                        'final' => 0,
                                    ];

                                    $data = $lands->map(function ($land) use (&$totals) {
                                        $totalEquipCost = $land->equipWorks->sum(fn ($work) => ($work->hours_count * $work->hour_price) / max($work->lands->count(), 1));
                                        $totalExpenses = $land->monyExports->sum(fn ($export) => $export->value / max($export->lands->count(), 1));
                                        $totalAttendanceCost = $land->attendances->sum(fn ($attendance) => ($attendance->employees->count() * (Setting::latest()->first()->daily_price ?? 0)) / max($attendance->lands->count(), 1));
                                        $totalSales = $land->sales->sum(fn ($sale) => $sale->products->sum('pivot.total') / max($sale->lands->count(), 1));
                                        $totalMonyImport = $land->monyImports->sum(fn ($import) => $import->value / max($import->lands->count(), 1));

                                        $grandTotal = $totalEquipCost + $totalExpenses + $totalAttendanceCost + $totalSales;
                                        $final = $totalMonyImport - $grandTotal;

                                        // Accumulate Totals
                                        $totals['total_equip_cost'] += $totalEquipCost;
                                        $totals['total_expenses'] += $totalExpenses;
                                        $totals['total_attendance_cost'] += $totalAttendanceCost;
                                        $totals['total_sales'] += $totalSales;
                                        $totals['total_mony_import'] += $totalMonyImport;
                                        $totals['grand_total'] += $grandTotal;
                                        $totals['final'] += $final;

                                        return [
                                            'land_name' => $land->name,
                                            'total_equip_cost' => $totalEquipCost,
                                            'total_expenses' => $totalExpenses,
                                            'total_attendance_cost' => $totalAttendanceCost,
                                            'total_sales' => $totalSales,
                                            'total_mony_import' => $totalMonyImport,
                                            'grand_total' => $grandTotal,
                                            'final' => $final,
                                        ];
                                    });

                                    // Add Totals Row
                                    $data->push([
                                        'land_name' => 'الإجمالي',
                                        'total_equip_cost' => $totals['total_equip_cost'],
                                        'total_expenses' => $totals['total_expenses'],
                                        'total_attendance_cost' => $totals['total_attendance_cost'],
                                        'total_sales' => $totals['total_sales'],
                                        'total_mony_import' => $totals['total_mony_import'],
                                        'grand_total' => $totals['grand_total'],
                                        'final' => $totals['final'],
                                    ]);

                                    return $data;
                                }
                            ),
                    ]),
            ]);
    }

    public function filterForm(Form $form): Form
    {
        return $form
            ->schema([
                DatePicker::make('from_date')->label('من تاريخ')->native(false)->required(),
                DatePicker::make('to_date')->label('إلى تاريخ')->native(false)->required(),
                Select::make('land_id')->label('الأراضي')->options(Land::pluck('name', 'id')->toArray())->placeholder('حدد الأرض (اختياري)')->multiple()->searchable()->preload(),
            ]);
    }
}
