<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Episode;
use App\Models\Movie;
use App\Models\Subtitle;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Validator;

class SubtitleController extends Controller
{
    /**
     * Show add-subtitle form (for modal).
     */
    public function add(string $type, int $videoId)
    {
        $model = match ($type) {
            'movie' => Movie::class,
            'episode' => Episode::class,
            default => abort(404, 'Invalid type'),
        };
        $model::findOrFail($videoId);

        return view('admin.subtitles.add', [
            'type'    => $type,
            'videoId' => $videoId,
        ]);
    }

    /**
     * List subtitles for a movie or episode (separate page, like download links).
     */
    public function index(string $type, int $videoId)
    {
        $model = match ($type) {
            'movie' => Movie::class,
            'episode' => Episode::class,
            default => abort(404, 'Invalid type'),
        };

        $video = $model::findOrFail($videoId);
        $subtitles = $video->subtitles;

        return view('admin.subtitles.index', [
            'type'      => $type,
            'videoId'   => $videoId,
            'video'     => $video,
            'subtitles' => $subtitles,
        ]);
    }

    /**
     * Store a new subtitle (movie or episode).
     */
    public function store(Request $request)
    {
        if (isDemoMode()) {
            return response()->json([
                'status' => 'error',
                'message' => __('this_action_is_disabled_in_demo_mode'),
            ], 403);
        }

        $validator = Validator::make($request->all(), [
            'subtitleable_type' => 'required|in:movie,episode',
            'subtitleable_id'   => 'required|integer',
            'label'             => 'required|string|max:100',
            'language_code'     => 'nullable|string|max:10',
            'subtitle_file'     => 'required|file|max:10240',
        ]);

        if ($validator->fails()) {
            return response()->json([
                'status' => 'error',
                'message' => $validator->errors()->first(),
            ], 422);
        }

        $type = $request->subtitleable_type;
        $id   = (int) $request->subtitleable_id;

        if ($type === 'movie') {
            $model = Movie::find($id);
        } else {
            $model = Episode::find($id);
        }

        if (! $model) {
            return response()->json([
                'status'  => 'error',
                'message' => __('resource_not_found'),
            ], 404);
        }

        $file = $request->file('subtitle_file');
        $ext  = strtolower($file->getClientOriginalExtension());
        if (! in_array($ext, ['srt', 'vtt'], true)) {
            return response()->json([
                'status'  => 'error',
                'message' => __('subtitle_file_must_be_srt_or_vtt'),
            ], 422);
        }

        $dir = 'uploads/subtitles/' . $type . 's/' . $id;
        $fullDir = public_path($dir);

        if (! File::isDirectory($fullDir)) {
            File::makeDirectory($fullDir, 0755, true);
        }

        $safeLabel = preg_replace('/[^a-zA-Z0-9_-]/', '_', $request->label);
        $filename  = $safeLabel . '_' . time() . '.vtt';
        $path      = $dir . '/' . $filename;

        $content = File::get($file->getRealPath());

        if ($ext === 'srt') {
            $content = $this->srtToVtt($content);
        }

        File::put(public_path($path), $content);

        $modelClass = $type === 'movie' ? Movie::class : Episode::class;

        Subtitle::create([
            'subtitleable_type' => $modelClass,
            'subtitleable_id'   => $id,
            'label'             => $request->label,
            'language_code'     => $request->language_code ?: null,
            'file_path'         => $path,
        ]);

        return response()->json([
            'status'  => 'success',
            'message' => __('subtitle_added_successfully'),
        ]);
    }

    /**
     * Remove the specified subtitle.
     */
    public function destroy($id)
    {
        if (isDemoMode()) {
            return response()->json([
                'status' => 'error',
                'message' => __('this_action_is_disabled_in_demo_mode'),
            ], 403);
        }

        $subtitle = Subtitle::find($id);
        if (! $subtitle) {
            return response()->json([
                'status'  => 'error',
                'message' => __('resource_not_found'),
            ], 404);
        }

        $fullPath = public_path($subtitle->file_path);
        if (File::exists($fullPath)) {
            File::delete($fullPath);
        }

        $subtitle->delete();

        return response()->json([
            'status'  => 'success',
            'message' => __('subtitle_removed_successfully'),
        ]);
    }

    /**
     * Convert SRT content to WebVTT.
     */
    protected function srtToVtt(string $srt): string
    {
        $lines = preg_split('/\r\n|\r|\n/', $srt);
        $vtt   = "WEBVTT\n\n";
        $i     = 0;
        $n     = count($lines);

        while ($i < $n) {
            $line = trim($lines[$i]);
            $i++;

            if ($line === '') {
                continue;
            }

            if (preg_match('/^\d+$/', $line)) {
                if ($i < $n && preg_match('/^(\d{2}:\d{2}:\d{2})[,.](\d{3})\s*-->\s*(\d{2}:\d{2}:\d{2})[,.](\d{3})/', trim($lines[$i]), $m)) {
                    $vtt .= $m[1] . '.' . $m[2] . ' --> ' . $m[3] . '.' . $m[4] . "\n";
                    $i++;
                    while ($i < $n && trim($lines[$i]) !== '') {
                        $vtt .= trim($lines[$i]) . "\n";
                        $i++;
                    }
                    $vtt .= "\n";
                }
            }
        }

        return trim($vtt) . "\n";
    }
}
