<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Asset;
use App\Models\AssetCategory;
use Illuminate\Http\Request;
use Inertia\Inertia;
use Inertia\Response;

class AssetController extends Controller
{
    public function index(Request $request): Response
    {
        $query = Asset::with(['category', 'currentAssignment.user']);

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

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

        if ($request->filled('search')) {
            $query->where(function ($q) use ($request) {
                $q->where('name', 'like', '%'.$request->search.'%')
                    ->orWhere('serial_number', 'like', '%'.$request->search.'%');
            });
        }

        return Inertia::render('Admin/Assets/Index', [
            'assets' => $query->latest()->paginate(10)->withQueryString(),
            'categories' => AssetCategory::all(),
            'users' => \App\Models\User::where('status', 'active')->get(),
            'filters' => $request->only(['category_id', 'status', 'search']),
        ]);
    }

    public function create(): Response
    {
        return Inertia::render('Admin/Assets/Create', [
            'categories' => AssetCategory::all(),
            'users' => \App\Models\User::where('status', 'active')->get(),
        ]);
    }

    public function store(Request $request)
    {
        $validated = $request->validate([
            'category_id' => 'required|exists:asset_categories,id',
            'name' => 'required|string|max:255',
            'serial_number' => 'required|string|max:255|unique:assets,serial_number',
            'purchase_date' => 'required|date',
            'warranty_expiry' => 'nullable|date',
            'condition' => 'required|in:new,good,damaged',
            'status' => 'required|in:available,assigned,maintenance,retired',
            'user_id' => 'nullable|exists:users,id',
        ]);

        $asset = Asset::create($validated);

        if ($request->filled('user_id')) {
            $asset->assignments()->create([
                'user_id' => $validated['user_id'],
                'assigned_at' => now(),
            ]);
            $asset->update(['status' => 'assigned']);
        }

        return redirect()->route('admin.assets.index')->with('success', 'Asset created successfully.');
    }

    public function edit(Asset $asset): Response
    {
        return Inertia::render('Admin/Assets/Edit', [
            'asset' => $asset->load(['category', 'currentAssignment']),
            'categories' => AssetCategory::all(),
            'users' => \App\Models\User::where('status', 'active')->get(),
        ]);
    }

    public function update(Request $request, Asset $asset)
    {
        $validated = $request->validate([
            'category_id' => 'required|exists:asset_categories,id',
            'name' => 'required|string|max:255',
            'serial_number' => 'required|string|max:255|unique:assets,serial_number,'.$asset->id,
            'purchase_date' => 'required|date',
            'warranty_expiry' => 'nullable|date',
            'condition' => 'required|in:new,good,damaged',
            'status' => 'required|in:available,assigned,maintenance,retired',
            'user_id' => 'nullable|exists:users,id',
        ]);

        $currentAssignment = $asset->currentAssignment;
        $newUserId = $validated['user_id'] ?? null;

        $asset->update($validated);

        if ($currentAssignment && $currentAssignment->user_id != $newUserId) {
            // Return current assignment
            $currentAssignment->update([
                'returned_at' => now(),
                'return_condition' => $asset->condition,
            ]);

            if ($newUserId) {
                // Assign to new user
                $asset->assignments()->create([
                    'user_id' => $newUserId,
                    'assigned_at' => now(),
                ]);
                $asset->update(['status' => 'assigned']);
            } else {
                // Set status to available if it was assigned
                if ($asset->status === 'assigned') {
                    $asset->update(['status' => 'available']);
                }
            }
        } elseif (! $currentAssignment && $newUserId) {
            // Create new assignment
            $asset->assignments()->create([
                'user_id' => $newUserId,
                'assigned_at' => now(),
            ]);
            $asset->update(['status' => 'assigned']);
        }

        return redirect()->route('admin.assets.index')->with('success', 'Asset updated successfully.');
    }

    public function show(Asset $asset): Response
    {
        return Inertia::render('Admin/Assets/Show', [
            'asset' => $asset->load(['category', 'assignments.user']),
            'users' => \App\Models\User::where('status', 'active')->get(),
        ]);
    }

    public function destroy(Asset $asset)
    {
        if ($asset->status === 'assigned') {
            return back()->with('error', 'Cannot delete an assigned asset. Return it first.');
        }

        $asset->delete();

        return redirect()->route('admin.assets.index')->with('success', 'Asset deleted successfully.');
    }
}
