<?php

namespace App\Filament\AssociationAdmin\Resources\AssociationStationLicenseResource\Pages;

use App\Enums\LicenseStatus;
use App\Filament\AssociationAdmin\Resources\AssociationStationLicenseResource;
use App\Filament\Resources\StationLicenseResource\Components\StationLicenseApprovalFlow;
use App\Models\StationLicense;
use Filament\Actions;
use Filament\Infolists\Components\Grid;
use Filament\Infolists\Components\Section;
use Filament\Infolists\Components\Split;
use Filament\Infolists\Components\TextEntry;
use Filament\Infolists\Infolist;
use Filament\Notifications\Notification;
use Filament\Resources\Pages\ViewRecord;
use Filament\Support\Enums\FontWeight;
use Illuminate\Support\Facades\Auth;

class ViewAssociationStationLicense extends ViewRecord
{
    protected static string $resource = AssociationStationLicenseResource::class;

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

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

        $actions = [];

        if ($record->status === LicenseStatus::PENDING_REQUIREMENTS) {
            $actions[] = Actions\EditAction::make();
        }

        $requiredPermission = StationLicenseApprovalFlow::getStepPermission($record->status);
        if ($requiredPermission && Auth::user()->can($requiredPermission)) {
            $actions[] = Actions\Action::make('approve')
                ->label(__('well_license.association_approve_to_next_stage'))
                ->icon('heroicon-o-check-circle')
                ->color('success')
                ->modalHeading(__('well_license.approve_confirm_title'))
                ->modalDescription(__('well_license.association_approve_confirm_title'))
                ->modalSubmitActionLabel(__('well_license.association_approve_confirm_message'))
                ->action(function () use ($record) {
                    return self::handleApproval($record);
                })
                ->visible($record->canApproveToNextStage());
        }

        return $actions;
    }

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

    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('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')
                                ->color('primary'),

                            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');
    }

    private static function handleApproval(StationLicense $record)
    {
        $notes = 'تم الإرسال للموافقة من قبل الجهة';

        // Approve to next stage
        if ($record->approveToNextStage($notes)) {
            Notification::make()
                ->title(__('well_license.approved_successfully'))
                ->success()
                ->send();

            return redirect(AssociationStationLicenseResource::getUrl('view', ['record' => $record]));
        } else {
            Notification::make()
                ->title(__('well_license.approval_failed'))
                ->danger()
                ->send();
        }

        return null;
    }
}
