<?php

namespace App\Filament\Resources\WellLicenseResource\Pages;

use App\Enums\LicenseStatus;
use App\Filament\Resources\AssociationResource;
use App\Filament\Resources\WellLicenseResource;
use App\Filament\Resources\WellLicenseResource\Components\WellLicenseApprovalFlow;
use App\Models\WellLicense;
use Filament\Actions\Action;
use Filament\Infolists\Components\Grid;
use Filament\Infolists\Components\Section;
use Filament\Infolists\Components\Split;
use Filament\Infolists\Components\TextEntry;
use Filament\Infolists\Components\ViewEntry;
use Filament\Infolists\Infolist;
use Filament\Resources\Pages\ViewRecord;
use Filament\Support\Enums\FontWeight;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\HtmlString;
use RalphJSmit\Filament\Activitylog\Actions\TimelineAction;
use RalphJSmit\Filament\Activitylog\Infolists\Components\Timeline;
use Spatie\Activitylog\Models\Activity;
use Torgodly\Html2Media\Actions\Html2MediaAction;

class ViewWellLicense extends ViewRecord
{
    protected static string $resource = WellLicenseResource::class;

    public function getTitle(): string|\Illuminate\Contracts\Support\Htmlable
    {
        return $this->getRecord()->well_name;
    }

    protected function getHeaderActions(): array
    {
        $record = $this->getRecord();

        $actions = WellLicenseApprovalFlow::getApprovalFlowActions($record);

        // Add PDF generation action if license is approved
        if ($record->status === LicenseStatus::APPROVED) {
            $actions[] = Html2MediaAction::make('downloadCertificate')
                ->label(__('well_license.download_certificate'))
                ->icon('heroicon-o-arrow-down-tray')
                ->color('success')
                ->filename(fn () => 'well-license-'.$record->ministry_license_number)
                ->content(fn () => view('well-permit', [
                    // License Title
                    'license_title_ar' => 'تفويض رخصة استخدام مصدر المياه الجوفية (البئر)',

                    // License Information
                    'ministry_license_number' => $record->ministry_license_number,
                    'ministry_license_start_date' => $record->ministry_license_start_date,
                    'ministry_license_end_date' => $record->ministry_license_end_date,
                    'delegation_start_date' => $record->delegation_start_date,
                    'delegation_end_date' => $record->delegation_end_date,
                    'sekaya_license_number' => $record->ministry_license_number.' - 1',

                    // Location Information
                    'state' => $record->state?->name,
                    'city' => $record->city?->name,
                    'center' => $record->center?->name,
                    'lat' => $record->lat,
                    'lng' => $record->lng,

                    // Association Information
                    'association_name' => $record->association?->name,
                    'association_license_number' => $record->association?->license_number,
                ]))
                ->orientation('landscape')
                ->format('a4')
                ->savePdf()
                ->preview();
        }

        $actions[] = TimelineAction::make()
            ->label(__('order.timeline'))
            ->modifyTimelineUsing(function (Timeline $timeline) {
                return $timeline
                    ->modifyActivitiesQueryUsing(function (Builder $query) {
                        return $query->whereIn('event', ['created', 'approved', 'rejected', 'send_back']);
                    })
                    ->itemIcon('created', 'heroicon-o-plus-circle')
                    ->itemIconColor('created', 'gray')
                    ->itemIcon('approved', 'heroicon-o-check-circle')
                    ->itemIconColor('approved', 'success')
                    ->itemIcon('rejected', 'heroicon-o-x-circle')
                    ->itemIconColor('rejected', 'danger')
                    ->itemIcon('send_back', 'heroicon-o-arrow-uturn-left')
                    ->itemIconColor('send_back', 'warning')
                    ->eventDescriptions([
                        'created' => function (Activity $activity) {
                            $description = __('order.order_created_by', ['name' => $activity->causer?->name ?? __('common.system')]);

                            return new HtmlString($description);
                        },
                        'approved' => function (Activity $activity) {
                            $oldStatus = $activity->getExtraProperty('old_status');
                            $newStatus = $activity->getExtraProperty('new_status');
                            $oldStatusName = LicenseStatus::getOptions()[$oldStatus] ?? $oldStatus;
                            $newStatusName = LicenseStatus::getOptions()[$newStatus] ?? $newStatus;

                            $description = __('order.order_approved_by', ['name' => $activity->causer?->name]);
                            if ($oldStatus && $newStatus) {
                                $description .= '<br/>'.__('order.status_changed', ['old_status' => $oldStatusName, 'new_status' => $newStatusName]);
                            }

                            // Add notes to description instead of badge
                            $notes = $activity->getExtraProperty('notes');
                            if ($notes) {
                                $description .= '<br/><span style="font-size: 0.875rem; color: #6b7280;">'.__('common.notes').': '.$notes.'</span>';
                            }

                            return new HtmlString($description);
                        },
                        'rejected' => function (Activity $activity) {
                            $oldStatus = $activity->getExtraProperty('old_status');
                            $oldStatusName = LicenseStatus::getOptions()[$oldStatus] ?? $oldStatus;
                            $description = __('order.order_rejected_by', ['name' => $activity->causer?->name]);
                            if ($oldStatus) {
                                $description .= ' '.__('order.status_was', ['status' => $oldStatusName]);
                            }

                            // Add notes to description instead of badge
                            $notes = $activity->getExtraProperty('notes');
                            if ($notes) {
                                $description .= '<br/><span style="font-size: 0.875rem; color: #6b7280;">'.__('common.notes').': '.$notes.'</span>';
                            }

                            return new HtmlString($description);
                        },
                        'send_back' => function (Activity $activity) {
                            $oldStatus = $activity->getExtraProperty('old_status');
                            $newStatus = $activity->getExtraProperty('new_status');
                            $oldStatusName = LicenseStatus::getOptions()[$oldStatus] ?? $oldStatus;
                            $newStatusName = LicenseStatus::getOptions()[$newStatus] ?? $newStatus;

                            $description = __('order.order_sent_back_by', ['name' => $activity->causer?->name]);
                            if ($oldStatus && $newStatus) {
                                $description .= '<br/>'.__('order.status_changed', ['old_status' => $oldStatusName, 'new_status' => $newStatusName]);
                            }

                            // Add notes to description instead of badge
                            $notes = $activity->getExtraProperty('notes');
                            if ($notes) {
                                $description .= '<br/><span style="font-size: 0.875rem; color: #6b7280;">'.__('common.notes').': '.$notes.'</span>';
                            }

                            return new HtmlString($description);
                        },
                    ])
                    ->emptyStateHeading(__('order.no_timeline_activities'))
                    ->emptyStateDescription(__('order.no_timeline_activities_description'));
            });

        return $actions;
    }

    public function infolist(Infolist $infolist): Infolist
    {
        return $infolist
            ->schema([
                Grid::make(1)
                    ->schema([
                        // License Status Bar
                        $this->getLicenseStatusBar(),
                        // License Info Split
                        $this->getLicenseInfoSplit(),
                    ]),
            ]);
    }

    public function getLicenseStatusBar(): ViewEntry
    {
        return ViewEntry::make('license_status_bar')
            ->view('filament.components.license-status-bar')
            ->columnSpanFull();
    }

    public function getLicenseInfoSplit(): Split
    {
        return Split::make([
            // First Column
            Grid::make(1)
                ->schema([
                    // License Details Card
                    Section::make(__('well_license.basic_information'))
                        ->icon('heroicon-o-document-text')
                        ->schema([
                            TextEntry::make('status')
                                ->label(__('well_license.status'))
                                ->badge()
                                ->formatStateUsing(fn (LicenseStatus $state): string => $state->getLabel())
                                ->color(fn (LicenseStatus $state): string => $state->getColor()),

                            TextEntry::make('current_status_notes')
                                ->label(__('well_license.current_status_notes'))
                                ->visible(fn (WellLicense $record): bool => ! empty($record->current_status_notes)),

                            Grid::make(2)
                                ->schema([
                                    TextEntry::make('id')
                                        ->label('ID')
                                        ->weight(FontWeight::SemiBold)
                                        ->color('gray')
                                        ->badge()
                                        ->prefix('#'),

                                    TextEntry::make('well_name')
                                        ->label(__('well_license.well_name'))
                                        ->weight(FontWeight::SemiBold),

                                    TextEntry::make('well_depth')
                                        ->label(__('well_license.well_depth'))
                                        ->suffix(' '.__('well_license.well_depth_suffix'))
                                        ->numeric(2),

                                    TextEntry::make('well_diameter')
                                        ->label(__('well_license.well_diameter'))
                                        ->suffix(' '.__('well_license.well_diameter_suffix'))
                                        ->numeric(2),

                                    TextEntry::make('pump_size')
                                        ->label(__('well_license.pump_size'))
                                        ->suffix(' '.__('well_license.pump_size_suffix'))
                                        ->numeric(2),

                                    TextEntry::make('withdrawal_amount')
                                        ->label(__('well_license.withdrawal_amount'))
                                        ->suffix(' '.__('well_license.withdrawal_amount_suffix'))
                                        ->numeric(2),

                                    TextEntry::make('state.name')
                                        ->label(__('well_license.state'))
                                        ->icon('heroicon-o-map-pin'),

                                    TextEntry::make('city.name')
                                        ->label(__('well_license.city'))
                                        ->icon('heroicon-o-building-office'),

                                    TextEntry::make('center.name')
                                        ->label(__('well_license.center'))
                                        ->icon('heroicon-o-map')
                                        ->placeholder('—'),

                                    TextEntry::make('residentialGatherings.name')
                                        ->label(__('well_license.residential_gatherings'))
                                        ->badge()
                                        ->color('info')
                                        ->separator(',')
                                        ->visible(fn ($record): bool => $record->residentialGatherings()->exists()),

                                    TextEntry::make('location')
                                        ->label(__('well_license.coordinates'))
                                        ->icon('heroicon-o-globe-alt')
                                        ->formatStateUsing(function ($record): string {
                                            if ($record->lat && $record->lng) {
                                                return number_format($record->lat, 6).', '.number_format($record->lng, 6);
                                            }

                                            return '—';
                                        })
                                        ->color('primary'),
                                ]),
                        ]),

                    // Ministry License Information Card
                    Section::make(__('well_license.ministry_license_information'))
                        ->icon('heroicon-o-shield-check')
                        ->visible(fn (WellLicense $record): bool => $record->status === LicenseStatus::APPROVED)
                        ->schema([
                            Grid::make(2)
                                ->schema([
                                    TextEntry::make('ministry_license_number')
                                        ->label(__('well_license.ministry_license_number'))
                                        ->icon('heroicon-o-document-text')
                                        ->badge()
                                        ->color('success'),

                                    TextEntry::make('ministry_license_start_date')
                                        ->label(__('well_license.ministry_license_start_date'))
                                        ->date()
                                        ->icon('heroicon-o-calendar'),

                                    TextEntry::make('ministry_license_end_date')
                                        ->label(__('well_license.ministry_license_end_date'))
                                        ->date()
                                        ->icon('heroicon-o-calendar'),

                                    TextEntry::make('delegation_start_date')
                                        ->label(__('well_license.delegation_start_date'))
                                        ->date()
                                        ->icon('heroicon-o-calendar'),

                                    TextEntry::make('delegation_end_date')
                                        ->label(__('well_license.delegation_end_date'))
                                        ->date()
                                        ->icon('heroicon-o-calendar'),

                                    TextEntry::make('ministry_license_file')
                                        ->label(__('well_license.ministry_license_file'))
                                        ->icon('heroicon-o-paper-clip')
                                        ->state(function ($record): string {
                                            $media = $record->getFirstMedia('ministry_license');
                                            if ($media) {
                                                return '<a href="'.$media->getTemporaryUrl(now()->addMinutes(5)).'" target="_blank" class="text-primary-600 hover:underline">'.$media->getCustomProperty('file_title') ?? $media->file_name.'</a>';
                                            }

                                            return '—';
                                        })
                                        ->html()
                                        ->columnSpanFull(),
                                ]),
                        ]),

                ]),

            // Second Column
            Grid::make(1)
                ->schema([
                    // Association Info Card
                    Section::make(__('order.association_information'))
                        ->icon('heroicon-o-building-office-2')
                        ->schema([
                            TextEntry::make('association.name')
                                ->label(__('order.association'))
                                ->weight(FontWeight::SemiBold)
                                ->icon('heroicon-o-building-office-2')
                                ->url(fn ($record) => $record->association ? AssociationResource::getUrl('view', ['record' => $record->association]) : null)
                                ->color('primary')
                                ->openUrlInNewTab(false),

                            Grid::make(2)
                                ->schema([
                                    TextEntry::make('association.representative_full_name')
                                        ->label(__('association.representative'))
                                        ->icon('heroicon-o-user')
                                        ->copyable(),

                                    TextEntry::make('association.phone_number')
                                        ->label(__('order.association_phone'))
                                        ->icon('heroicon-o-phone')
                                        ->copyable(),
                                ]),
                        ]),

                    // Timestamps Card
                    Section::make(__('well_license.created_at'))
                        ->icon('heroicon-o-clock')
                        ->schema([
                            Grid::make(2)
                                ->schema([
                                    TextEntry::make('created_at')
                                        ->label(__('well_license.created_at'))
                                        ->dateTime()
                                        ->icon('heroicon-o-calendar'),

                                    TextEntry::make('updated_at')
                                        ->label(__('well_license.updated_at'))
                                        ->dateTime()
                                        ->icon('heroicon-o-calendar'),

                                    TextEntry::make('createdBy.name')
                                        ->label(__('well_license.created_by'))
                                        ->icon('heroicon-o-user'),
                                ]),
                        ]),
                ]),
        ])
            ->from('lg')
            ->columnSpan('full');
    }
}
