<?php

namespace App\Http\Controllers\Public;

use App\Http\Controllers\Controller;
use App\Models\AuctionVehicle;
use App\Models\AuctionHouse;
use App\Models\SeoMeta;
use App\Services\Auction\AuctionService;
use App\Services\Calculator\BangladeshLandedCostCalculator;
use App\Services\SEO\SchemaGenerator;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class AuctionController extends Controller
{
    protected AuctionService $auctionService;
    protected BangladeshLandedCostCalculator $calculator;

    public function __construct(
        AuctionService $auctionService,
        BangladeshLandedCostCalculator $calculator
    ) {
        $this->auctionService = $auctionService;
        $this->calculator = $calculator;
    }

    public function index(Request $request)
    {
        $query = AuctionVehicle::with('auctionHouse')->active();

        if ($request->filled('auction_house_id')) {
            $query->where('auction_house_id', $request->auction_house_id);
        }
        if ($request->filled('make')) {
            $query->where('make', $request->make);
        }
        if ($request->filled('model')) {
            $query->where('model', 'like', '%' . $request->model . '%');
        }
        if ($request->filled('year')) {
            $query->where('year', $request->year);
        }
        if ($request->filled('grade')) {
            $query->where('auction_grade', $request->grade);
        }
        if ($request->filled('fuel_type')) {
            $query->where('fuel_type', 'like', '%' . $request->fuel_type . '%');
        }
        if ($request->filled('max_starting_bid_jpy')) {
            $query->where('starting_bid_jpy', '<=', (float) $request->max_starting_bid_jpy);
        }

        // Sorting
        $sortBy = $request->get('sort', 'closing_soon');
        match ($sortBy) {
            'starting_bid_asc' => $query->orderBy('starting_bid_jpy', 'asc'),
            'starting_bid_desc' => $query->orderBy('starting_bid_jpy', 'desc'),
            'year_desc' => $query->orderBy('year', 'desc'),
            'mileage_asc' => $query->orderBy('mileage', 'asc'),
            default => $query->orderBy('auction_ends_at', 'asc'),
        };

        $auctionVehicles = $query->paginate(12)->withQueryString();

        $auctionHouses = AuctionHouse::where('is_active', true)->get();
        $makes = AuctionVehicle::distinct()->pluck('make')->filter();
        $grades = AuctionVehicle::distinct()->orderBy('auction_grade', 'desc')->pluck('auction_grade')->filter();
        $years = AuctionVehicle::distinct()->orderBy('year', 'desc')->pluck('year')->filter();

        $seo = SeoMeta::where('url_path', '/auction')->first();

        return view('public.auction', compact(
            'auctionVehicles',
            'auctionHouses',
            'makes',
            'grades',
            'years',
            'seo'
        ));
    }

    public function show(string $auctionId)
    {
        $vehicle = AuctionVehicle::with('auctionHouse', 'bids.user')
            ->where('slug', $auctionId)
            ->orWhere('id', $auctionId)
            ->orWhere('lot_number', $auctionId)
            ->firstOrFail();

        $vehicle->increment('views_count');

        // Calculate detailed landed cost breakdown for current starting bid
        $costEstimate = $this->calculator->calculate([
            'price_jpy' => $vehicle->starting_bid_jpy,
            'engine_cc' => $vehicle->engine_cc,
            'fuel_type' => $vehicle->fuel_type,
            'is_hybrid' => str_contains(strtolower($vehicle->fuel_type), 'hybrid'),
            'year' => $vehicle->year,
        ]);

        $similarLots = AuctionVehicle::with('auctionHouse')
            ->where('id', '!=', $vehicle->id)
            ->where('make', $vehicle->make)
            ->active()
            ->take(4)
            ->get();

        $schemaJson = SchemaGenerator::auctionVehicle($vehicle);

        return view('public.auction-show', compact('vehicle', 'costEstimate', 'similarLots', 'schemaJson'));
    }

    public function placeBid(Request $request, string $auctionId)
    {
        if (!Auth::check()) {
            return response()->json([
                'success' => false,
                'requires_auth' => true,
                'redirect_url' => route('login'),
                'message' => 'Please login or create an account to authorize a bid.',
            ], 401);
        }

        $vehicle = AuctionVehicle::where('id', $auctionId)
            ->orWhere('lot_number', $auctionId)
            ->firstOrFail();

        $validated = $request->validate([
            'max_bid_jpy' => 'required|numeric|min:' . $vehicle->starting_bid_jpy,
            'terms' => 'accepted',
            'notes' => 'nullable|string|max:500',
        ]);

        $result = $this->auctionService->submitCustomerBid(
            Auth::user(),
            $vehicle,
            (float) $validated['max_bid_jpy'],
            ['notes' => $validated['notes'] ?? null]
        );

        if (!$result['success']) {
            if ($request->wantsJson()) {
                return response()->json($result, 422);
            }
            return back()->with('error', $result['message']);
        }

        if ($request->wantsJson()) {
            return response()->json([
                'success' => true,
                'message' => $result['message'],
                'bid_code' => $result['bid']->bid_code,
                'redirect_url' => route('customer.bids.index'),
            ]);
        }

        return redirect()->route('customer.bids.index')->with('success', $result['message']);
    }
}
