<?php

namespace App\Http\Controllers;

use App\Models\Technology;
use Illuminate\Http\Request;

class TechnologyController extends Controller
{
    public function store(Request $request)
    {
        $validated = $request->validate([
            'name' => 'required|string|max:255|unique:technologies,name',
            'icon' => 'nullable|string|max:255',
            'color' => ['nullable', 'regex:/^#?(?:[0-9A-Fa-f]{3}|[0-9A-Fa-f]{6})$/'],
            'selected_technologies' => 'nullable|array',
            'selected_technologies.*' => 'nullable',
        ]);

        $color = $validated['color'] ?? null;

        if (!empty($color) && strpos($color, '#') !== 0) {
            $color = '#' . $color;
        }

        $technology = Technology::create([
            'name' => $validated['name'],
            'icon' => $validated['icon'] ?? null,
            'color' => $color,
        ]);

        if ($request->expectsJson() || $request->ajax()) {
            $selectedTechnologies = collect($request->input('selected_technologies', []))
                ->map(function ($id) {
                    return (string) $id;
                })
                ->push((string) $technology->id)
                ->unique()
                ->values()
                ->all();

            $technologyOptionsHtml = view('projects._technology_options', [
                'technologies' => Technology::withCount('projects')->get(),
                'selectedTechnologies' => $selectedTechnologies,
                'allowTechnologyDelete' => true,
            ])->render();

            return response()->json([
                'message' => 'Technology created successfully.',
                'technology' => [
                    'id' => $technology->id,
                    'name' => $technology->name,
                    'icon' => $technology->icon,
                    'color' => $technology->color,
                ],
                'technologyOptionsHtml' => $technologyOptionsHtml,
            ]);
        }

        return redirect()
            ->back()
            ->with('success', 'Technology created successfully.');
    }

    public function destroy(Request $request, $id)
    {
        $technology = Technology::withCount('projects')->findOrFail($id);

        $validated = $request->validate([
            'selected_technologies' => 'nullable|array',
            'selected_technologies.*' => 'nullable',
        ]);

        $selectedTechnologies = collect($validated['selected_technologies'] ?? [])
            ->map(function ($value) {
                return (string) $value;
            })
            ->reject(function ($value) use ($technology) {
                return $value === (string) $technology->id;
            })
            ->values()
            ->all();

        if ($technology->projects_count > 0) {
            $message = 'This technology is already used by a project, so it cannot be deleted here.';

            if ($request->expectsJson() || $request->ajax()) {
                return response()->json([
                    'message' => $message,
                ], 422);
            }

            return redirect()
                ->back()
                ->with('error', $message);
        }

        $technology->delete();

        if ($request->expectsJson() || $request->ajax()) {
            $technologyOptionsHtml = view('projects._technology_options', [
                'technologies' => Technology::withCount('projects')->get(),
                'selectedTechnologies' => $selectedTechnologies,
                'allowTechnologyDelete' => true,
            ])->render();

            return response()->json([
                'message' => 'Technology deleted successfully.',
                'technologyOptionsHtml' => $technologyOptionsHtml,
            ]);
        }

        return redirect()
            ->back()
            ->with('success', 'Technology deleted successfully.');
    }
}
