<?php

namespace App\Livewire\Host;

use Livewire\Component;
use Livewire\WithFileUploads;
use App\Models\Listing;
use App\Models\RentalType;
use App\Models\Location;
use App\Models\AddOn;
use App\Models\DiscountTier;
use App\Models\PickupLocation;
use Illuminate\Support\Facades\Storage;

class ListingManager extends Component
{
    use WithFileUploads;

    public $listings;
    public $showForm = false;
    public $editMode = false;
    public $listingId;

    public $rental_type_id;
    public $location_id;
    public $title;
    public $description;
    public $price_per_day;
    public $buffer_hours = 0;
    public $capacity;
    public $available_units = 1;
    public $is_available = true;
    public $is_featured = false;
    public $images = [];
    public $existingImages = [];
    public $amenities = [];
    public $availableAmenities = [];

    // Pickup locations (for cars and mobile rentals)
    public $selectedPickupLocations = [];

    // Discount tiers
    public $discountTiers = [];

    // Add-ons
    public $selectedAddOns = [];
    public $addOnCustomPrices = [];

    public function mount()
    {
        $this->loadListings();
        $this->loadAvailableAmenities();
    }

    public function loadAvailableAmenities()
    {
        // Load amenities from database grouped by rental type
        $amenities = \App\Models\Amenity::with('rentalType')
            ->active()
            ->orderBy('sort_order')
            ->orderBy('name')
            ->get()
            ->groupBy('rentalType.name');

        $this->availableAmenities = [];
        foreach ($amenities as $rentalTypeName => $amenitiesList) {
            $this->availableAmenities[$rentalTypeName] = $amenitiesList->pluck('name')->toArray();
        }
    }

    public function loadListings()
    {
        $this->listings = Listing::where('user_id', auth()->id())
            ->with(['rentalType', 'location', 'discountTiers', 'addOns', 'pickupLocations'])
            ->withCount('bookings')
            ->latest()
            ->get();
    }

    public function create()
    {
        $this->resetForm();
        $this->showForm = true;
        $this->editMode = false;
    }

    public function edit($id)
    {
        $listing = Listing::with(['discountTiers', 'addOns', 'pickupLocations'])->findOrFail($id);
        $this->listingId = $listing->id;
        $this->rental_type_id = $listing->rental_type_id;
        $this->location_id = $listing->location_id;
        $this->title = $listing->title;
        $this->description = $listing->description;
        $this->price_per_day = $listing->price_per_day;
        $this->buffer_hours = $listing->buffer_hours ?? 0;
        $this->capacity = $listing->capacity;
        $this->available_units = $listing->available_units;
        $this->is_available = $listing->is_available;
        $this->is_featured = $listing->is_featured;
        $this->existingImages = $listing->images ?? [];
        $this->amenities = $listing->amenities ?? [];

        // Load discount tiers
        $this->discountTiers = $listing->discountTiers->map(function ($tier) {
            return [
                'id' => $tier->id,
                'min_days' => $tier->min_days,
                'max_days' => $tier->max_days,
                'discount_percentage' => $tier->discount_value, // discount_value in DB, discount_percentage in form
            ];
        })->toArray();

        // Load selected add-ons and custom prices
        $this->selectedAddOns = $listing->addOns->pluck('id')->toArray();
        $this->addOnCustomPrices = [];
        foreach ($listing->addOns as $addOn) {
            if ($addOn->pivot->custom_price) {
                $this->addOnCustomPrices[$addOn->id] = $addOn->pivot->custom_price;
            }
        }

        // Load selected pickup locations
        $this->selectedPickupLocations = $listing->pickupLocations->pluck('id')->toArray();

        $this->showForm = true;
        $this->editMode = true;
    }

    public function removeExistingImage($index)
    {
        unset($this->existingImages[$index]);
        $this->existingImages = array_values($this->existingImages);
    }

    public function addDiscountTier()
    {
        $this->discountTiers[] = [
            'id' => null,
            'min_days' => '',
            'max_days' => '',
            'discount_percentage' => '',
        ];
    }

    public function removeDiscountTier($index)
    {
        unset($this->discountTiers[$index]);
        $this->discountTiers = array_values($this->discountTiers);
    }

    public function save()
    {
        $this->validate([
            'rental_type_id' => 'required|exists:rental_types,id',
            'location_id' => 'required|exists:locations,id',
            'title' => 'required|string|max:255',
            'description' => 'required|string|max:1000',
            'price_per_day' => 'required|numeric|min:0',
            'buffer_hours' => 'required|integer|min:0|max:72',
            'capacity' => 'required|integer|min:1',
            'available_units' => 'required|integer|min:1',
            'images.*' => 'nullable|image|mimes:jpg,jpeg,png,webp,avif|max:5120',
        ]);

        // Validate total image count (existing + new)
        $totalImages = count($this->existingImages) + count($this->images);
        if ($totalImages > 15) {
            session()->flash('error', 'Maximum 15 images allowed. You have ' . $totalImages . ' images.');
            return;
        }

        $data = [
            'rental_type_id' => $this->rental_type_id,
            'location_id' => $this->location_id,
            'user_id' => auth()->id(),
            'title' => $this->title,
            'description' => $this->description,
            'price_per_day' => $this->price_per_day,
            'buffer_hours' => $this->buffer_hours,
            'capacity' => $this->capacity,
            'available_units' => $this->available_units,
            'is_available' => $this->is_available,
            'is_featured' => $this->is_featured,
            'amenities' => $this->amenities,
        ];

        // Handle image uploads
        $imageUrls = $this->existingImages;

        if ($this->images) {
            // Ensure the directory exists
            $destinationPath = public_path('images' . DIRECTORY_SEPARATOR . 'listings');
            if (!file_exists($destinationPath)) {
                mkdir($destinationPath, 0755, true);
            }

            foreach ($this->images as $image) {
                // Generate unique filename
                $filename = time() . '_' . uniqid() . '.' . $image->getClientOriginalExtension();

                // Get the temporary file path
                $tempPath = $image->getRealPath();

                // Copy the file to destination
                if (copy($tempPath, $destinationPath . DIRECTORY_SEPARATOR . $filename)) {
                    // Store the URL path (always use forward slashes for URLs)
                    $imageUrls[] = '/images/listings/' . $filename;
                }
            }
        }

        $data['images'] = $imageUrls;

        if ($this->editMode) {
            $listing = Listing::findOrFail($this->listingId);
            $listing->update($data);

            // Update discount tiers
            $this->saveDiscountTiers($listing);

            // Update add-ons with custom prices
            $this->syncAddOnsWithCustomPrices($listing);

            // Sync pickup locations
            $listing->pickupLocations()->sync($this->selectedPickupLocations);

            session()->flash('message', 'Listing updated successfully!');
        } else {
            $listing = Listing::create($data);

            // Create discount tiers
            $this->saveDiscountTiers($listing);

            // Attach add-ons with custom prices
            $this->syncAddOnsWithCustomPrices($listing);

            // Attach pickup locations
            $listing->pickupLocations()->sync($this->selectedPickupLocations);

            session()->flash('message', 'Listing created successfully!');
        }

        $this->loadListings();
        $this->showForm = false;
        $this->resetForm();
    }

    protected function saveDiscountTiers($listing)
    {
        // Delete existing discount tiers if editing
        if ($this->editMode) {
            $listing->discountTiers()->delete();
        }

        // Create new discount tiers
        foreach ($this->discountTiers as $tier) {
            if (!empty($tier['min_days']) && !empty($tier['discount_percentage'])) {
                $listing->discountTiers()->create([
                    'min_days' => $tier['min_days'],
                    'max_days' => $tier['max_days'] ?: null,
                    'discount_type' => 'percentage',
                    'discount_value' => $tier['discount_percentage'],
                ]);
            }
        }
    }

    protected function syncAddOnsWithCustomPrices($listing)
    {
        $syncData = [];
        foreach ($this->selectedAddOns as $addOnId) {
            $syncData[$addOnId] = [
                'custom_price' => $this->addOnCustomPrices[$addOnId] ?? null,
            ];
        }
        $listing->addOns()->sync($syncData);
    }

    public function delete($id)
    {
        Listing::findOrFail($id)->delete();
        $this->loadListings();
    }

    public function resetForm()
    {
        $this->rental_type_id = null;
        $this->location_id = null;
        $this->title = '';
        $this->description = '';
        $this->price_per_day = '';
        $this->buffer_hours = 0;
        $this->capacity = 1;
        $this->available_units = 1;
        $this->is_available = true;
        $this->is_featured = false;
        $this->images = [];
        $this->existingImages = [];
        $this->amenities = [];
        $this->selectedPickupLocations = [];
        $this->discountTiers = [];
        $this->selectedAddOns = [];
        $this->addOnCustomPrices = [];
    }

    public function render()
    {
        // Separate admin (global) and custom (host-created) pickup locations
        $adminPickupLocations = PickupLocation::active()
            ->whereNotNull('created_by')
            ->where('created_by', '!=', auth()->id())
            ->orWhereNull('created_by')
            ->get();

        $customPickupLocations = PickupLocation::active()
            ->where('created_by', auth()->id())
            ->get();

        // Count host's custom locations for limit check
        $customLocationsCount = PickupLocation::where('created_by', auth()->id())->count();
        $canAddMoreLocations = $customLocationsCount < 3;

        return view('livewire.host.listing-manager', [
            'rentalTypes' => RentalType::all(),
            'locations' => Location::all(),
            'availableAmenities' => $this->availableAmenities,
            'availableAddOns' => AddOn::where('is_active', true)->get(),
            'adminPickupLocations' => $adminPickupLocations,
            'customPickupLocations' => $customPickupLocations,
            'customLocationsCount' => $customLocationsCount,
            'canAddMoreLocations' => $canAddMoreLocations,
        ])->layout('layouts.app');
    }
}
