<?php

namespace App\Filament\Pages;

use App\Enums\MediaClassification;
use App\Enums\MediaType;
use App\Models\Company;
use App\Models\PartnerMedia;
use Asmit\FilamentUpload\Forms\Components\AdvancedFileUpload;
use BackedEnum;
use BezhanSalleh\FilamentShield\Traits\HasPageShield;
use Filament\Forms\Components\Radio;
use Filament\Forms\Components\Textarea;
use Filament\Forms\Components\TextInput;
use Filament\Notifications\Notification;
use Filament\Pages\Page;
use Filament\Schemas\Components\Group;
use Filament\Schemas\Components\Section;
use Filament\Schemas\Schema;
use Filament\Support\Icons\Heroicon;
use Illuminate\Support\Facades\Storage;
use UnitEnum;

class CustomMedia extends Page
{
    use HasPageShield;

    protected string $view = 'filament.pages.custom-media';

    protected static ?string $title = 'Media';

    protected static ?string $model = PartnerMedia::class;

    protected static string|BackedEnum|null $navigationIcon = Heroicon::Newspaper;

    protected static ?string $navigationLabel = 'Media';

    protected static string|UnitEnum|null $navigationGroup = 'Kelola';

    protected static ?string $slug = 'manage/media';

    protected static ?string $recordTitleAttribute = 'name';

    protected static ?int $navigationSort = 10;

    public ?Company $company = null;

    public ?PartnerMedia $media = null;

    public bool $restricted = false;

    public array $data = [];

    public function mount(): void
    {
        if (auth()->user()->hasRole('Perusahaan') && ! auth()->user()->company) {
            $this->restricted = true;

            return;
        }

        $this->company = auth()->user()->company;

        $media = $this->company?->partnerMedia;

        if (! $media) {
            return;
        }

        $this->media = $media;

        $this->form->fill($media->toArray());

        $documents = [
            'journalism_organization',
            'press_council_certificate',
        ];

        $mediaItems = $media->getMedia('partnerMedia');

        foreach ($documents as $docType) {
            $media = $mediaItems
                ->where('custom_properties.doc_type', str($docType)->replace('_docs', '')->slug('-'))
                ->sortByDesc('created_at')
                ->first();

            if ($media) {
                $this->data["{$docType}_docs"] = [$media->getPathRelativeToRoot()];
            }
        }
    }

    public static function form(Schema $schema): Schema
    {
        $documents = [
            [
                'title' => 'Organisasi Kewartawanan',
                'text_name' => 'journalism_organization',
                'placeholder' => '*****',
                'max' => 100,
                'max_size' => 1024 * 10,
                'file_name' => 'journalism_organization_docs',
                'accept' => ['application/pdf'],
                'folder' => 'media/journalism-organization/',
            ],
            [
                'title' => 'Sertifikat Dewan Pers',
                'text_name' => 'press_council_certificate',
                'placeholder' => '*****',
                'max' => 100,
                'max_size' => 1024 * 10,
                'file_name' => 'press_council_certificate_docs',
                'accept' => ['application/pdf'],
                'folder' => 'media/press-council-certificate/',
            ],
        ];

        return $schema
            ->components([
                Section::make('Informasi')
                    ->schema([
                        TextInput::make('name')
                            ->label('Nama')
                            ->placeholder('PWK News')
                            ->autocomplete(false)
                            ->autofocus()
                            ->required()
                            ->maxLength(100),

                        TextInput::make('link')
                            ->label('Tautan')
                            ->placeholder('https://www.pwknews.com')
                            ->autocomplete(false)
                            ->nullable()
                            ->maxLength(50)
                            ->url(),

                        Textarea::make('address')
                            ->label('Alamat')
                            ->placeholder('Jl. Kebontoro, Jakarta Pusat')
                            ->autocomplete(false)
                            ->required()
                            ->columnSpanFull(),

                        Radio::make('type')
                            ->label('Jenis')
                            ->options(MediaType::options())
                            ->inline()
                            ->required()
                            ->in(implode(',', array_column(MediaType::cases(), 'value'))),

                        Radio::make('classification')
                            ->label('Klasifikasi')
                            ->options(MediaClassification::options())
                            ->inline()
                            ->required()
                            ->in(implode(',', array_column(MediaClassification::cases(), 'value'))),
                    ])
                    ->columns(2)
                    ->columnSpan(2),

                Group::make()
                    ->schema(

                        collect($documents)
                            ->map(
                                fn ($doc) => Section::make($doc['title'])
                                    ->schema([
                                        TextInput::make($doc['text_name'])
                                            ->hiddenLabel()
                                            ->placeholder($doc['placeholder'])
                                            ->autocomplete(false)
                                            ->required()
                                            ->maxLength($doc['max']),

                                        AdvancedFileUpload::make($doc['file_name'])
                                            ->hiddenLabel()
                                            ->disk(config('filesystems.default'))
                                            ->acceptedFileTypes($doc['accept'])
                                            ->maxSize($doc['max_size'])
                                            ->directory($doc['folder'].now()->toDateString())
                                            ->required(),
                                    ])
                            )->toArray()
                    )
                    ->columns(2),
            ])
            ->statePath('data');
    }

    public function save()
    {
        $data = $this->form->getState();

        $media = PartnerMedia::updateOrCreate([
            'id' => $this->media?->id,
        ], [
            'company_id' => $this->company->id,
            'name' => $data['name'],
            'link' => $data['link'],
            'address' => $data['address'],
            'type' => $data['type'],
            'classification' => $data['classification'],
            'journalism_organization' => $data['journalism_organization'],
            'press_council_certificate' => $data['press_council_certificate'],
        ]);

        $this->media = $media;

        $documents = [
            'journalism_organization_docs',
            'press_council_certificate_docs',
        ];

        foreach ($documents as $field) {
            if (empty($this->data[$field])) {
                continue;
            }

            foreach ((array) $this->data[$field] as $filePath) {
                $fullPath = Storage::disk(config('filesystems.default'))->path($filePath);

                if (! file_exists($fullPath)) {
                    continue;
                }

                $media
                    ->addMediaFromDisk($filePath, config('filesystems.default'))
                    ->preservingOriginal()
                    ->withCustomProperties([
                        'feature' => 'media',
                        'date' => now()->toDateString(),
                        'doc_type' => str($field)
                            ->replace('_docs', '')
                            ->slug('-'),
                    ])
                    ->toMediaCollection('partnerMedia');
            }
        }

        Notification::make()
            ->title('Informasi media berhasil diperbarui.')
            ->success()
            ->send();
    }
}
