<?php

namespace App\Filament\Resources\StationLicenseResource\Pages;

use App\Enums\LicenseStatus;
use App\Filament\Resources\AssociationResource;
use App\Filament\Resources\StationLicenseResource;
use App\Filament\Resources\StationLicenseResource\Components\StationLicenseApprovalFlow;
use App\Models\StationLicense;
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 ViewStationLicense extends ViewRecord
{
    protected static string $resource = StationLicenseResource::class;

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

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

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

        // Add PDF generation action if license is approved
        if ($record->status === LicenseStatus::APPROVED) {
            $actions[] = Html2MediaAction::make('downloadCertificate')
                ->label(__('station_license.download_certificate'))
                ->icon('heroicon-o-arrow-down-tray')
                ->color('success')
                ->filename(fn () => 'station-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(__('station_license.basic_information'))
                        ->icon('heroicon-o-document-text')
                        ->schema([
                            TextEntry::make('status')
                                ->label(__('station_license.status'))
                                ->badge()
                                ->formatStateUsing(fn (LicenseStatus $state): string => $state->getLabel())
                                ->color(fn (LicenseStatus $state): string => $state->getColor()),

                            TextEntry::make('current_status_notes')
                                ->label(__('station_license.current_status_notes'))
                                ->visible(fn (StationLicense $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('station_name')
                                        ->label(__('station_license.station_name'))
                                        ->weight(FontWeight::SemiBold),

                                    TextEntry::make('wellLicenses.well_name')
                                        ->label(__('station_license.well_licenses'))
                                        ->icon('heroicon-o-beaker')
                                        ->badge()
                                        ->color('info')
                                        ->separator(',')
                                        ->listWithLineBreaks()
                                        ->placeholder('—'),

                                    TextEntry::make('site_area')
                                        ->label(__('station_license.site_area'))
                                        ->suffix(' '.__('station_license.site_area_suffix'))
                                        ->numeric(2),

                                    TextEntry::make('design_capacity')
                                        ->label(__('station_license.design_capacity'))
                                        ->suffix(' '.__('station_license.design_capacity_suffix'))
                                        ->numeric(2),

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

                                    TextEntry::make('state.name')
                                        ->label(__('station_license.state'))
                                        ->icon('heroicon-o-map-pin')
                                        ->visible(fn (StationLicense $record): bool => ! empty($record->state_id)),

                                    TextEntry::make('city.name')
                                        ->label(__('station_license.city'))
                                        ->icon('heroicon-o-building-office')
                                        ->visible(fn (StationLicense $record): bool => ! empty($record->city_id)),

                                    TextEntry::make('center.name')
                                        ->label(__('station_license.center'))
                                        ->icon('heroicon-o-map')
                                        ->placeholder('—')
                                        ->visible(fn (StationLicense $record): bool => ! empty($record->center_id)),

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

                                    TextEntry::make('location')
                                        ->label(__('station_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(__('station_license.ministry_license_information'))
                        ->icon('heroicon-o-shield-check')
                        ->visible(fn (StationLicense $record): bool => $record->status === LicenseStatus::APPROVED)
                        ->schema([
                            Grid::make(2)
                                ->schema([
                                    TextEntry::make('ministry_license_number')
                                        ->label(__('station_license.ministry_license_number'))
                                        ->icon('heroicon-o-document-text')
                                        ->badge()
                                        ->color('success'),

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

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

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

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

                                    TextEntry::make('ministry_license_file')
                                        ->label(__('station_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(),
                                ]),
                        ]),

                    // Environmental Compliance Card
                    Section::make(__('station_license.environmental_compliance'))
                        ->icon('heroicon-o-shield-check')
                        ->schema([
                            Grid::make(2)
                                ->schema([
                                    TextEntry::make('has_environmental_permit')
                                        ->label(__('station_license.has_environmental_permit'))
                                        ->badge()
                                        ->formatStateUsing(fn (bool $state): string => $state ? __('station_license.yes') : __('station_license.no'))
                                        ->color(fn (bool $state): string => $state ? 'success' : 'gray'),

                                    TextEntry::make('has_evaporation_ponds')
                                        ->label(__('station_license.has_evaporation_ponds'))
                                        ->badge()
                                        ->formatStateUsing(fn (bool $state): string => $state ? __('station_license.yes') : __('station_license.no'))
                                        ->color(fn (bool $state): string => $state ? 'success' : 'gray'),

                                    TextEntry::make('evaporation_ponds_count')
                                        ->label(__('station_license.evaporation_ponds_count'))
                                        ->numeric()
                                        ->visible(fn ($record) => $record->has_evaporation_ponds),

                                    TextEntry::make('evaporation_ponds_area')
                                        ->label(__('station_license.evaporation_ponds_area'))
                                        ->suffix(' '.__('station_license.evaporation_ponds_area_suffix'))
                                        ->numeric(2)
                                        ->visible(fn ($record) => $record->has_evaporation_ponds),
                                ]),
                        ]),
                ]),

            // Second Column
            Grid::make(1)
                ->schema([
                    // Association Info Card
                    Section::make(__('station_license.association'))
                        ->icon('heroicon-o-building-office-2')
                        ->schema([
                            TextEntry::make('association.name')
                                ->label(__('station_license.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(__('association.phone'))
                                        ->icon('heroicon-o-phone')
                                        ->copyable(),
                                ]),
                        ]),

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

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

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