@extends('layouts.app')

@section('content')
<div class="container-fluid py-4">
    <div class="row mb-4">
        <div class="col-12">
            <div class="d-flex justify-content-between align-items-center">
                <div>
                    <a href="{{ route('creator.social-connections.index') }}" class="btn btn-link text-decoration-none p-0 mb-2">
                        <i class="fas fa-arrow-left me-2"></i>Back to Connections
                    </a>
                    <h2 class="mb-1">{{ $connection->display_label }}</h2>
                    <p class="text-muted">Manage connection details and shared access</p>
                </div>
                <span class="badge bg-{{ $connection->status_color }} fs-6">
                    {{ ucfirst($connection->status) }}
                </span>
            </div>
        </div>
    </div>

    @if(session('success'))
        <div class="alert alert-success alert-dismissible fade show" role="alert">
            <i class="fas fa-check-circle me-2"></i>{{ session('success') }}
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
    @endif

    @if(session('error'))
        <div class="alert alert-danger alert-dismissible fade show" role="alert">
            <i class="fas fa-exclamation-circle me-2"></i>{{ session('error') }}
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
    @endif

    <div class="row">
        <!-- Connection Details -->
        <div class="col-lg-8">
            <div class="card mb-4">
                <div class="card-header">
                    <h5 class="mb-0">
                        <i class="{{ $connection->platform_icon }} me-2"></i>Connection Details
                    </h5>
                </div>
                <div class="card-body">
                    <div class="row mb-3">
                        <div class="col-md-6">
                            <label class="text-muted small">Platform</label>
                            <p class="fw-bold">{{ $connection->platform_display_name }}</p>
                        </div>
                        <div class="col-md-6">
                            <label class="text-muted small">Status</label>
                            <p><span class="badge bg-{{ $connection->status_color }}">{{ ucfirst($connection->status) }}</span></p>
                        </div>
                    </div>

                    @if($connection->platform_username)
                        <div class="row mb-3">
                            <div class="col-md-6">
                                <label class="text-muted small">Username</label>
                                <p class="fw-bold">@{{ $connection->platform_username }}</p>
                            </div>
                            <div class="col-md-6">
                                <label class="text-muted small">Display Name</label>
                                <p>{{ $connection->platform_display_name }}</p>
                            </div>
                        </div>
                    @endif

                    @if($connection->label)
                        <div class="row mb-3">
                            <div class="col-12">
                                <label class="text-muted small">Label</label>
                                <p>{{ $connection->label }}</p>
                            </div>
                        </div>
                    @endif>

                    <div class="row mb-3">
                        <div class="col-md-6">
                            <label class="text-muted small">Last Tested</label>
                            <p>{{ $connection->last_tested_at ? $connection->last_tested_at->format('M d, Y H:i') : 'Never' }}</p>
                        </div>
                        <div class="col-md-6">
                            <label class="text-muted small">Last Synced</label>
                            <p>{{ $connection->last_synced_at ? $connection->last_synced_at->format('M d, Y H:i') : 'Never' }}</p>
                        </div>
                    </div>

                    @if($connection->token_expires_at)
                        <div class="row mb-3">
                            <div class="col-12">
                                <label class="text-muted small">Token Expires</label>
                                <p>
                                    {{ $connection->token_expires_at->format('M d, Y H:i') }}
                                    @if($connection->isExpiringSoon())
                                        <span class="badge bg-warning ms-2">Expiring Soon</span>
                                    @endif
                                </p>
                            </div>
                        </div>
                    @endif

                    @if($connection->use_for_ads)
                        <div class="alert alert-info">
                            <i class="fas fa-ad me-2"></i>
                            <strong>Ad Access Enabled</strong>
                            <p class="mb-0 small">This connection is approved for advertising campaigns</p>
                        </div>
                    @endif

                    <!-- Actions -->
                    <div class="d-flex gap-2 flex-wrap mt-4">
                        <button type="button" class="btn btn-success" onclick="testConnection()">
                            <i class="fas fa-check me-2"></i>Test Connection
                        </button>
                        @if($connection->refresh_token)
                            <form action="{{ route('creator.social-connections.refresh-token', $connection) }}" method="POST" class="d-inline">
                                @csrf
                                <button type="submit" class="btn btn-info">
                                    <i class="fas fa-sync me-2"></i>Refresh Token
                                </button>
                            </form>
                        @endif
                        <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#shareModal">
                            <i class="fas fa-share-alt me-2"></i>Share with Brand
                        </button>
                        <button type="button" class="btn btn-danger" data-bs-toggle="modal" data-bs-target="#deleteModal">
                            <i class="fas fa-trash me-2"></i>Delete Connection
                        </button>
                    </div>
                </div>
            </div>

            <!-- Shared Access -->
            <div class="card">
                <div class="card-header">
                    <h5 class="mb-0">
                        <i class="fas fa-users me-2"></i>Shared Access
                    </h5>
                </div>
                <div class="card-body">
                    @if($connection->sharedAccess->isEmpty())
                        <p class="text-muted text-center py-4">
                            <i class="fas fa-info-circle me-2"></i>
                            This connection is not shared with any brands yet
                        </p>
                    @else
                        <div class="table-responsive">
                            <table class="table">
                                <thead>
                                    <tr>
                                        <th>Brand</th>
                                        <th>Access Level</th>
                                        <th>Granted</th>
                                        <th>Expires</th>
                                        <th>Status</th>
                                        <th>Actions</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    @foreach($connection->sharedAccess as $shared)
                                        <tr>
                                            <td>
                                                <strong>{{ $shared->brand->name }}</strong>
                                                @if($shared->campaign)
                                                    <br><small class="text-muted">Campaign: {{ $shared->campaign->name }}</small>
                                                @endif
                                            </td>
                                            <td>
                                                <span class="badge bg-info">{{ $shared->access_level_display }}</span>
                                            </td>
                                            <td>{{ $shared->granted_at->format('M d, Y') }}</td>
                                            <td>
                                                {{ $shared->expires_at->format('M d, Y') }}
                                                @if($shared->isExpiringSoon())
                                                    <br><small class="text-warning">Expiring soon</small>
                                                @endif
                                            </td>
                                            <td>
                                                <span class="badge bg-{{ $shared->status_color }}">{{ ucfirst($shared->status) }}</span>
                                            </td>
                                            <td>
                                                @if($shared->isValid())
                                                    <button type="button" class="btn btn-sm btn-danger" onclick="revokeAccess({{ $shared->id }})">
                                                        <i class="fas fa-times me-1"></i>Revoke
                                                    </button>
                                                @else
                                                    <span class="text-muted small">-</span>
                                                @endif
                                            </td>
                                        </tr>
                                    @endforeach
                                </tbody>
                            </table>
                        </div>
                    @endif
                </div>
            </div>
        </div>

        <!-- Sidebar -->
        <div class="col-lg-4">
            <!-- Security Info -->
            <div class="card mb-4">
                <div class="card-header">
                    <h6 class="mb-0">
                        <i class="fas fa-shield-alt me-2"></i>Security
                    </h6>
                </div>
                <div class="card-body">
                    <p class="small text-muted mb-2">
                        <i class="fas fa-lock me-2"></i>Your credentials are encrypted at rest
                    </p>
                    <p class="small text-muted mb-2">
                        <i class="fas fa-eye-slash me-2"></i>Tokens are never displayed in full
                    </p>
                    <p class="small text-muted mb-0">
                        <i class="fas fa-history me-2"></i>All actions are logged for audit
                    </p>
                </div>
            </div>

            <!-- Quick Stats -->
            <div class="card">
                <div class="card-header">
                    <h6 class="mb-0">
                        <i class="fas fa-chart-bar me-2"></i>Quick Stats
                    </h6>
                </div>
                <div class="card-body">
                    <div class="d-flex justify-content-between mb-3">
                        <span class="text-muted">Active Shares</span>
                        <strong>{{ $connection->activeSharedAccess->count() }}</strong>
                    </div>
                    <div class="d-flex justify-content-between mb-3">
                        <span class="text-muted">Total Shares</span>
                        <strong>{{ $connection->sharedAccess->count() }}</strong>
                    </div>
                    <div class="d-flex justify-content-between">
                        <span class="text-muted">Created</span>
                        <strong>{{ $connection->created_at->format('M d, Y') }}</strong>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Share with Brand Modal -->
<div class="modal fade" id="shareModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <form action="{{ route('creator.social-connections.share', $connection) }}" method="POST">
                @csrf
                <div class="modal-header">
                    <h5 class="modal-title">Share Connection with Brand</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <div class="mb-3">
                        <label class="form-label">Select Brand *</label>
                        <select name="brand_id" class="form-select" required>
                            <option value="">Choose a brand...</option>
                            @foreach(\App\Models\Brand::all() as $brand)
                                <option value="{{ $brand->id }}">{{ $brand->name }}</option>
                            @endforeach
                        </select>
                    </div>

                    <div class="mb-3">
                        <label class="form-label">Campaign (Optional)</label>
                        <select name="campaign_id" class="form-select">
                            <option value="">No specific campaign</option>
                            <!-- Campaigns will be loaded dynamically based on brand selection -->
                        </select>
                    </div>

                    <div class="mb-3">
                        <label class="form-label">Access Level *</label>
                        <select name="access_level" class="form-select" required>
                            <option value="read_only">Read Only - View profile and posts</option>
                            <option value="read_write">Read & Write - View and publish content</option>
                            <option value="full">Full Access - Complete account management</option>
                        </select>
                    </div>

                    <div class="mb-3">
                        <label class="form-label">Permissions *</label>
                        <div class="form-check">
                            <input class="form-check-input" type="checkbox" name="scopes[]" value="read_profile" id="scope1" checked>
                            <label class="form-check-label" for="scope1">View Profile</label>
                        </div>
                        <div class="form-check">
                            <input class="form-check-input" type="checkbox" name="scopes[]" value="read_posts" id="scope2" checked>
                            <label class="form-check-label" for="scope2">View Posts</label>
                        </div>
                        <div class="form-check">
                            <input class="form-check-input" type="checkbox" name="scopes[]" value="read_analytics" id="scope3">
                            <label class="form-check-label" for="scope3">View Analytics</label>
                        </div>
                        <div class="form-check">
                            <input class="form-check-input" type="checkbox" name="scopes[]" value="publish_content" id="scope4">
                            <label class="form-check-label" for="scope4">Publish Content</label>
                        </div>
                    </div>

                    <div class="mb-3">
                        <label class="form-label">Access Duration (Days) *</label>
                        <select name="expiry_days" class="form-select" required>
                            <option value="7">7 days</option>
                            <option value="30" selected>30 days</option>
                            <option value="60">60 days</option>
                            <option value="90">90 days</option>
                            <option value="180">180 days</option>
                            <option value="365">1 year</option>
                        </select>
                    </div>

                    <div class="alert alert-info">
                        <i class="fas fa-info-circle me-2"></i>
                        <strong>Note:</strong> You can revoke access at any time. Both you and the brand will be notified when access is granted or revoked.
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-primary">
                        <i class="fas fa-share-alt me-2"></i>Share Access
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Delete Confirmation Modal -->
<div class="modal fade" id="deleteModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Confirm Deletion</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <p>Are you sure you want to delete this connection?</p>
                <p class="text-danger"><strong>Warning:</strong> This will revoke all shared access with brands and cannot be undone.</p>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                <form action="{{ route('creator.social-connections.destroy', $connection) }}" method="POST" style="display: inline;">
                    @csrf
                    @method('DELETE')
                    <button type="submit" class="btn btn-danger">Delete Connection</button>
                </form>
            </div>
        </div>
    </div>
</div>

<!-- Revoke Access Modal -->
<div class="modal fade" id="revokeModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <form id="revokeForm" method="POST">
                @csrf
                <div class="modal-header">
                    <h5 class="modal-title">Revoke Access</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <p>Are you sure you want to revoke this brand's access?</p>
                    <div class="mb-3">
                        <label class="form-label">Reason (Optional)</label>
                        <textarea name="reason" class="form-control" rows="3" placeholder="Provide a reason for revocation..."></textarea>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-danger">Revoke Access</button>
                </div>
            </form>
        </div>
    </div>
</div>

@push('scripts')
<script>
function testConnection() {
    const btn = event.target;
    const originalHtml = btn.innerHTML;
    btn.disabled = true;
    btn.innerHTML = '<i class="fas fa-spinner fa-spin me-2"></i>Testing...';

    fetch('{{ route('creator.social-connections.test', $connection) }}', {
        method: 'POST',
        headers: {
            'X-CSRF-TOKEN': '{{ csrf_token() }}',
            'Content-Type': 'application/json',
            'Accept': 'application/json'
        }
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            alert('Connection test successful!');
            location.reload();
        } else {
            alert('Connection test failed: ' + data.message);
        }
    })
    .catch(error => {
        alert('Error testing connection: ' + error.message);
    })
    .finally(() => {
        btn.disabled = false;
        btn.innerHTML = originalHtml;
    });
}

function revokeAccess(sharedAccessId) {
    const form = document.getElementById('revokeForm');
    form.action = `/creator/social-connections/shared-access/${sharedAccessId}/revoke`;
    const modal = new bootstrap.Modal(document.getElementById('revokeModal'));
    modal.show();
}
</script>
@endpush
@endsection