<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Http\Requests\Admin\AiStaffProfileCreateRequest;
use App\Http\Requests\Admin\AiStaffProfileDestroyRequest;
use App\Http\Requests\Admin\AiStaffProfileEditRequest;
use App\Http\Requests\Admin\AiStaffProfileIndexRequest;
use App\Http\Requests\Admin\AiStaffProfileRecordsRequest;
use App\Http\Requests\Admin\AiStaffProfileStoreRequest;
use App\Http\Requests\Admin\AiStaffProfileUpdateRequest;
use App\Models\Admin;
use App\Models\AiStaffProfile;
use App\Models\TicketDepartment;
use App\Traits\LogsAdminActivity;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Str;
use Illuminate\View\View;

class AiStaffController extends Controller
{
    use LogsAdminActivity;

    /**
     * Display AI staff listing page.
     */
    public function index(AiStaffProfileIndexRequest $request): View
    {
        return view('admin.ai-staff.index');
    }

    /**
     * Show the form for creating a new AI staff profile.
     */
    public function create(AiStaffProfileCreateRequest $request): View
    {
        $departments = TicketDepartment::orderBy('name')->get();

        return view('admin.ai-staff.create', compact('departments'));
    }

    /**
     * Store a newly created AI staff profile.
     */
    public function store(AiStaffProfileStoreRequest $request)
    {
        $validated = $request->validated();

        // Create Admin record for the AI staff
        $admin = Admin::create([
            'uuid' => (string) Str::uuid(),
            'name' => $validated['name'],
            'email' => $validated['email'] ?? $this->generateAiStaffEmail($validated['name']),
            'password' => Hash::make(Str::random(32)),
            'status' => 'active',
            'email_verified' => true,
            'is_deleted' => false,
            'is_ai_staff' => true,
        ]);

        // Assign ai-staff role
        $admin->assignRole('ai-staff');

        // Convert percentage to decimal
        $confidenceThreshold = ($validated['confidence_threshold'] ?? 70) / 100;

        // Create AiStaffProfile linked to admin
        $profile = AiStaffProfile::create([
            'admin_id' => $admin->id,
            'name' => $validated['name'],
            'email' => $admin->email,
            'job_title' => $validated['job_title'] ?? null,
            'system_prompt' => $validated['system_prompt'] ?? null,
            'personality_tone' => $validated['personality_tone'],
            'humanize_enabled' => $validated['humanize_enabled'] ?? false,
            'typo_frequency' => ($validated['typo_frequency'] ?? 0) / 100,
            'confidence_threshold' => $confidenceThreshold,
            'response_delay_min' => $validated['response_delay_min'],
            'response_delay_max' => $validated['response_delay_max'],
            'working_hours_start' => $validated['working_hours_start'] ?? null,
            'working_hours_end' => $validated['working_hours_end'] ?? null,
            'working_days' => $validated['working_days'] ?? null,
            'timezone' => $validated['timezone'] ?? config('app.timezone', 'UTC'),
            'waiting_message_enabled' => $validated['waiting_message_enabled'] ?? false,
            'waiting_message_text' => $validated['waiting_message_text'] ?? null,
            'max_autonomous_replies_per_ticket' => $validated['max_autonomous_replies_per_ticket'],
            'status' => $validated['status'],
        ]);

        $this->logCreated($profile, "Created AI staff profile #{$profile->id} - {$profile->name}");

        return redirect()->route('admin.ai-staff.index')
            ->with('success', __('admin/ai-staff.messages_created'));
    }

    /**
     * Show the form for editing the specified AI staff profile.
     */
    public function edit(AiStaffProfileEditRequest $request, AiStaffProfile $aiStaffProfile): View
    {
        $aiStaff = $aiStaffProfile->load(['admin', 'departmentRules.department']);
        $departments = TicketDepartment::orderBy('name')->get();
        $departmentRules = $aiStaff->departmentRules;

        return view('admin.ai-staff.edit', compact('aiStaff', 'departments', 'departmentRules'));
    }

    /**
     * Update the specified AI staff profile.
     */
    public function update(AiStaffProfileUpdateRequest $request, AiStaffProfile $aiStaffProfile)
    {
        $validated = $request->validated();

        $confidenceThreshold = ($validated['confidence_threshold'] ?? 70) / 100;

        $aiStaffProfile->update([
            'name' => $validated['name'],
            'email' => $validated['email'] ?? $aiStaffProfile->email,
            'job_title' => $validated['job_title'] ?? $aiStaffProfile->job_title,
            'system_prompt' => $validated['system_prompt'] ?? $aiStaffProfile->system_prompt,
            'personality_tone' => $validated['personality_tone'],
            'humanize_enabled' => $validated['humanize_enabled'] ?? false,
            'typo_frequency' => ($validated['typo_frequency'] ?? 0) / 100,
            'confidence_threshold' => $confidenceThreshold,
            'response_delay_min' => $validated['response_delay_min'],
            'response_delay_max' => $validated['response_delay_max'],
            'working_hours_start' => $validated['working_hours_start'] ?? null,
            'working_hours_end' => $validated['working_hours_end'] ?? null,
            'working_days' => $validated['working_days'] ?? null,
            'timezone' => $validated['timezone'] ?? $aiStaffProfile->timezone,
            'waiting_message_enabled' => $validated['waiting_message_enabled'] ?? false,
            'waiting_message_text' => $validated['waiting_message_text'] ?? null,
            'max_autonomous_replies_per_ticket' => $validated['max_autonomous_replies_per_ticket'],
            'status' => $validated['status'],
        ]);

        // Sync admin name and email
        $aiStaffProfile->admin->update([
            'name' => $validated['name'],
            'email' => $validated['email'] ?? $aiStaffProfile->email,
        ]);

        $this->logUpdated($aiStaff, "Updated AI staff profile #{$aiStaffProfile->id} - {$aiStaffProfile->name}");

        return redirect()->route('admin.ai-staff.index')
            ->with('success', __('admin/ai-staff.messages_updated'));
    }

    /**
     * Remove the specified AI staff profile.
     */
    public function destroy(AiStaffProfileDestroyRequest $request, AiStaffProfile $aiStaffProfile): JsonResponse
    {
        $this->logDeleted($aiStaff, "Deleted AI staff profile #{$aiStaffProfile->id} - {$aiStaffProfile->name}");

        // Delete profile only; admin record stays for historical replies
        $aiStaffProfile->delete();

        return response()->json([
            'success' => true,
            'message' => __('admin/ai-staff.messages_deleted'),
        ]);
    }

    /**
     * Get records for DataTables.
     */
    public function records(AiStaffProfileRecordsRequest $request): JsonResponse
    {
        $query = AiStaffProfile::with(['admin', 'departmentRules.department']);

        // Total count before filtering
        $totalRecords = AiStaffProfile::count();

        // Search
        if ($request->filled('search.value')) {
            $searchValue = $request->input('search.value');
            $query->where(function ($q) use ($searchValue) {
                $q->where('name', 'like', "%{$searchValue}%")
                    ->orWhere('job_title', 'like', "%{$searchValue}%")
                    ->orWhere('email', 'like', "%{$searchValue}%");
            });
        }

        $filteredRecords = $query->count();

        // Ordering
        $orderColumn = 'id';
        $orderDir = 'desc';

        if ($request->has('order') && isset($request->input('order')[0])) {
            $order = $request->input('order')[0];
            $columns = ['id', 'name', 'job_title', 'status', null, 'created_at'];

            $colIndex = $order['column'] ?? 0;
            if (isset($columns[$colIndex]) && $columns[$colIndex] !== null) {
                $orderColumn = $columns[$colIndex];
                $orderDir = $order['dir'] ?? 'desc';
            }
        }

        $query->orderBy($orderColumn, $orderDir);

        // Pagination
        $start = $request->input('start', 0);
        $length = $request->input('length', 10);

        $profiles = $query->skip($start)->take($length)->get();

        $data = [];
        foreach ($profiles as $profile) {
            $departmentNames = $profile->departmentRules
                ->filter(fn ($rule) => $rule->enabled && $rule->department)
                ->pluck('department.name')
                ->values()
                ->toArray();

            $data[] = [
                'id' => $profile->id,
                'name' => $profile->name,
                'job_title' => $profile->job_title,
                'status' => $profile->status,
                'departments' => $departmentNames,
                'created_at' => $profile->created_at->format('d.m.Y H:i'),
            ];
        }

        return response()->json([
            'draw' => (int) $request->input('draw'),
            'recordsTotal' => $totalRecords,
            'recordsFiltered' => $filteredRecords,
            'data' => $data,
        ]);
    }

    /**
     * Toggle AI staff profile status between active and paused.
     */
    public function toggleStatus(AiStaffProfile $aiStaffProfile): JsonResponse
    {
        $oldStatus = $aiStaffProfile->status;
        $newStatus = $oldStatus === 'active' ? 'paused' : 'active';

        $aiStaffProfile->update(['status' => $newStatus]);

        $this->logUpdated($aiStaff, "Toggled AI staff profile #{$aiStaffProfile->id} status from {$oldStatus} to {$newStatus}");

        return response()->json([
            'success' => true,
            'status' => $newStatus,
            'message' => __('admin/ai-staff.messages_status_updated'),
        ]);
    }

    /**
     * Generate a unique email for AI staff.
     */
    private function generateAiStaffEmail(string $name): string
    {
        $slug = Str::slug($name, '.');

        return "ai.{$slug}." . Str::random(4) . '@staff.internal';
    }
}
