<?php

namespace App\Models;

use App\Scopes\AdminsTaskViewScope;
use Heloufir\FilamentKanban\Interfaces\KanbanRecordModel;
use Heloufir\FilamentKanban\ValueObjects\KanbanRecord;
use Heloufir\FilamentKanban\ValueObjects\KanbanResources;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Support\Facades\Auth;
use Spatie\EloquentSortable\Sortable;
use Spatie\EloquentSortable\SortableTrait;
use Spatie\MediaLibrary\HasMedia;
use Spatie\MediaLibrary\InteractsWithMedia;
use Spatie\MediaLibrary\MediaCollections\Models\Media;

class AdminsTask extends Model implements HasMedia, KanbanRecordModel, Sortable
{
    use HasFactory, InteractsWithMedia, SortableTrait;

    // Keep constants for backward compatibility and transition period
    const STATUS_PENDING = 'pending';

    const STATUS_IN_PROGRESS = 'in_progress';

    const STATUS_COMPLETED = 'completed';

    const STATUS_CANCELLED = 'cancelled';

    const STATUS_ON_HOLD = 'on_hold';

    protected $fillable = [
        'name',
        'description',
        'start_date',
        'end_date',
        'status_id',
        'created_by',
        'order_column',
    ];

    protected $casts = [
        'start_date' => 'datetime',
        'end_date' => 'datetime',
        'created_at' => 'datetime',
        'updated_at' => 'datetime',
    ];

    protected $attributes = [
        // Default will be set through relationship
    ];

    protected $with = [
        'status',
    ];

    /**
     * Sortable configuration for Kanban board
     */
    public $sortable = [
        'order_column_name' => 'order_column',
        'sort_when_creating' => true,
    ];

    /**
     * Define the group column for sorting (tasks are sorted within each status)
     */
    public function buildSortQuery()
    {
        return static::query()->where('status_id', $this->status_id);
    }

    protected static function boot()
    {
        parent::boot();

        static::creating(function ($model) {
            if (Auth::check()) {
                $model->created_by = Auth::id();
            }

            // Set default status if not provided
            if (! $model->status_id) {
                $defaultStatus = AdminsTaskStatus::getDefault();
                if ($defaultStatus) {
                    $model->status_id = $defaultStatus->id;
                }
            }
        });
    }

    /**
     * Boot the model and add global scope
     */
    protected static function booted()
    {
        static::addGlobalScope(new AdminsTaskViewScope);
    }

    /**
     * Get the status of this task
     */
    public function status(): BelongsTo
    {
        return $this->belongsTo(AdminsTaskStatus::class, 'status_id');
    }

    /**
     * Get the user who created this task
     */
    public function creator(): BelongsTo
    {
        return $this->belongsTo(User::class, 'created_by');
    }

    /**
     * Get the assigned users
     */
    public function assignedUsers(): BelongsToMany
    {
        return $this->belongsToMany(User::class, 'admins_task_user')
            ->withTimestamps();
    }

    /**
     * Get the checklist items for this task
     */
    public function checklistItems(): \Illuminate\Database\Eloquent\Relations\HasMany
    {
        return $this->hasMany(AdminsTaskChecklistItem::class)
            ->orderBy('order_column');
    }

    /**
     * Register media collections for file uploads
     */
    public function registerMediaCollections(): void
    {
        $this->addMediaCollection('task_attachments')
            ->acceptsMimeTypes([
                'application/pdf',
                'application/msword',
                'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
                'application/vnd.ms-excel',
                'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
                'application/vnd.ms-powerpoint',
                'application/vnd.openxmlformats-officedocument.presentationml.presentation',
                'image/jpeg',
                'image/png',
                'image/gif',
                'image/webp',
                'text/plain',
                'application/zip',
                'application/x-rar-compressed',
            ]);
    }

    /**
     * Register media conversions for thumbnails
     */
    public function registerMediaConversions(?Media $media = null): void
    {
        $this->addMediaConversion('thumb')
            ->width(300)
            ->height(300)
            ->sharpen(10)
            ->optimize()
            ->nonQueued();

        $this->addMediaConversion('preview')
            ->width(500)
            ->height(500)
            ->sharpen(10)
            ->optimize()
            ->nonQueued();
    }

    /**
     * Get all task attachments
     */
    public function getTaskAttachments()
    {
        return $this->getMedia('task_attachments');
    }

    /**
     * Check if task has attachments
     */
    public function hasAttachments(): bool
    {
        return $this->getMedia('task_attachments')->isNotEmpty();
    }

    /**
     * Get attachments count
     */
    public function getAttachmentsCount(): int
    {
        return $this->getMedia('task_attachments')->count();
    }

    /**
     * Get checklist completion percentage
     */
    public function getChecklistCompletionPercentage(): float
    {
        $totalItems = $this->checklistItems()->count();

        if ($totalItems === 0) {
            return 0;
        }

        $completedItems = $this->checklistItems()->where('is_completed', true)->count();

        return ($completedItems / $totalItems) * 100;
    }

    /**
     * Check if all checklist items are completed
     */
    public function isChecklistCompleted(): bool
    {
        $totalItems = $this->checklistItems()->count();

        if ($totalItems === 0) {
            return true; // No checklist means it's "completed"
        }

        return $this->checklistItems()->where('is_completed', false)->count() === 0;
    }

    /**
     * Get completed checklist items count
     */
    public function getCompletedChecklistItemsCount(): int
    {
        return $this->checklistItems()->where('is_completed', true)->count();
    }

    /**
     * Get total checklist items count
     */
    public function getTotalChecklistItemsCount(): int
    {
        return $this->checklistItems()->count();
    }

    public function toKanbanRecord(): KanbanRecord
    {
        return KanbanRecord::make($this)
            ->deletable(true)
            ->sortable(true)
            ->editable(true)
            ->viewable(true)
            ->id($this->id)
            ->title($this->name)
            ->description($this->description)
            ->deadline($this->end_date)
            // ->progress('progress')
            ->assignees(
                KanbanResources::make(
                    $this->assignedUsers
                )
            )
            ->color($this->status->color)
            ->status($this->status->toKanbanStatus());
        // ->tags(true);
    }

    public function statusColumn(): string
    {
        return 'status_id';
    }

    public function sortColumn(): string
    {
        return 'order_column';
    }
}
