<?php

namespace App\Http\Controllers;

use App\Models\EmailTemplate;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Inertia\Inertia;
use Inertia\Response;

class TemplateController extends Controller
{
    public function index(Request $request): Response
    {
        $tab = $request->input('tab', 'my'); // 'my' or 'builtin'
        $perPage = (int) $request->input('per_page', 20);

        $query = EmailTemplate::query();

        if ($tab === 'builtin') {
            $query = EmailTemplate::withoutGlobalScope(\App\Models\Scopes\TenantScope::class)->where('is_builtin', true);
        } else {
            $query = EmailTemplate::query()->where(function ($q) {
                $q->where('is_builtin', false)->orWhereNull('is_builtin');
            });
        }

        if ($search = trim($request->input('search', ''))) {
            $query->where(function ($q) use ($search) {
                $q->where('title', 'like', "%{$search}%")
                  ->orWhere('email_subject', 'like', "%{$search}%");
            });
        }

        $sortField = $request->input('sort', 'id');
        $sortDir = $request->input('direction', 'desc');

        if (in_array($sortField, ['id', 'title', 'created_at'])) {
            $query->orderBy($sortField, strtolower($sortDir) === 'asc' ? 'asc' : 'desc');
        } else {
            $query->orderByDesc('id');
        }

        $templates = $query->paginate($perPage)->withQueryString();

        $builtinTemplates = EmailTemplate::withoutGlobalScope(\App\Models\Scopes\TenantScope::class)
            ->where('is_builtin', true)
            ->get();

        $customTemplates = EmailTemplate::query()
            ->where(fn($q) => $q->where('is_builtin', false)->orWhereNull('is_builtin'))
            ->orderByDesc('id')
            ->get();

        return Inertia::render('Templates/Index', [
            'templates' => $templates,
            'builtinTemplates' => $builtinTemplates,
            'customTemplates' => $customTemplates,
            'filters'   => [
                'search'   => $search,
                'tab'      => $tab,
                'per_page' => $perPage,
                'sort'     => $sortField,
                'direction'=> $sortDir,
            ],
            'counts'    => [
                'my'      => EmailTemplate::where(fn($q) => $q->where('is_builtin', false)->orWhereNull('is_builtin'))->count(),
                'builtin' => EmailTemplate::withoutGlobalScope(\App\Models\Scopes\TenantScope::class)->where('is_builtin', true)->count(),
            ]
        ]);
    }

    public function create(Request $request): Response
    {
        $templateData = null;
        if ($fromId = $request->input('from_template')) {
            $src = EmailTemplate::withoutGlobalScope(\App\Models\Scopes\TenantScope::class)->find($fromId);
            if ($src) {
                $templateData = [
                    'title'            => $src->title . ' (Customized)',
                    'email_subject'    => $src->email_subject,
                    'email_pre_header' => $src->email_pre_header,
                    'email_body'       => $src->email_body,
                ];
            }
        }

        $builtinTemplates = EmailTemplate::withoutGlobalScope(\App\Models\Scopes\TenantScope::class)
            ->where('is_builtin', true)
            ->get();

        $customTemplates = EmailTemplate::query()
            ->where(fn($q) => $q->where('is_builtin', false)->orWhereNull('is_builtin'))
            ->orderByDesc('id')
            ->get();

        return Inertia::render('Templates/Create', [
            'template' => $templateData,
            'builtinTemplates' => $builtinTemplates,
            'customTemplates' => $customTemplates,
        ]);
    }

    public function store(Request $request): RedirectResponse
    {
        $validated = $request->validate([
            'title'            => 'required|string|max:255',
            'email_subject'    => 'nullable|string|max:255',
            'email_pre_header' => 'nullable|string|max:255',
            'email_body'       => 'nullable|array',
            'is_builtin'       => 'nullable|boolean',
        ]);

        $template = EmailTemplate::create([
            'user_id'          => auth()->id(),
            'title'            => $validated['title'],
            'email_subject'    => $validated['email_subject'] ?? null,
            'email_pre_header' => $validated['email_pre_header'] ?? null,
            'email_body'       => $validated['email_body'] ?? [],
            'is_builtin'       => $validated['is_builtin'] ?? false,
            'created_by'       => auth()->user()?->name ?? 'User',
        ]);

        if ($request->input('stay')) {
            return redirect()->route('templates.edit', $template->id)->with('success', 'Template saved successfully.');
        }

        return redirect()->route('templates.index')->with('success', 'Template created successfully.');
    }

    public function edit(EmailTemplate $template): Response
    {
        $builtinTemplates = EmailTemplate::withoutGlobalScope(\App\Models\Scopes\TenantScope::class)
            ->where('is_builtin', true)
            ->get();

        $customTemplates = EmailTemplate::query()
            ->where(fn($q) => $q->where('is_builtin', false)->orWhereNull('is_builtin'))
            ->orderByDesc('id')
            ->get();

        return Inertia::render('Templates/Create', [
            'template' => [
                'id'               => $template->id,
                'title'            => $template->title,
                'email_subject'    => $template->email_subject,
                'email_pre_header' => $template->email_pre_header,
                'email_body'       => $template->email_body,
                'is_builtin'       => $template->is_builtin,
                'created_at'       => $template->created_at?->toDateTimeString(),
            ],
            'builtinTemplates' => $builtinTemplates,
            'customTemplates' => $customTemplates,
        ]);
    }

    public function update(Request $request, EmailTemplate $template): RedirectResponse
    {
        $validated = $request->validate([
            'title'            => 'required|string|max:255',
            'email_subject'    => 'nullable|string|max:255',
            'email_pre_header' => 'nullable|string|max:255',
            'email_body'       => 'nullable|array',
            'is_builtin'       => 'nullable|boolean',
        ]);

        $template->update([
            'title'            => $validated['title'],
            'email_subject'    => $validated['email_subject'] ?? null,
            'email_pre_header' => $validated['email_pre_header'] ?? null,
            'email_body'       => $validated['email_body'] ?? [],
            'is_builtin'       => $validated['is_builtin'] ?? $template->is_builtin,
        ]);

        if ($request->input('stay')) {
            return redirect()->route('templates.edit', $template->id)->with('success', 'Template saved successfully.');
        }

        return redirect()->route('templates.index')->with('success', 'Template updated successfully.');
    }

    public function duplicate(EmailTemplate $template): RedirectResponse
    {
        $replica = EmailTemplate::create([
            'user_id'          => auth()->id(),
            'title'            => $template->title . ' (Copy)',
            'email_subject'    => $template->email_subject,
            'email_pre_header' => $template->email_pre_header,
            'email_body'       => $template->email_body,
            'is_builtin'       => false,
            'created_by'       => auth()->user()?->name ?? 'User',
        ]);

        return redirect()->route('templates.index')->with('success', 'Template duplicated successfully.');
    }

    public function destroy(EmailTemplate $template): RedirectResponse
    {
        $template->delete();

        return redirect()->route('templates.index')->with('success', 'Template deleted successfully.');
    }

    public function bulkDestroy(Request $request): RedirectResponse
    {
        $request->validate([
            'ids'   => 'required|array',
            'ids.*' => 'integer|exists:email_templates,id',
        ]);

        EmailTemplate::whereIn('id', $request->input('ids'))->delete();

        return redirect()->route('templates.index')->with('success', 'Templates deleted successfully.');
    }

    public function import(Request $request): RedirectResponse
    {
        $request->validate([
            'file' => 'required|file|mimes:json,txt',
        ]);

        $content = file_get_contents($request->file('file')->getRealPath());
        $data = json_decode($content, true);

        if (!$data || !is_array($data)) {
            return redirect()->back()->withErrors(['file' => 'Invalid JSON template format.']);
        }

        EmailTemplate::create([
            'user_id'          => auth()->id(),
            'title'            => $data['title'] ?? 'Imported Template',
            'email_subject'    => $data['email_subject'] ?? '',
            'email_pre_header' => $data['email_pre_header'] ?? '',
            'email_body'       => $data['email_body'] ?? [],
            'is_builtin'       => false,
            'created_by'       => auth()->user()?->name ?? 'User',
        ]);

        return redirect()->route('templates.index')->with('success', 'Template imported successfully.');
    }

    public function sendTest(Request $request, \App\Services\EmailRenderer $renderer): JsonResponse
    {
        $request->validate([
            'email'         => 'required|email|max:255',
            'title'         => 'required|string|max:255',
            'email_subject' => 'nullable|string|max:255',
            'blocks'        => 'required|array',
        ]);

        $blocks = $request->input('blocks') ?? [];
        $html = $renderer->render($blocks);

        try {
            $smtp = \App\Services\SmtpConfigService::getDefault();
            if ($smtp) {
                \App\Services\SmtpConfigService::configureRuntime($smtp);
            }

            $emailSettings = \App\Services\BusinessSettings::emailSettings();
            
            $fromEmail = $emailSettings['from_email'] ?: ($smtp?->from_email ?: config('mail.from.address'));
            $fromName  = $emailSettings['from_name'] ?: ($smtp?->from_name ?: config('mail.from.name'));
            $replyEmail = $emailSettings['reply_to_email'] ?: $fromEmail;
            $replyName  = $emailSettings['reply_to_name'] ?: $fromName;

            \Illuminate\Support\Facades\Mail::to($request->input('email'))
                ->send(new \App\Mail\TemplateTestMail(
                    $request->input('title'),
                    $request->input('email_subject') ?? 'Test Email',
                    $html,
                    $fromEmail,
                    $fromName,
                    $replyEmail,
                    $replyName
                ));
        } catch (\Exception $e) {
            return response()->json(['success' => false, 'message' => $e->getMessage()], 422);
        }

        return response()->json(['success' => true]);
    }

    public function apiIndex(): JsonResponse
    {
        $templates = EmailTemplate::query()
            ->where('is_builtin', false)
            ->orWhereNull('is_builtin')
            ->orderByDesc('id')
            ->get();
        return response()->json($templates);
    }
}
