<?php

namespace App\Http\Controllers\User;

use App\Http\Controllers\Controller;
use App\Models\ContactQuery;
use App\Models\SkinAnalysis;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;
use Illuminate\Validation\ValidationException;
use Illuminate\View\View;

class UserPageController extends Controller
{
    public function dashboard(): View
    {
        return view('user.pages.dashboard');
    }

    public function about(): View
    {
        return view('user.pages.about');
    }

    public function checker(): View
    {
        $analyses = auth()->check()
            ? auth()->user()->skinAnalyses()->latest()->take(5)->get()
            : collect();

        return view('user.pages.checker', compact('analyses'));
    }

    public function diseases(): View
    {
        return view('user.pages.diseases');
    }

    public function book(): View
    {
        return view('user.pages.book');
    }

    public function contact(): View
    {
        return view('user.pages.contact');
    }

    public function history(): View
    {
        $analyses = auth()->user()->skinAnalyses()->latest()->paginate(12);

        return view('user.pages.history', compact('analyses'));
    }

    public function analyze(Request $request): RedirectResponse
    {
        $validated = $request->validate([
            'file' => ['required', 'image', 'mimes:jpg,jpeg,png', 'max:5120'],
        ]);

        $file = $validated['file'];
        $originalFilename = $file->getClientOriginalName();
        $fileContents = file_get_contents($file->getRealPath());

        try {
            $response = Http::baseUrl(config('services.ml_service.base_url'))
                ->timeout(60)
                ->acceptJson()
                ->attach('file', $fileContents, $originalFilename)
                ->post('/predict')
                ->throw()
                ->json();
        } catch (\Throwable $exception) {
            throw ValidationException::withMessages([
                'file' => 'Analysis service is unavailable right now. Please try again in a moment.',
            ]);
        }

        $disease = $response['disease'] ?? null;
        $confidence = $response['confidence'] ?? null;

        if (! is_string($disease) || ! is_numeric($confidence)) {
            throw ValidationException::withMessages([
                'file' => 'Analysis service returned an unexpected response.',
            ]);
        }

        $directory = public_path('uploads/skin-analysis');

        if (! is_dir($directory)) {
            mkdir($directory, 0755, true);
        }

        $storedFilename = uniqid('skin_', true).'.'.$file->getClientOriginalExtension();
        $file->move($directory, $storedFilename);
        $storedPath = 'uploads/skin-analysis/'.$storedFilename;

        SkinAnalysis::create([
            'user_id' => auth()->id(),
            'original_filename' => $originalFilename,
            'image_path' => $storedPath,
            'disease' => $disease,
            'confidence' => (float) $confidence,
            'api_response' => $response,
        ]);

        return redirect()
            ->route('checker')
            ->with('analysis_result', [
                'disease' => $disease,
                'confidence' => (float) $confidence,
                'image_url' => asset($storedPath),
            ])
            ->with('status', 'Image analyzed successfully.');
    }

    public function storeContact(Request $request): RedirectResponse
    {
        $validated = $request->validate([
            'name' => ['required', 'string', 'max:255'],
            'email' => ['required', 'email', 'max:255'],
            'phone' => ['nullable', 'string', 'max:50'],
            'message' => ['required', 'string', 'max:5000'],
        ]);

        ContactQuery::create([
            'user_id' => auth()->id(),
            'name' => $validated['name'],
            'email' => $validated['email'],
            'phone' => $validated['phone'] ?: null,
            'message' => $validated['message'],
            'status' => 'Unread',
        ]);

        return back()->with('status', 'Your inquiry has been submitted successfully.');
    }
}
