<?php

use Livewire\Component;
use Livewire\WithFileUploads;
use App\Models\Gallery;
use App\Models\Category;

new class extends Component
{
    use WithFileUploads;

    public $title = '';
    public $category_id = '';
    public $image_type = 'url'; // 'url' or 'file'
    public $image_url = '';
    public $image_file;

    public function render()
    {
        return $this->view()->layout('layouts::auth');
    }

    public function save()
    {
        $rules = [
            'title' => 'nullable|string|max:255',
            'category_id' => 'nullable|exists:categories,id',
        ];

        if ($this->image_type === 'url') {
            $rules['image_url'] = 'required|url';
        } else {
            $rules['image_file'] = 'required|image|max:5120';
        }

        $this->validate($rules);

        $image_path = $this->image_url;
        if ($this->image_type === 'file' && $this->image_file) {
            $image_path = app(\App\Services\ImageCompressor::class)->compress($this->image_file, 'gallery');
        }

        Gallery::create([
            'title' => $this->title ?: null,
            'category_id' => $this->category_id ?: null,
            'image_path' => $image_path,
            'sort_order' => 0,
        ]);

        session()->flash('message', 'Gallery item added successfully.');
        return $this->redirect(route('admin.gallery'), navigate: true);
    }

    public function with()
    {
        return [
            'categories' => Category::orderBy('name')->get(),
        ];
    }
};
?>

<div class="max-content">
    <header class="flex justify-between items-center mb-10">
        <div>
            <h1 class="text-2xl font-semibold tracking-tight">Add Visual Asset</h1>
            <p class="text-sm text-gray-500 mt-1">Upload or link a new image to the public gallery.</p>
        </div>
        <a href="{{ route('admin.gallery') }}" wire:navigate class="btn-secondary text-xs">Back to Gallery</a>
    </header>

    <form wire:submit.prevent="save" class="space-y-8">
        <div class="card p-8 space-y-6">
            <div>
                <label class="block text-[11px] font-bold text-gray-500 uppercase mb-2">Image Title</label>
                <input type="text" wire:model="title" class="input-field w-full" placeholder="e.g. Village Youth Circle">
                @error('title') <span class="text-red-500 text-xs mt-1">{{ $message }}</span> @enderror
            </div>

            <div>
                <label class="block text-[11px] font-bold text-gray-500 uppercase mb-2">Category</label>
                <select wire:model="category_id" class="input-field w-full">
                    <option value="">Select Category</option>
                    @foreach($categories as $category)
                        <option value="{{ $category->id }}">{{ $category->name }}</option>
                    @endforeach
                </select>
                @error('category_id') <span class="text-red-500 text-xs mt-1">{{ $message }}</span> @enderror
            </div>

            <div>
                <label class="block text-[11px] font-bold text-gray-500 uppercase mb-2">Gallery Image</label>
                <div class="flex flex-col gap-4">
                    <div class="flex gap-2 p-1 bg-gray-100 rounded-lg w-fit">
                        <button type="button" wire:click="$set('image_type', 'url')" class="px-4 py-1.5 text-xs font-semibold rounded-md {{ $image_type === 'url' ? 'bg-white shadow-sm' : 'text-gray-500' }} transition-all">URL</button>
                        <button type="button" wire:click="$set('image_type', 'file')" class="px-4 py-1.5 text-xs font-semibold rounded-md {{ $image_type === 'file' ? 'bg-white shadow-sm' : 'text-gray-500' }} transition-all">Upload File</button>
                    </div>
                    
                    @if($image_type === 'url')
                        <div>
                            <input type="text" wire:model="image_url" class="input-field w-full" placeholder="https://images.unsplash.com/...">
                            @error('image_url') <span class="text-red-500 text-xs mt-1">{{ $message }}</span> @enderror
                        </div>
                    @else
                        <div>
                            <div class="flex items-center justify-center w-full">
                                <label class="flex flex-col items-center justify-center w-full h-48 border-2 border-gray-300 border-dashed rounded-lg cursor-pointer bg-gray-50 hover:bg-gray-100 transition-colors">
                                    <div class="flex flex-col items-center justify-center pt-5 pb-6">
                                        @if($image_file)
                                            <img src="{{ $image_file->temporaryUrl() }}" class="h-32 object-contain mb-2">
                                        @else
                                            <svg class="w-8 h-8 mb-3 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M7 16a4 4 0 01-.88-7.903A5 5 0 1115.9 6L16 6a5 5 0 011 9.9M15 13l-3-3m0 0l-3 3m3-3v12"></path></svg>
                                            <p class="mb-2 text-sm text-gray-500"><span class="font-semibold">Click to upload</span> or drag and drop</p>
                                            <p class="text-xs text-gray-400">High resolution recommended (Max. 5MB)</p>
                                        @endif
                                    </div>
                                    <input type="file" wire:model="image_file" class="hidden" accept="image/*" />
                                </label>
                            </div>
                            <div wire:loading wire:target="image_file" class="text-xs text-gray-500 mt-1">Uploading...</div>
                            @error('image_file') <span class="text-red-500 text-xs mt-1">{{ $message }}</span> @enderror
                        </div>
                    @endif
                </div>
            </div>
        </div>

        <div class="flex justify-end gap-3">
            <a href="{{ route('admin.gallery') }}" wire:navigate class="px-8 py-2 border border-gray-300 text-gray-700 text-sm font-medium rounded-md hover:bg-gray-50 transition-colors">Cancel</a>
            <button type="submit" wire:loading.attr="disabled" class="px-10 py-2 bg-sage text-white text-sm font-medium rounded-md hover:bg-sage-dark transition-colors" style="background-color: #99BC85;">
                <span wire:loading.remove wire:target="save">Add to Gallery</span>
                <span wire:loading wire:target="save">Adding...</span>
            </button>
        </div>
    </form>
</div>
