<?php

namespace App\Livewire;

use App\Models\Profile;
use Livewire\Component;
use Livewire\WithFileUploads;
use Livewire\Attributes\Rule;
use Illuminate\Support\Facades\Auth;

class ProfileComponent extends Component
{
    use WithFileUploads;

    public Profile $profile;
    
    #[Rule('required|min:2|max:50|unique:profiles,display_name')]
    public string $display_name = '';
    
    #[Rule('nullable|max:50')]
    public ?string $pronouns = '';
    
    #[Rule('nullable|max:500')]
    public ?string $bio = '';
    
    #[Rule('nullable|url|max:255')]
    public ?string $twitter = '';
    
    #[Rule('nullable|url|max:255')]
    public ?string $instagram = '';
    
    #[Rule('nullable|url|max:255')]
    public ?string $youtube = '';
    
    #[Rule('nullable|max:100')]
    public ?string $discord = '';
    
    #[Rule('nullable|image|max:1024')] // 1MB Max
    public $avatar;

    public function mount()
    {
        $this->profile = Auth::user()->profile;
        $this->fill($this->profile->only([
            'display_name',
            'pronouns',
            'bio',
            'twitter',
            'instagram',
            'youtube',
            'discord',
        ]));
    }

    public function save()
    {
        $this->validate();

        if ($this->avatar) {
            $this->profile->setAvatar($this->avatar);
        }

        $this->profile->update([
            'display_name' => $this->display_name,
            'pronouns' => $this->pronouns,
            'bio' => $this->bio,
            'twitter' => $this->twitter,
            'instagram' => $this->instagram,
            'youtube' => $this->youtube,
            'discord' => $this->discord,
        ]);

        session()->flash('message', 'Profile updated successfully!');
    }

    public function removeAvatar()
    {
        $this->profile->setAvatar(null);
        session()->flash('message', 'Avatar removed successfully!');
    }

    public function render()
    {
        return view('livewire.profile-component');
    }
}