<?php

namespace App\Http\Controllers;

use App\Models\Competition;
use App\Models\Field;
use App\Models\SchedulingMode;
use App\Models\Team;
use App\Models\User;
use Illuminate\Http\Request;
use Inertia\Inertia;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\ValidationException;

class TournamentController extends Controller
{
    /**
     * Show the form for creating a new tournament.
     *
     * @return \Inertia\Response
     */
    public function create()
    {
        return Inertia::render('tournaments/Create');
    }

    /**
     * Store a newly created tournament in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\RedirectResponse
     */
    public function store(Request $request)
    {
        // Validate the request data
        $validator = Validator::make($request->all(), [
            'name' => 'required|string|max:255',
            'description' => 'nullable|string',
            'location' => 'nullable|string|max:255',
            'start_date' => 'required|date',
            'max_teams' => 'nullable|integer|min:2',
            'status' => 'required|in:draft,public,private',
        ]);

        if ($validator->fails()) {
            return redirect()->back()->withErrors($validator)->withInput();
        }

        // Create the tournament (competition)
        $tournament = new Competition();
        $tournament->name = $request->name;
        $tournament->description = $request->description;
        $tournament->location = $request->location;
        $tournament->start_date = $request->start_date;
        $tournament->max_teams = $request->max_teams;
        $tournament->status = $request->status;
        $tournament->owner = Auth::id();
        $tournament->save();

        // Create a default scheduling mode
        $schedulingMode = new SchedulingMode();
        $schedulingMode->competition_id = $tournament->id;
        $schedulingMode->name = 'Default';
        $schedulingMode->description = 'Default scheduling mode';
        $schedulingMode->algorithm = 'round_robin';
        $schedulingMode->config = json_encode([
            'match_duration' => 90, // 90 minutes
            'break_between_matches' => 15, // 15 minutes
        ]);
        $schedulingMode->sequence_order = 1;
        $schedulingMode->status = 'active';
        $schedulingMode->save();

        // Set as current scheduling mode
        $tournament->current_scheduling_mode_id = $schedulingMode->id;
        $tournament->save();

        return redirect()->route('tournaments.show', $tournament->id)
            ->with('success', 'Tournament created successfully!');
    }

    /**
     * Display the specified tournament.
     *
     * @param  \App\Models\Competition  $tournament
     * @return \Inertia\Response
     */
    public function show(Competition $tournament)
    {
        // Load relationships
        $tournament->load(['teams', 'fields', 'matches', 'breakPeriods']);

        return Inertia::render('tournaments/Show', [
            'tournament' => $tournament,
        ]);
    }

    /**
     * Show the form for editing the specified tournament.
     *
     * @param  \App\Models\Competition  $tournament
     * @return \Inertia\Response
     */
    public function edit(Competition $tournament)
    {
        // Load relationships
        $tournament->load(['teams', 'fields']);

        // Get all fields and teams for dropdowns
        $fields = Field::all();
        $teams = Team::all();

        return Inertia::render('tournaments/Edit', [
            'tournament' => $tournament,
            'fields' => $fields,
            'teams' => $teams,
        ]);
    }

    /**
     * Update the specified tournament in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Models\Competition  $tournament
     * @return \Illuminate\Http\RedirectResponse
     */
    public function update(Request $request, Competition $tournament)
    {
        // Check if user is tournament owner
        if ($tournament->owner != Auth::id()) {
            return redirect()->back()->with('error', 'You are not authorized to edit this tournament.');
        }

        // Validate the request data
        $validator = Validator::make($request->all(), [
            'name' => 'required|string|max:255',
            'description' => 'nullable|string',
            'location' => 'nullable|string|max:255',
            'start_date' => 'required|date',
            'end_date' => 'required|date|after_or_equal:start_date',
            'registration_deadline' => 'nullable|date|before_or_equal:start_date',
            'max_teams' => 'nullable|integer|min:2',
            'status' => 'required|in:draft,public,private',
            'team_ids' => 'nullable|array',
            'team_ids.*' => 'exists:teams,id',
            'field_ids' => 'nullable|array',
            'field_ids.*' => 'exists:fields,id',
        ]);

        if ($validator->fails()) {
            return redirect()->back()->withErrors($validator)->withInput();
        }

        // Update the tournament
        $tournament->name = $request->name;
        $tournament->description = $request->description;
        $tournament->location = $request->location;
        $tournament->start_date = $request->start_date;
        $tournament->end_date = $request->end_date;
        $tournament->registration_deadline = $request->registration_deadline;
        $tournament->max_teams = $request->max_teams;
        $tournament->status = $request->status;
        $tournament->save();

        // Sync teams
        if ($request->has('team_ids')) {
            $teamSync = [];
            foreach ($request->team_ids as $teamId) {
                $teamSync[$teamId] = ['status' => 'confirmed'];
            }
            $tournament->teams()->sync($teamSync);
        }

        // Sync fields
        if ($request->has('field_ids')) {
            $tournament->fields()->sync($request->field_ids);
        }

        return redirect()->route('tournaments.show', $tournament->id)
            ->with('success', 'Tournament updated successfully!');
    }

    /**
     * Remove the specified tournament from storage.
     *
     * @param  \App\Models\Competition  $tournament
     * @return \Illuminate\Http\RedirectResponse
     */
    public function destroy(Competition $tournament)
    {
        // Check if user is tournament owner
        if ($tournament->owner != Auth::id()) {
            return redirect()->back()->with('error', 'You are not authorized to delete this tournament.');
        }

        // Delete the tournament
        $tournament->delete();

        return redirect()->route('home')
            ->with('success', 'Tournament deleted successfully!');
    }

    public function addTeam(Request $request, Competition $tournament)
    {
        Log::info($request);
        // Check if user is tournament owner
        if ($tournament->owner != Auth::id()) {
            Log::error('User is not authorized to add a team to this tournament.');
            Log::error('userId: ' . Auth::id() . ' tournamentOwnerId: ' . $tournament->owner);
            return redirect()->back()->with('error', 'You are not authorized to add a team to this tournament.');
        }

        // Validate the request data
        $validator = Validator::make($request->all(), [
            'teamName' => 'required|exists:teams,string',
        ]);

        if ($validator->fails()) {
            Log::error('Validation failed for addTeam', $validator->errors());
            return redirect()->back()->withErrors($validator)->withInput();
        }

        // Add the team
        $team = Team::find($request->team_id);
        // if it doesn't exist, create new team
        //
        if (!$team) {
            $team = new Team();
            $team->name = $request->team_name;
            $team->save();
        }
        $tournament->teams()->attach($team->id);

        return response()->json([
            'tournament' => $tournament,
        ]);
    }
}
