<?php

namespace App\Filament\Pages;

use App\Exports\OrdersReportExport;
use App\Models\Client;
use App\Models\Order;
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 OrdersReport extends Page implements HasSchemas
{
    use InteractsWithSchemas;

    protected static ?string $title = 'تقرير الطلبات';

    protected static string | \BackedEnum | null $navigationIcon = 'heroicon-o-shopping-cart';

    protected static ?string $navigationLabel = 'تقرير الطلبات';

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

    protected static ?int $navigationSort = 1;

    public ?string $start_date = null;
    public ?string $end_date = null;
    public ?string $status = null;
    public ?int $client_id = 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('status')
                            ->label('حالة الطلب')
                            ->options([
                                'pending' => 'قيد الانتظار',
                                'confirmed' => 'مؤكد',
                                'in_progress' => 'قيد التنفيذ',
                                'completed' => 'مكتمل',
                                'cancelled' => 'ملغي',
                            ])
                            ->native(false)
                            ->columnSpan(1),
                        Select::make('client_id')
                            ->label('العميل')
                            ->options(Client::pluck('name', 'id'))
                            ->searchable()
                            ->preload()
                            ->columnSpan(1),
                        Select::make('technician_id')
                            ->label('الفني')
                            ->options(Technician::pluck('name', 'id'))
                            ->searchable()
                            ->preload()
                            ->columnSpan(1),
                    ])->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();
        $orders = $this->getFilteredOrders($data);
        $filename = 'orders-report-' . Carbon::now()->format('Y-m-d') . '.xlsx';

        return Excel::download(new OrdersReportExport($orders), $filename);
    }

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

        $html = view('reports.orders', [
            'orders' => $orders,
            'data' => $data,
            'title' => 'تقرير الطلبات',
            'totalFees' => $orders->sum('fee'),
            'totalPrice' => $orders->sum('price'),
            'totalCommission' => $orders->sum('technician_commission'),
            'totalDiscount' => $orders->sum('discount'),
            'totalAmount' => $orders->sum('total'),
        ])->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 getFilteredOrders(array $data)
    {
        $query = Order::with(['client', 'service', 'technician']);

        if ($data['start_date']) {
            $query->whereDate('created_at', '>=', $data['start_date']);
        }

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

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

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

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

        return $query->get();
    }
}
