<?php

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

use App\Enums\LicenseStatus;
use App\Filament\AssociationAdmin\Resources\AssociationWellLicenseResource;
use App\Filament\Resources\WellLicenseResource\Components\WellLicenseApprovalFlow as BaseWellLicenseApprovalFlow;
use App\Models\WellLicense;
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 ViewAssociationWellLicense extends ViewRecord
{
    protected static string $resource = AssociationWellLicenseResource::class;

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

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

        $actions = [];

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

        $requiredPermission = BaseWellLicenseApprovalFlow::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(__('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('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')
                                ->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(__('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');
    }

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

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

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

        return null;
    }
}
