<?php

namespace App\Http\Controllers\Tenant;

use App\Http\Controllers\Controller;
use App\Models\ClientFile;
use App\Models\ClinicalHistory;
use App\Models\ConsentForm;
use App\Models\Customer;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Illuminate\View\View;

class ClinicalHistoryController extends Controller
{
    public function index(): View
    {
        $customers = Customer::with('clinicalHistory')
            ->latest('updated_at')
            ->paginate(12);

        return view('tenant.clinical-histories.index', compact('customers'));
    }

    public function show(Customer $customer): View
    {
        $history = $customer->clinicalHistory()
            ->with(['notes.author', 'treatments', 'conditions', 'consents.employee', 'files.uploader'])
            ->firstOrCreate([], [
                'created_by' => auth()->id(),
            ]);

        return view('tenant.clinical-histories.show', compact('customer', 'history'));
    }

    public function update(Request $request, Customer $customer): RedirectResponse
    {
        $data = $request->validate([
            'allergies' => ['nullable', 'string'],
            'diseases' => ['nullable', 'string'],
            'current_medications' => ['nullable', 'string'],
            'previous_procedures' => ['nullable', 'string'],
            'contraindications' => ['nullable', 'string'],
            'skin_sensitivity' => ['nullable', 'string'],
            'special_conditions' => ['nullable', 'string'],
            'medical_notes' => ['nullable', 'string'],
            'skin_type' => ['nullable', 'string', 'max:50'],
            'hair_type' => ['nullable', 'string', 'max:50'],
            'current_color' => ['nullable', 'string', 'max:100'],
            'formulas_used' => ['nullable', 'string'],
            'treatments_done' => ['nullable', 'string'],
            'initial_diagnosis' => ['nullable', 'string'],
            'treatment_evolution' => ['nullable', 'string'],
            'internal_notes' => ['nullable', 'string'],
        ]);

        $customer->clinicalHistory()->updateOrCreate([], $data + [
            'created_by' => auth()->id(),
            'updated_by' => auth()->id(),
        ]);

        return back()->with('success', 'Historial clínico actualizado.');
    }

    public function storeNote(Request $request, Customer $customer): RedirectResponse
    {
        $data = $request->validate([
            'title' => ['nullable', 'string', 'max:255'],
            'content' => ['required', 'string'],
            'tags' => ['nullable', 'string', 'max:255'],
            'is_private' => ['nullable', 'boolean'],
        ]);

        $history = $customer->clinicalHistory()->firstOrCreate([], [
            'created_by' => auth()->id(),
        ]);

        $history->notes()->create([
            'title' => $data['title'] ?? null,
            'content' => $data['content'],
            'tags' => collect(explode(',', (string) ($data['tags'] ?? '')))
                ->map(fn ($tag) => trim($tag))
                ->filter()
                ->values()
                ->all(),
            'is_private' => $request->boolean('is_private'),
            'created_by' => auth()->id(),
        ]);

        return back()->with('success', 'Nota clínica agregada.');
    }

    public function storeConsent(Request $request, Customer $customer): RedirectResponse
    {
        $data = $request->validate([
            'title' => ['required', 'string', 'max:255'],
            'content' => ['required', 'string'],
            'signer_name' => ['nullable', 'string', 'max:255'],
            'signer_document' => ['nullable', 'string', 'max:50'],
            'status' => ['required', 'in:pending,signed,rejected,expired'],
            'document' => ['nullable', 'file', 'mimes:pdf,jpg,jpeg,png,webp', 'max:4096'],
        ]);

        $history = $customer->clinicalHistory()->firstOrCreate([], [
            'created_by' => auth()->id(),
        ]);

        if ($request->hasFile('document')) {
            $data['document_path'] = $request->file('document')->store('consents', 'public');
        }

        $history->consents()->create([
            'company_id' => $history->company_id,
            'title' => $data['title'],
            'content' => $data['content'],
            'document_path' => $data['document_path'] ?? null,
            'signer_name' => $data['signer_name'] ?? null,
            'signer_document' => $data['signer_document'] ?? null,
            'status' => $data['status'],
            'signed_ip' => $data['status'] === 'signed' ? $request->ip() : null,
            'signed_user_agent' => $data['status'] === 'signed' ? $request->userAgent() : null,
            'signed_at' => $data['status'] === 'signed' ? now() : null,
        ]);

        return back()->with('success', 'Consentimiento guardado.');
    }

    public function storeFile(Request $request, Customer $customer): RedirectResponse
    {
        $data = $request->validate([
            'file' => ['required', 'file', 'max:10240'],
            'type' => ['required', 'in:photo,document,prescription,authorization,evidence,other'],
            'title' => ['nullable', 'string', 'max:255'],
            'description' => ['nullable', 'string', 'max:1000'],
            'tags' => ['nullable', 'string', 'max:255'],
            'is_private' => ['nullable', 'boolean'],
        ]);

        $history = $customer->clinicalHistory()->firstOrCreate([], [
            'created_by' => auth()->id(),
        ]);

        $file = $request->file('file');
        $history->files()->create([
            'company_id' => $history->company_id,
            'uploaded_by' => auth()->id(),
            'type' => $data['type'],
            'title' => $data['title'] ?? null,
            'description' => $data['description'] ?? null,
            'path' => $file->store('client-files', 'public'),
            'original_name' => $file->getClientOriginalName(),
            'mime_type' => $file->getMimeType() ?: 'application/octet-stream',
            'size_bytes' => $file->getSize() ?: 0,
            'is_private' => $request->boolean('is_private', true),
            'tags' => collect(explode(',', (string) ($data['tags'] ?? '')))
                ->map(fn ($tag) => trim($tag))
                ->filter()
                ->values()
                ->all(),
        ]);

        return back()->with('success', 'Archivo adjuntado.');
    }

    public function downloadFile(Customer $customer, ClientFile $file)
    {
        abort_unless($file->history?->customer_id === $customer->id, 404);

        return Storage::disk('public')->download($file->path, $file->original_name);
    }

    public function deleteFile(Customer $customer, ClientFile $file): RedirectResponse
    {
        abort_unless($file->history?->customer_id === $customer->id, 404);

        Storage::disk('public')->delete($file->path);
        $file->delete();

        return back()->with('success', 'Archivo eliminado.');
    }
}
