<?php

namespace App\Http\Controllers\Admin\Ranch;

use App\Http\Controllers\Controller;
use App\Models\Cattle;
use App\Models\FatteningLot;
use App\Services\FatteningLotService;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Inertia\Inertia;
use Inertia\Response;
use InvalidArgumentException;

class FatteningLotPageController extends Controller
{
    public function __construct(
        private readonly FatteningLotService $fatteningLotService,
    ) {}

    public function index(Request $request): Response
    {
        $query = FatteningLot::query()
            ->withCount(['activeAnimals as animals_count'])
            ->orderByDesc('entry_date');

        if ($request->filled('status')) {
            $query->where('status', $request->string('status'));
        }

        return Inertia::render('Ranch/Fattening/Index', [
            'lots' => $query->paginate(20)->withQueryString(),
            'filters' => [
                'status' => $request->get('status', ''),
            ],
        ]);
    }

    public function create(): Response
    {
        return Inertia::render('Ranch/Fattening/Form');
    }

    public function store(Request $request): RedirectResponse
    {
        $validated = $request->validate([
            'name' => ['required', 'string', 'max:150'],
            'description' => ['nullable', 'string'],
            'entry_date' => ['required', 'date'],
            'notes' => ['nullable', 'string'],
            'target_net_profit' => ['nullable', 'numeric', 'min:0'],
            'target_price_per_kg' => ['nullable', 'numeric', 'min:0'],
            'target_min_gdp_kg_per_day' => ['nullable', 'numeric', 'min:0'],
        ]);

        $lot = FatteningLot::create($validated + ['status' => FatteningLot::STATUS_OPEN]);

        return redirect()
            ->route('admin.ranch.fattening.show', $lot)
            ->with('success', 'Lote de engorda creado.');
    }

    public function show(FatteningLot $fatteningLot): Response
    {
        $fatteningLot->load(['activeAnimals.cattle', 'animals.cattle', 'expenses.materialType']);

        return Inertia::render('Ranch/Fattening/Show', [
            'lot' => $fatteningLot,
            'evaluation' => $this->fatteningLotService->evaluateLot($fatteningLot),
            'cattleOptions' => Cattle::query()->active()->orderBy('ear_tag')->get(['id', 'ear_tag']),
        ]);
    }

    public function close(Request $request, FatteningLot $fatteningLot): RedirectResponse
    {
        $validated = $request->validate([
            'exit_weights' => ['required', 'array'],
            'exit_weights.*.cattle_id' => ['required', 'integer'],
            'exit_weights.*.exit_weight_kg' => ['required', 'numeric', 'min:0.01'],
        ]);

        $map = [];
        foreach ($validated['exit_weights'] as $row) {
            $map[(int) $row['cattle_id']] = (float) $row['exit_weight_kg'];
        }

        try {
            $this->fatteningLotService->closeLot($fatteningLot, $map);
        } catch (InvalidArgumentException $e) {
            return back()->with('error', $e->getMessage());
        }

        return redirect()
            ->route('admin.ranch.fattening.show', $fatteningLot)
            ->with('success', 'Lote cerrado correctamente.');
    }

    public function addAnimal(Request $request, FatteningLot $fatteningLot): RedirectResponse
    {
        $validated = $request->validate([
            'cattle_id' => ['required_without:ear_tag', 'integer', 'exists:cattle,id'],
            'ear_tag' => ['required_without:cattle_id', 'string'],
            'entry_weight_kg' => ['required', 'numeric', 'min:0.01'],
            'entry_date' => ['nullable', 'date'],
        ]);

        $cattle = isset($validated['cattle_id'])
            ? Cattle::findOrFail($validated['cattle_id'])
            : Cattle::where('ear_tag', $validated['ear_tag'])->firstOrFail();

        try {
            $this->fatteningLotService->addAnimal(
                $fatteningLot,
                $cattle,
                (float) $validated['entry_weight_kg'],
                isset($validated['entry_date']) ? \Carbon\Carbon::parse($validated['entry_date']) : null
            );
        } catch (InvalidArgumentException $e) {
            return back()->with('error', $e->getMessage());
        }

        return back()->with('success', 'Animal agregado al lote.');
    }
}
