<?php

namespace App\Http\Controllers;

use App\Enums\PostStatus;
use App\Enums\PostType;
use App\Enums\StatusEnum;
use App\Http\Requests\PostUpdateRequest;
use App\Http\Requests\SocialPostRequest;
use App\Http\Services\AnalyticsService;
use App\Models\AiSetting;
use App\Models\Platform;
use App\Models\SocialAccount;
use App\Models\SocialPost;
use App\Traits\Fileable;
use App\Traits\ModelAction;
use App\Traits\PostManager;
use Illuminate\Http\Request;

use Inertia\Inertia;

class PostController extends Controller
{
    protected $user, $workspace, $analyticsService;

    use Fileable, ModelAction, PostManager;

    public function __construct(AnalyticsService $analyticsService)
    {
        $this->user = auth_user();
        $this->workspace = current_workspace();
        $this->analyticsService = new AnalyticsService();
    }

    public function create()
    {
        $media = $this->getMedia($this->user);
        $templates = $this->getTemplates($this->user);
        $aiTemplates = $this->getAiTemplates($this->user);

        $map = ['text_ai' => 'text', 'image_ai' => 'image', 'video_ai' => 'video'];

        // Get connected accounts for actual use
        $connectedAccounts = SocialAccount::with('platform')
            ->where('user_id', $this->user->id)
            ->when($this->workspace, function ($query) {
                return $query->where('workspace_id', $this->workspace->id);
            })
            ->active()
            ->connected()
            ->get();

        // Get all accounts to check if any exist at all (regardless of connection status)
        // Don't filter by workspace for checking if accounts exist
        $allAccounts = SocialAccount::with('platform')
            ->where('user_id', $this->user->id)
            ->get();

        return Inertia::render("Post/Index", [
            "platforms" => Platform::all(),
            "accounts" => $connectedAccounts,
            "all_accounts" => $allAccounts,
            'media' => $media,
            'post_templates' => $templates,
            'ai_templates' => $aiTemplates,
            'ai_modules' => AiSetting::all()->mapWithKeys(fn($s) => [
                $key = $map[$s->module] ?? $s->module => [
                    'model' => $s->config['model'] ?? null,
                    'name' => ucfirst($key) . ' Module'
                ]
            ])
        ]);
    }

    public function store(SocialPostRequest $request)
    {
        try {
            $insertedPosts = $this->savePosts($request->validated(), auth()->user());

            return redirect()->back()->with('success', 'Post(s) created successfully!');
        } catch (\Exception $e) {
            return redirect()->back()->with('error', 'Something went wrong while creating the post.');
        }
    }

    public function reschedule(Request $request)
    {
        $request->validate([
            'id' => 'required|exists:social_posts,id'
        ]);

        SocialPost::find($request->input('id'))->update([
            'schedule_time' => $request->input('schedule_time'),
            'is_scheduled' => StatusEnum::true->status(),
        ]);

        return redirect()->back()->with('success', 'Post re-scheduled successfully!');
    }

    /**
     * store a new post
     *
     * @param string $uid
     * @return
     */
    public function send(Request $request)
    {
        $request->validate([
            'id' => 'required|exists:social_posts,id'
        ]);

        $post = SocialPost::where('id', $request->input('id'))->with(['files'])
            ->where('status', '!=', (string) PostStatus::SUCCESS->value)
            ->firstOrFail();


        $this->publishPost($post);
        return back()->with('success', 'The resend operation was successful. Please review the response status.');


    }

    public function preview($id)
    {
        $post = SocialPost::with(['account', 'platform', 'files', 'metrics'])
            ->findOrFail($id);

        $formattedPost = [
            'id' => $post->id,
            'author' => $post->account?->name ?? 'Unknown',
            'avatar' => $post->account?->avatar ?? null,
            'content' => $post->content,
            'postType' => PostType::tryFrom($post->post_type)?->name ?? 'FEED',
            'status' => PostStatus::tryFrom($post->status)?->name ?? 'PENDING',
            'dateGroup' => optional($post->schedule_time ?? $post->posted_at ?? $post->created_at)
                ->format('Y-m-d\TH:i:s\Z'),
            'date' => $post->schedule_time ?? $post->posted_at ?? $post->created_at,
            'platform' => $post->platform,
            'platform_slug' => $post->platform?->slug,
            'account' => [
                'name' => $post->account?->name,
                'avatar' => $post->account?->avatar ?? null,
            ],
            'media' => $post->files->map(fn($file) => [
                'id' => $file->id,
                'url' => imageURL($file, 'gallery'),
                'thumbnail' => imageURL($file, 'gallery'),
                'alt' => $file->pivot->alt ?? $file->name,
                'isVideo' => (getFileTypeFromExtension($file->extension) === 'video'),
            ])->toArray(),
            'metrics' => $post->metrics ? [
                'impressions' => $post->metrics->impressions ?? 0,
                'engagements' => $post->metrics->engagements ?? 0,
                'reactions' => $post->metrics->reactions ?? 0,
                'likes' => $post->metrics->likes ?? 0,
                'comments' => $post->metrics->comments ?? 0,
                'shares' => $post->metrics->shares ?? 0,
                'reach' => $post->metrics->reach ?? 0,
            ] : null,
            'engagement' => [
                'reactions' => ['like' => $post->metrics->likes ?? 0],
                'comments' => $post->metrics->comments ?? 0,
                'shares' => $post->metrics->shares ?? 0,
            ],
        ];


        return Inertia::render('Post/Preview', [
            'post' => $formattedPost,
            'AnalyticalData' => $this->analyticsService->getAnalytics(),
        ]);

    }

    public function edit($id)
    {
        $media = $this->getMedia($this->user);
        $templates = $this->getTemplates($this->user);
        $aiTemplates = $this->getAiTemplates($this->user);


        $post = SocialPost::with(['account.platform', 'files'])->findOrFail($id);

        $postData = [
            'id' => $post->id,
            'postTypes' => [
                strtolower($post->platform?->slug ?? 'unknown') => strtolower(
                    PostType::tryFrom($post->post_type)?->name ?? 'feed'
                ),
            ],
            'content' => $post->content,
            'files' => $post->files->map(fn($file) => [
                'id' => $file->id,
                'url' => imageURL($file, 'gallery'),
                'caption' => $file->pivot->caption,
                'alt' => $file->pivot->alt,
                'order' => $file->pivot->order,
            ])->values() ?? [],
            'links' => $post->links ?? [],
            'active_platform' => $post->platform?->slug ?? 'facebook',
            'is_scheduled' => $post->is_scheduled ?? '0',
            'scheduled_time' => $post->schedule_time,
            'is_draft' => $post->is_draft ?? '0',
        ];

        return Inertia::render('Post/Edit', [
            'post' => $postData,
            'media' => $media,
            'post_templates' => $templates,
            'ai_templates' => $aiTemplates,
            "platforms" => Platform::all(),
        ]);


    }

    public function update(PostUpdateRequest $request)
    {
        $data = $request->validated();
        $user = $this->user;

        $postId = $data['id'] ?? null;

        if (!$postId) {
            return back()->with('error', 'Post ID is required.');
        }

        $post = $this->updateSinglePost($postId, $data, $user);

        return back()->with('success', 'Post updated successfully!');
    }

    public function allPosts(Request $request)
    {
        $platforms = Platform::active()->get();
        $accounts = SocialAccount::with('platform')
            ->where('user_id', $this->user->id)
            ->where('workspace_id', $this->workspace->id)
            ->active()
            ->get();

        $postsQuery = SocialPost::with(['account.platform', 'files', 'metrics'])
            ->where('user_id', $this->user->id);

        // Filter by account IDs if provided
        if ($request->has('account_ids') && !empty($request->account_ids)) {
            $postsQuery->whereIn('account_id', $request->account_ids);
        }

        // Filter by tab key
        if ($request->has('tab_key') && $request->tab_key !== 'all') {
            switch ($request->tab_key) {
                case 'upcoming':
                    $postsQuery->where('status', PostStatus::SCHEDULE->value)
                        ->where('schedule_time', '>', now());
                    break;
                case 'past':
                    $postsQuery->where('status', PostStatus::SUCCESS->value)
                        ->orWhere(function ($query) {
                            $query->where('status', PostStatus::SCHEDULE->value)
                                ->where('schedule_time', '<=', now());
                        });
                    break;
                case 'drafts':
                    $postsQuery->where('is_draft', true);
                    break;
            }
        }

        // Search functionality
        if ($request->has('search') && !empty($request->search)) {
            $postsQuery->where('content', 'like', '%' . $request->search . '%');
        }

        // Filter by platform if provided
        if ($request->has('platform') && !empty($request->platform)) {
            $postsQuery->whereHas('account.platform', function ($query) use ($request) {
                $query->where('slug', $request->platform);
            });
        }

        $posts = $postsQuery->latest()
            ->paginate(20)
            ->through(function ($post) {
                // Parse platform_response to extract failure reason
                $failedReason = null;
                if ($post->platform_response) {
                    $response = json_decode($post->platform_response, true);
                    if (is_array($response) && isset($response['response'])) {
                        $failedReason = $response['response'];
                    }
                }

                return [
                    'id' => $post->id,
                    'author' => $post->account?->name ?? 'Unknown',
                    'avatar' => $post->account?->avatar ?? null,
                    'content' => $post->content,
                    'postType' => PostType::tryFrom($post->post_type)?->name ?? 'FEED',
                    'status' => PostStatus::tryFrom($post->status)?->name ?? 'PENDING',
                    'failedReason' => $failedReason,
                    'failedReasonFallback' => translate("Reason unknown"),
                    'dateGroup' => optional($post->schedule_time ?? $post->posted_at ?? $post->created_at)->format('Y-m-d\TH:i:s\Z'),
                    'date' => $post->schedule_time ?? $post->posted_at ?? $post->created_at,
                    'platform' => $post->platform,
                    'platform_slug' => $post->platform?->slug,
                    'account' => [
                        'name' => $post->account?->name,
                        'avatar' => $post->account?->avatar ?? null,
                    ],
                    'media' => $post->files->map(fn($file) => [
                        'id' => $file->id,
                        'url' => imageURL($file, 'gallery'),
                        'thumbnail' => imageURL($file, 'gallery'),
                        'alt' => $file->pivot->alt ?? $file->name,
                        'isVideo' => (getFileTypeFromExtension($file->extension) === 'video'),
                    ])->toArray(),
                    'metrics' => $post->metrics ? [
                        'impressions' => $post->metrics->impressions ?? 0,
                        'engagements' => $post->metrics->engagements ?? 0,
                        'reactions' => $post->metrics->reactions ?? 0,
                        'likes' => $post->metrics->likes ?? 0,
                        'comments' => $post->metrics->comments ?? 0,
                        'shares' => $post->metrics->shares ?? 0,
                        'reach' => $post->metrics->reach ?? 0,
                    ] : null,
                    'engagement' => [
                        'reactions' => ['like' => $post->metrics->likes ?? 0],
                        'comments' => $post->metrics->comments ?? 0,
                        'shares' => $post->metrics->shares ?? 0,
                    ],
                ];
            });

        return Inertia::render('AllPosts', [
            'platforms' => $platforms,
            'accounts' => $accounts,
            'posts' => $posts->items(),
            'pagination' => [
                'current_page' => $posts->currentPage(),
                'last_page' => $posts->lastPage(),
                'per_page' => $posts->perPage(),
                'total' => $posts->total(),
                'has_more_pages' => $posts->hasMorePages(),
                'next_page_url' => $posts->nextPageUrl(),
                'prev_page_url' => $posts->previousPageUrl(),
            ],
        ]);
    }

}
