<?php

namespace App\Http\Controllers\Creator;

use App\Http\Controllers\Controller;
use App\Models\SocialAccount;
use App\Services\SocialProviders\ProviderFactory;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\Validator;

class SocialController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        // Get all social accounts for the current user
        $accounts = SocialAccount::where('user_id', Auth::id())
            ->orderBy('provider')
            ->get();

        // Get supported providers
        $providers = ProviderFactory::getSupportedProviders();

        return view('creator.connections', compact('accounts', 'providers'));
    }

    /**
     * Redirect to provider for authentication.
     *
     * @param string $provider
     * @return \Illuminate\Http\RedirectResponse
     */
    public function connect($provider)
    {
        try {
            // Validate provider
            $providerInstance = ProviderFactory::make($provider);
        } catch (\InvalidArgumentException $e) {
            return redirect()->route('creator.connections.index')
                ->with('error', 'Unsupported provider: ' . $provider);
        }

        // Check if already connected
        $existingAccount = SocialAccount::where('user_id', Auth::id())
            ->where('provider', $provider)
            ->first();

        if ($existingAccount) {
            return redirect()->route('creator.connections.index')
                ->with('error', 'You are already connected to ' . $providerInstance->getName());
        }

        // Redirect to provider
        return $providerInstance->redirectToProvider(request());
    }

    /**
     * Handle the callback from the provider.
     *
     * @param string $provider
     * @return \Illuminate\Http\RedirectResponse
     */
    public function callback($provider)
    {
        try {
            // Validate provider
            $providerInstance = ProviderFactory::make($provider);
        } catch (\InvalidArgumentException $e) {
            return redirect()->route('creator.connections.index')
                ->with('error', 'Unsupported provider: ' . $provider);
        }

        try {
            // Handle callback
            $data = $providerInstance->handleCallback(request());

            // Check if already connected
            $existingAccount = SocialAccount::where('user_id', Auth::id())
                ->where('provider', $provider)
                ->where('provider_user_id', $data['user']['id'])
                ->first();

            if ($existingAccount) {
                // Update existing account
                $existingAccount->setAccessToken($data['token']['access_token']);
                
                if (isset($data['token']['refresh_token'])) {
                    $existingAccount->setRefreshToken($data['token']['refresh_token']);
                }
                
                if (isset($data['token']['expires_in'])) {
                    $existingAccount->token_expires_at = now()->addSeconds($data['token']['expires_in']);
                }
                
                $existingAccount->meta = $data['user'];
                $existingAccount->last_synced_at = null; // Reset sync status
                $existingAccount->save();

                return redirect()->route('creator.connections.index')
                    ->with('success', 'Account reconnected successfully!');
            }

            // Create new account
            $account = new SocialAccount();
            $account->user_id = Auth::id();
            $account->provider = $provider;
            $account->provider_user_id = $data['user']['id'];
            $account->setAccessToken($data['token']['access_token']);
            
            if (isset($data['token']['refresh_token'])) {
                $account->setRefreshToken($data['token']['refresh_token']);
            }
            
            if (isset($data['token']['expires_in'])) {
                $account->token_expires_at = now()->addSeconds($data['token']['expires_in']);
            }
            
            $account->meta = $data['user'];
            $account->connected_at = now();
            $account->save();

            return redirect()->route('creator.connections.index')
                ->with('success', 'Account connected successfully!');
        } catch (\Exception $e) {
            return redirect()->route('creator.connections.index')
                ->with('error', 'Failed to connect account: ' . $e->getMessage());
        }
    }

    /**
     * Store a manually entered token.
     *
     * @param \Illuminate\Http\Request $request
     * @return \Illuminate\Http\RedirectResponse
     */
    public function manualStore(Request $request)
    {
        // Validate request
        $validator = Validator::make($request->all(), [
            'provider' => 'required|string|in:' . implode(',', array_keys(ProviderFactory::getSupportedProviders())),
            'provider_user_id' => 'required|string',
            'access_token' => 'required|string',
        ]);

        if ($validator->fails()) {
            return redirect()->route('creator.connections.index')
                ->withErrors($validator)
                ->withInput();
        }

        // Validate provider
        try {
            $providerInstance = ProviderFactory::make($request->provider);
        } catch (\InvalidArgumentException $e) {
            return redirect()->route('creator.connections.index')
                ->with('error', 'Unsupported provider: ' . $request->provider);
        }

        // Check if already connected
        $existingAccount = SocialAccount::where('user_id', Auth::id())
            ->where('provider', $request->provider)
            ->where('provider_user_id', $request->provider_user_id)
            ->first();

        if ($existingAccount) {
            // Update existing account
            $existingAccount->setAccessToken($request->access_token);
            $existingAccount->meta = ['manually_added' => true];
            $existingAccount->last_synced_at = null; // Reset sync status
            $existingAccount->save();

            return redirect()->route('creator.connections.index')
                ->with('success', 'Account token updated successfully!');
        }

        // Create new account
        $account = new SocialAccount();
        $account->user_id = Auth::id();
        $account->provider = $request->provider;
        $account->provider_user_id = $request->provider_user_id;
        $account->setAccessToken($request->access_token);
        $account->meta = ['manually_added' => true];
        $account->connected_at = now();
        $account->save();

        return redirect()->route('creator.connections.index')
            ->with('success', 'Account added successfully!');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param int $id
     * @return \Illuminate\Http\RedirectResponse
     */
    public function destroy($id)
    {
        // Find the account
        $account = SocialAccount::where('user_id', Auth::id())->findOrFail($id);

        // Delete the account
        $account->delete();

        return redirect()->route('creator.connections.index')
            ->with('success', 'Account disconnected successfully!');
    }
}