<?php

namespace App\Filament\Resources\Interviews\Pages;

use App\Filament\Resources\Interviews\InterviewResource;
use App\Mail\InterviewScheduled;
use App\Mail\InterviewScheduledAdmin;
use App\Models\AdoptionApplication;
use App\Models\ApplicationStatusHistory;
use App\Models\Interview;
use App\Models\Setting;
use Filament\Actions\Action;
use Filament\Resources\Pages\CreateRecord;
use Filament\Support\Icons\Heroicon;
use Illuminate\Contracts\View\View;
use Illuminate\Support\Facades\Mail;

class CreateInterview extends CreateRecord
{
    protected static string $resource = InterviewResource::class;

    protected static bool $canCreateAnother = false;

    protected function getRedirectUrl(): string
    {
        return $this->getResource()::getUrl('index');
    }

    protected function getCreateFormAction(): Action
    {
        return parent::getCreateFormAction()
            ->requiresConfirmation()
            ->modalHeading('Schedule Interview')
            ->modalDescription('This will schedule the interview and send email notifications based on your communication settings.')
            ->modalSubmitActionLabel('Schedule & Send Emails')
            ->submit('create');
    }

    protected function getFormActions(): array
    {
        return [
            $this->getCreateFormAction(),
            Action::make('skipInterview')
                ->label('Skip Interview & Move to Decisioning')
                ->icon(Heroicon::OutlinedForward)
                ->color('warning')
                ->requiresConfirmation()
                ->modalHeading('Skip Interview?')
                ->modalDescription('This will skip the interview process and move the application directly to decisioning. No interview will be scheduled.')
                ->modalSubmitActionLabel('Skip Interview')
                ->action(function () {
                    $data = $this->form->getState();

                    if (! isset($data['adoption_application_id'])) {
                        return;
                    }

                    $interview = Interview::create([
                        'adoption_application_id' => $data['adoption_application_id'],
                        'skipped_at' => now(),
                    ]);

                    $adoptionApplication = AdoptionApplication::find($data['adoption_application_id']);

                    if ($adoptionApplication?->pet) {
                        $adoptionApplication->pet->update([
                            'status' => 'pending',
                        ]);
                    }

                    $oldStatus = $adoptionApplication->status;

                    $adoptionApplication->update([
                        'status' => 'under_review',
                    ]);

                    ApplicationStatusHistory::create([
                        'adoption_application_id' => $adoptionApplication->id,
                        'from_status' => $oldStatus,
                        'to_status' => 'under_review',
                        'changed_by' => auth()->id(),
                        'notes' => 'Interview skipped - moved directly to decisioning',
                    ]);

                    $this->redirect($this->getResource()::getUrl('index'));
                }),
            $this->getCancelFormAction(),
        ];
    }

    protected function afterCreate(): void
    {
        /** @var Interview $interview */
        $interview = $this->record;

        $interview->load('adoptionApplication.pet.species', 'adoptionApplication.user');

        if ($interview->adoptionApplication->pet) {
            $interview->adoptionApplication->pet->update([
                'status' => 'pending',
            ]);
        }

        $oldStatus = $interview->adoptionApplication->status;

        $interview->adoptionApplication->update([
            'status' => 'interview_scheduled',
        ]);

        ApplicationStatusHistory::create([
            'adoption_application_id' => $interview->adoptionApplication->id,
            'from_status' => $oldStatus,
            'to_status' => 'interview_scheduled',
            'changed_by' => auth()->id(),
            'notes' => 'Interview scheduled',
        ]);

        // Send email notifications to applicant and admin who scheduled the interview
        $applicant = $interview->adoptionApplication->user;
        $admin = auth()->user();

        if (Setting::get('email_interview_scheduled_enabled', true)) {
            Mail::to($applicant)->send(new InterviewScheduled($interview, $admin));
        }
        if (Setting::get('email_interview_scheduled_admin_enabled', true)) {
            Mail::to($admin)->send(new InterviewScheduledAdmin($interview, $admin));
        }
    }

    public function getFooter(): ?View
    {
        $adoptionApplicationId = request()->query('adoption_application_id');

        if (! $adoptionApplicationId) {
            return null;
        }

        $adoptionApplication = AdoptionApplication::with(['user', 'pet.species'])->find($adoptionApplicationId);

        if (! $adoptionApplication) {
            return null;
        }

        return view('filament.resources.interviews.pages.create-interview-footer', [
            'adoptionApplication' => $adoptionApplication,
        ]);
    }
}
