<?php

namespace App\Filament\Pages;

use App\Models\Technician;
use Mpdf\Mpdf;
use Filament\Actions\Action;
use Filament\Forms\Components\DatePicker;
use Filament\Forms\Components\Select;
use Filament\Pages\Page;
use Filament\Schemas\Components\Actions;
use Filament\Schemas\Components\EmbeddedSchema;
use Filament\Schemas\Components\Form;
use Filament\Schemas\Components\Section;
use Filament\Schemas\Concerns\InteractsWithSchemas;
use Filament\Schemas\Contracts\HasSchemas;
use Filament\Schemas\Schema;
use Illuminate\Support\Carbon;
use Maatwebsite\Excel\Facades\Excel;

class TechniciansReport extends Page implements HasSchemas
{
    use InteractsWithSchemas;

    protected static ?string $title = 'تقرير الفنيين';

    protected static string | \BackedEnum | null $navigationIcon = 'heroicon-o-wrench-screwdriver';

    protected static ?string $navigationLabel = 'تقرير الفنيين';

    protected static string | \UnitEnum | null $navigationGroup = 'التقارير';

    protected static ?int $navigationSort = 4;

    public ?string $start_date = null;
    public ?string $end_date = null;
    public ?int $technician_id = null;

    public function mount(): void
    {
        $this->form->fill([
            'start_date' => Carbon::now()->startOfMonth()->format('Y-m-d'),
            'end_date' => Carbon::now()->format('Y-m-d'),
        ]);
    }

    public function form(Schema $schema): Schema
    {
        return $schema
            ->components([
                Section::make('إعدادات التقرير')
                    ->description('اختر الفلاتر المطلوبة لتقرير الفنيين')
                    ->icon('heroicon-o-funnel')
                    ->components([
                        DatePicker::make('start_date')
                            ->label('من تاريخ')
                            ->required()
                            ->native(false)
                            ->default(Carbon::now()->startOfMonth())
                            ->columnSpan(1),
                        DatePicker::make('end_date')
                            ->label('إلى تاريخ')
                            ->required()
                            ->native(false)
                            ->default(Carbon::now())
                            ->columnSpan(1),
                        Select::make('technician_id')
                            ->label('الفني')
                            ->options(Technician::pluck('name', 'id'))
                            ->searchable()
                            ->preload()
                            ->columnSpanFull(),
                    ])->columns(2),
            ]);
    }

    public function content(Schema $schema): Schema
    {
        return $schema
            ->components([
                Form::make([EmbeddedSchema::make('form')])
                    ->id('form')
                    ->footer([
                        Actions::make($this->getFormActions())
                            ->alignment('end')
                            ->key('form-actions'),
                    ]),
            ]);
    }

    protected function getFormActions(): array
    {
        return [
            Action::make('export_excel')
                ->label('تصدير Excel')
                ->icon('heroicon-o-arrow-down-tray')
                ->color('success')
                ->action('exportExcel'),
            Action::make('export_pdf')
                ->label('تصدير PDF')
                ->icon('heroicon-o-document-arrow-down')
                ->color('danger')
                ->action('exportPdf'),
        ];
    }

    public function exportExcel(): \Symfony\Component\HttpFoundation\BinaryFileResponse
    {
        $data = $this->form->getState();
        $technicians = $this->getFilteredTechnicians($data);
        $filename = 'technicians-report-' . Carbon::now()->format('Y-m-d') . '.xlsx';

        $export = new class($technicians) implements \Maatwebsite\Excel\Concerns\FromCollection, \Maatwebsite\Excel\Concerns\WithHeadings, \Maatwebsite\Excel\Concerns\WithMapping {
            protected $technicians;

            public function __construct($technicians)
            {
                $this->technicians = $technicians;
            }

            public function collection()
            {
                return $this->technicians;
            }

            public function headings(): array
            {
                return ['الاسم', 'البريد الإلكتروني', 'رقم الهاتف', 'الخدمة', 'عدد الطلبات', 'إجمالي الطلبات المكتملة', 'رسوم التطبيق', 'إجمالي المستحقات', 'صافي الفني', 'تاريخ التسجيل', 'الحالة'];
            }

            public function map($technician): array
            {
                $completedTotal = $technician->completed_total ?? 0;
                $completedFee = $technician->completed_fee ?? 0;
                $completedCommission = $technician->completed_commission ?? 0;
                $technicianNet = $completedCommission;

                return [
                    $technician->name,
                    $technician->email,
                    $technician->phone ?? '-',
                    $technician->service?->getTranslation('name', 'ar') ?? '-',
                    $technician->orders_count ?? 0,
                    number_format($completedTotal, 2) . ' ر.س',
                    number_format($completedFee, 2) . ' ر.س',
                    number_format($completedCommission, 2) . ' ر.س',
                    number_format($technicianNet, 2) . ' ر.س',
                    $technician->created_at->format('Y-m-d'),
                    $technician->is_active ? 'نشط' : 'غير نشط',
                ];
            }
        };

        return Excel::download($export, $filename);
    }

    public function exportPdf()
    {
        $data = $this->form->getState();
        $technicians = $this->getFilteredTechnicians($data);
        $filename = 'technicians-report-' . Carbon::now()->format('Y-m-d') . '.pdf';

        $html = view('reports.technicians', [
            'technicians' => $technicians,
            'data' => $data,
            'title' => 'تقرير الفنيين',
        ])->render();

        $mpdf = new Mpdf([
            'mode' => 'utf-8',
            'format' => 'A4-L',
            'orientation' => 'L',
            'margin_left' => 10,
            'margin_right' => 10,
            'margin_top' => 10,
            'margin_bottom' => 10,
            'default_font' => 'dejavusans',
            'direction' => 'rtl',
        ]);

        $mpdf->WriteHTML($html);
        
        return response()->streamDownload(function () use ($mpdf) {
            echo $mpdf->Output('', 'S');
        }, $filename);
    }

    protected function getFilteredTechnicians(array $data)
    {
        $query = Technician::with('service')->withCount('orders')
            ->withSum(['orders as completed_total' => function ($q) {
                $q->where('status', 'completed');
            }], 'total')
            ->withSum(['orders as completed_fee' => function ($q) {
                $q->where('status', 'completed');
            }], 'fee')
            ->withSum(['orders as completed_price' => function ($q) {
                $q->where('status', 'completed');
            }], 'price')
            ->withSum(['orders as completed_commission' => function ($q) {
                $q->where('status', 'completed');
            }], 'technician_commission');

        if ($data['start_date']) {
            $query->whereHas('orders', function ($q) use ($data) {
                $q->whereDate('created_at', '>=', $data['start_date']);
            });
        }

        if ($data['end_date']) {
            $query->whereHas('orders', function ($q) use ($data) {
                $q->whereDate('created_at', '<=', $data['end_date']);
            });
        }

        if (!empty($data['technician_id'])) {
            $query->where('id', $data['technician_id']);
        }

        return $query->get();
    }
}
