<?php

use App\Models\Gallery;
use App\Models\Province;
use Livewire\Volt\Component;
use Livewire\WithFileUploads;
use Intervention\Image\ImageManager;
use Intervention\Image\Drivers\Gd\Driver;
use Illuminate\Support\Facades\Storage;

new class extends Component {

    use WithFileUploads;

    public ?Gallery $gallery = null;

    public $gallery_category_id;
    public $isFromCategory = false;

    public $title;
    public $description;
    public $hashtags;
    public $province_id;
    public $image;
    public $status = 'published';
    public $pin = 'false';
    public string $provinceSearch = '';

    public function mount(?Gallery $gallery = null)
    {
        $this->gallery = $gallery;

        // detect dari category
        if (request('category_id')) {

            $this->isFromCategory = true;
            $this->gallery_category_id = request('category_id');

            $category = \App\Models\GalleryCategory::find($this->gallery_category_id);

            // auto set province dari category
            if ($category) {
                $this->province_id = $category->province_id;
            }
        }

        if ($gallery) {
            $this->title = $gallery->title;
            $this->description = $gallery->description;
            $this->hashtags = $gallery->hashtags;
            $this->province_id = $gallery->province_id;
            $this->pin = $gallery->pin;
            $this->status = $gallery->status;
            $this->gallery_category_id = $gallery->gallery_category_id;

            // kalau edit dan punya category → treat as from category
            if ($gallery->gallery_category_id) {
                $this->isFromCategory = true;
            }
        }
    }

    protected function rules()
    {
        return [
            'title' => 'required|string|max:255',
            'description' => 'nullable|string',
            'hashtags' => 'nullable|string',

            // penting
            'province_id' => $this->isFromCategory
                ? 'nullable'
                : 'required|exists:provinces,id',

            'pin' => 'required|in:true,false',
            'status' => 'required|in:draft,published',

            'image' => $this->gallery
                ? 'nullable|image|mimes:jpg,jpeg,png,webp|max:15360'
                : 'required|image|mimes:jpg,jpeg,png,webp|max:15360',
        ];
    }

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

        if ($this->gallery) {
            $this->update();
        } else {
            $this->store();
        }
    }

    /* ===========================
        STORE
    ============================ */

    protected function store()
    {
        [$originalPath, $thumbPath] = $this->handleImageUpload();

        Gallery::create([
            'title' => $this->title,
            'description' => $this->description,
            'hashtags' => $this->hashtags,
            'province_id' => $this->province_id,
            'gallery_category_id' => $this->gallery_category_id,
            'user_id' => auth()->id(),
            'image' => $originalPath,
            'thumbnail' => $thumbPath,
            'pin' => $this->pin,
            'status' => $this->status,
        ]);

        return redirect()->route(
            $this->gallery_category_id
                ? 'gallerycategories.show'
                : 'galleries.index',
            $this->gallery_category_id
            )->with('notify', [
                'type' => 'success',
                'message' => 'Image Gallery created successfully.'
            ]);
    }

    /* ===========================
        UPDATE
    ============================ */
    protected function update()
    {
        $originalPath = $this->gallery->image;
        $thumbPath = $this->gallery->thumbnail;

        if ($this->image) {

            // delete old files
            $this->deleteOldImages();

            [$originalPath, $thumbPath] = $this->handleImageUpload();
        }

        $this->gallery->update([
            'title' => $this->title,
            'description' => $this->description,
            'hashtags' => $this->hashtags,
            'province_id' => $this->province_id,
            'gallery_category_id' => $this->gallery_category_id,
            'image' => $originalPath,
            'thumbnail' => $thumbPath,
            'pin' => $this->pin,
            'status' => $this->status,
        ]);

        return redirect()->route(
            $this->gallery_category_id
                ? 'gallerycategories.show'
                : 'galleries.index',
            $this->gallery_category_id
        );
    }

    /* ===========================
        IMAGE HANDLER
    ============================ */
    protected function handleImageUpload(): array
    {
        $manager = new ImageManager(new Driver());

        $filename = uniqid() . '.' . $this->image->getClientOriginalExtension();

        // Store original
        $originalPath = $this->image->storeAs('gallery', $filename, 'public');

        // Ensure thumbs folder exists
        Storage::disk('public')->makeDirectory('gallery/thumbs');

        // Read image from public storage
        $image = $manager->read(public_path("storage/{$originalPath}"));

        // Create square thumbnail
        $image->cover(300, 300);

        $thumbPath = "gallery/thumbs/{$filename}";

        $image->save(public_path("storage/{$thumbPath}"));

        return [$originalPath, $thumbPath];
    }

    protected function deleteOldImages()
    {
        Storage::disk('public')->delete($this->gallery->image);
        Storage::disk('public')->delete($this->gallery->thumbnail);
    }

    public function with()
    {
        return [
            'provinces' => Province::query()
                ->when($this->provinceSearch, function ($query) {
                    $query->where('name', 'like', '%' . $this->provinceSearch . '%');
                })
                ->orderBy('island_id', 'asc')
                ->get()
        ];
    }

};
?>

<div class="space-y-6 max-w-xl">

    <flux:heading size="xl">
        {{ $gallery ? 'Edit Image Gallery' : 'Add Image Gallery' }}
    </flux:heading>

    <flux:card>

        <form wire:submit.prevent="submit" class="space-y-4">

            <flux:input label="Title" wire:model="title" />

            @if($isFromCategory)
                <div class="text-sm text-gray-300">
                    Category:
                    <strong>
                        {{ \App\Models\GalleryCategory::find($gallery_category_id)?->title }}
                    </strong>
                </div>
            @endif

            @if(!$isFromCategory)
                <flux:select label="Province" wire:model="province_id">
                    <option value="">Select Province</option>
                    @foreach($provinces as $province)
                        <option value="{{ $province->id }}">
                            {{ $province->name }}
                        </option>
                    @endforeach
                </flux:select>
            @endif

            <flux:textarea wire:model="description" hidden/>

            <flux:textarea label="Hashtags" wire:model="hashtags" class="min-h-[200px]"/>

            <div class="space-y-3">
                <label class="block text-sm font-medium">
                    Image
                </label>
                <div class="flex items-center gap-4">
                    {{-- Preview --}}
                    <div class="w-28 h-28 rounded-lg overflow-hidden bg-gray-100 border flex items-center justify-center">

                        {{-- Image baru --}}
                        @if ($image)
                            <img
                                src="{{ $image->temporaryUrl() }}"
                                class="w-full h-full object-cover"
                            >

                        {{-- Image lama saat edit --}}
                        @elseif ($gallery && $gallery->thumbnail)
                            <img
                                src="{{ asset('storage/'.$gallery->thumbnail) }}"
                                class="w-full h-full object-cover"
                            >

                        {{-- Placeholder --}}
                        @else
                            <span class="text-gray-400 text-xs text-center px-2">
                                No Image
                            </span>
                        @endif
                    </div>

                    {{-- File Input --}}
                    <div class="flex-1">
                        <input
                            type="file"
                            wire:model="image"
                            accept="image/*"
                            class="block w-full text-sm text-gray-700
                                file:mr-4 file:py-2 file:px-4
                                file:rounded-md file:border-0
                                file:text-sm file:font-medium
                                file:bg-blue-600 file:text-white
                                hover:file:bg-blue-700
                                cursor-pointer"
                        >

                        <p class="text-xs text-gray-200 mt-2">
                            JPG, PNG, WEBP • Max 10MB
                        </p>

                        {{-- Loading --}}
                        <div wire:loading wire:target="image" class="mt-2 text-sm">
                            Uploading image...
                        </div>

                        {{-- Error --}}
                        @error('image')
                            <div class="mt-1 text-sm text-red-500">
                                {{ $message }}
                            </div>
                        @enderror
                    </div>
                </div>
            </div>

            <flux:select wire:model="pin" hidden>
                <option value="true">Yes</option>
                <option value="false">No</option>
            </flux:select>

            <flux:select label="Status" wire:model="status">
                <option value="published">Published</option>
                <option value="draft">Draft</option>
            </flux:select>

            <input type="hidden" wire:model="gallery_category_id">

            <flux:button type="submit" variant="primary">
                Save
            </flux:button>

        </form>

    </flux:card>

</div>
