{% extends "base.html" %}
{% from "components/ui.html" import confirm_dialog %}

{% block content %}
<div class="flex flex-col md:flex-row justify-between items-start md:items-center mb-6">
    <div>
        <h1 class="text-2xl font-bold">{{ client.name }}</h1>
        <p class="text-text-muted-light dark:text-text-muted-dark">Client details and associated projects.</p>
    </div>
    {% if current_user.is_admin or has_any_permission(['edit_clients', 'delete_clients']) %}
    <div class="flex gap-2">
        {% if current_user.is_admin or has_permission('edit_clients') %}
        <a href="{{ url_for('clients.edit_client', client_id=client.id) }}" class="bg-primary text-white px-4 py-2 rounded-lg mt-4 md:mt-0">{{ _('Edit Client') }}</a>
        {% if client.status == 'active' %}
        <form method="POST" action="{{ url_for('clients.archive_client', client_id=client.id) }}" onsubmit="event.preventDefault(); window.showConfirm('{{ _('Mark client as Inactive?') }}', { title: '{{ _('Change Client Status') }}', confirmText: '{{ _('Change') }}' }).then(ok=>{ if(ok) this.submit(); });" class="inline">
            <input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
            <button type="submit" class="px-4 py-2 rounded-lg bg-amber-500 text-white mt-4 md:mt-0">{{ _('Mark Inactive') }}</button>
        </form>
        {% else %}
        <form method="POST" action="{{ url_for('clients.activate_client', client_id=client.id) }}" onsubmit="event.preventDefault(); window.showConfirm('{{ _('Activate client?') }}', { title: '{{ _('Activate Client') }}', confirmText: '{{ _('Activate') }}' }).then(ok=>{ if(ok) this.submit(); });" class="inline">
            <input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
            <button type="submit" class="px-4 py-2 rounded-lg bg-emerald-600 text-white mt-4 md:mt-0">{{ _('Activate') }}</button>
        </form>
        {% endif %}
        {% endif %}
        {% if (current_user.is_admin or has_permission('delete_clients')) and client.total_projects == 0 %}
        <button type="button" class="bg-red-600 text-white px-4 py-2 rounded-lg mt-4 md:mt-0"
                onclick="document.getElementById('confirmDeleteClient-{{ client.id }}').classList.remove('hidden')">
            {{ _('Delete Client') }}
        </button>
        <form id="confirmDeleteClient-{{ client.id }}-form" method="POST" action="{{ url_for('clients.delete_client', client_id=client.id) }}" class="hidden">
            <input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
        </form>
        {% endif %}
    </div>
    {% endif %}
</div>

<div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
    <!-- Left Column: Client Details -->
    <div class="lg:col-span-1 space-y-6">
        <div class="bg-card-light dark:bg-card-dark p-6 rounded-lg shadow">
            <h2 class="text-lg font-semibold mb-4">Contact Information</h2>
            <div class="space-y-4">
                <div>
                    <h3 class="text-sm font-medium text-text-muted-light dark:text-text-muted-dark">Contact Person</h3>
                    <p>{{ client.contact_person or 'N/A' }}</p>
                </div>
                <div>
                    <h3 class="text-sm font-medium text-text-muted-light dark:text-text-muted-dark">Email</h3>
                    <p>{{ client.email or 'N/A' }}</p>
                </div>
                <div>
                    <h3 class="text-sm font-medium text-text-muted-light dark:text-text-muted-dark">Phone</h3>
                    <p>{{ client.phone or 'N/A' }}</p>
                </div>
                <div>
                    <h3 class="text-sm font-medium text-text-muted-light dark:text-text-muted-dark">Address</h3>
                    <p>{{ client.address or 'N/A' }}</p>
                </div>
            </div>
        </div>
    </div>

    <!-- Right Column: Projects -->
    <div class="lg:col-span-2">
        <div class="bg-card-light dark:bg-card-dark p-6 rounded-lg shadow">
            <h2 class="text-lg font-semibold mb-4">Projects</h2>
            <div class="overflow-x-auto">
                <table class="w-full text-left">
                    <thead class="border-b border-border-light dark:border-border-dark">
                        <tr>
                            <th class="p-4">Name</th>
                            <th class="p-4">Status</th>
                            <th class="p-4">Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        {% for project in projects %}
                        <tr class="border-b border-border-light dark:border-border-dark">
                            <td class="p-4">
                                <div class="flex items-center gap-2">
                                    <span>{{ project.name }}</span>
                                    {% if project.code_display %}
                                    <span class="inline-flex items-center px-2 py-0.5 rounded text-[10px] font-semibold tracking-wide uppercase bg-gray-200 text-gray-800 dark:bg-gray-700 dark:text-gray-200">{{ project.code_display }}</span>
                                    {% endif %}
                                </div>
                            </td>
                            <td class="p-4">
                                {% set status_map = {
                                    'active':   {'cls': 'bg-green-100 text-green-700 dark:bg-green-900/30 dark:text-green-300', 'label': _('Active')},
                                    'inactive': {'cls': 'bg-amber-100 text-amber-700 dark:bg-amber-900/30 dark:text-amber-300', 'label': _('Inactive')},
                                    'archived': {'cls': 'bg-gray-100 text-gray-700 dark:bg-gray-700 dark:text-gray-200', 'label': _('Archived')},
                                } %}
                                {% set st = status_map.get(project.status, status_map['inactive']) %}
                                <span class="px-2 py-1 rounded-full text-xs font-medium whitespace-nowrap {{ st.cls }}">{{ st.label }}</span>
                            </td>
                            <td class="p-4">
                                <a href="{{ url_for('projects.view_project', project_id=project.id) }}" class="text-primary hover:underline">View</a>
                            </td>
                        </tr>
                        {% else %}
                        <tr>
                            <td colspan="3" class="p-4 text-center text-text-muted-light dark:text-text-muted-dark">No projects found for this client.</td>
                        </tr>
                        {% endfor %}
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<!-- Client Notes Section -->
<div class="mt-6">
    <div class="bg-card-light dark:bg-card-dark p-6 rounded-lg shadow">
        <div class="flex justify-between items-center mb-4">
            <h2 class="text-lg font-semibold">{{ _('Internal Notes') }}</h2>
            <button type="button" id="addNoteBtn" class="bg-primary text-white px-4 py-2 rounded-lg text-sm hover:bg-opacity-90 transition">
                {{ _('Add Note') }}
            </button>
        </div>
        
        <!-- Add Note Form (Hidden by default) -->
        <div id="addNoteForm" class="hidden mb-6 p-4 bg-gray-50 dark:bg-gray-800 rounded-lg border border-border-light dark:border-border-dark">
            <form method="POST" action="{{ url_for('client_notes.create_note', client_id=client.id) }}">
                <input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
                <div class="mb-4">
                    <label for="note-content" class="block text-sm font-medium mb-2">{{ _('Note Content') }}</label>
                    <textarea 
                        name="content" 
                        id="note-content" 
                        class="w-full px-3 py-2 border border-border-light dark:border-border-dark rounded-lg bg-background-light dark:bg-background-dark focus:ring-2 focus:ring-primary focus:border-transparent" 
                        rows="4" 
                        required
                        placeholder="{{ _('Add an internal note about this client...') }}"
                    ></textarea>
                </div>
                <div class="mb-4">
                    <label class="flex items-center">
                        <input 
                            type="checkbox" 
                            name="is_important" 
                            value="true" 
                            class="w-4 h-4 text-primary border-gray-300 rounded focus:ring-primary focus:ring-2"
                        >
                        <span class="ml-2 text-sm">{{ _('Mark as important') }}</span>
                    </label>
                </div>
                <div class="flex gap-2">
                    <button type="submit" class="px-4 py-2 bg-primary text-white rounded-lg text-sm hover:bg-opacity-90 transition">
                        {{ _('Save Note') }}
                    </button>
                    <button type="button" id="cancelNoteBtn" class="px-4 py-2 bg-gray-200 dark:bg-gray-700 text-gray-700 dark:text-gray-200 rounded-lg text-sm hover:bg-opacity-90 transition">
                        {{ _('Cancel') }}
                    </button>
                </div>
            </form>
        </div>
        
        <!-- Notes List -->
        <div id="notesList" class="space-y-4">
            {% if client.notes %}
                {% for note in client.notes|sort(attribute='created_at', reverse=True) %}
                <div class="p-4 bg-background-light dark:bg-background-dark rounded-lg border border-border-light dark:border-border-dark {% if note.is_important %}border-l-4 border-l-amber-500{% endif %}">
                    <div class="flex justify-between items-start mb-2">
                        <div class="flex items-center gap-2">
                            <div class="w-8 h-8 rounded-full bg-primary text-white flex items-center justify-center text-sm font-semibold">
                                {{ (note.author_name)[0].upper() }}
                            </div>
                            <div>
                                <div class="font-medium">{{ note.author_name }}</div>
                                <div class="text-xs text-text-muted-light dark:text-text-muted-dark">
                                    {{ note.created_at.strftime('%B %d, %Y at %I:%M %p') }}
                                    {% if note.created_at != note.updated_at %}
                                    <span class="ml-1">({{ _('edited') }})</span>
                                    {% endif %}
                                </div>
                            </div>
                            {% if note.is_important %}
                            <span class="inline-flex items-center px-2 py-0.5 rounded text-xs font-medium bg-amber-100 text-amber-800 dark:bg-amber-900/30 dark:text-amber-300">
                                <svg class="w-3 h-3 mr-1" fill="currentColor" viewBox="0 0 20 20">
                                    <path d="M9.049 2.927c.3-.921 1.603-.921 1.902 0l1.07 3.292a1 1 0 00.95.69h3.462c.969 0 1.371 1.24.588 1.81l-2.8 2.034a1 1 0 00-.364 1.118l1.07 3.292c.3.921-.755 1.688-1.54 1.118l-2.8-2.034a1 1 0 00-1.175 0l-2.8 2.034c-.784.57-1.838-.197-1.539-1.118l1.07-3.292a1 1 0 00-.364-1.118L2.98 8.72c-.783-.57-.38-1.81.588-1.81h3.461a1 1 0 00.951-.69l1.07-3.292z"></path>
                                </svg>
                                {{ _('Important') }}
                            </span>
                            {% endif %}
                        </div>
                        {% if note.can_edit(current_user) %}
                        <div class="flex gap-2">
                            <button type="button" 
                                    class="text-sm text-blue-600 dark:text-blue-400 hover:underline"
                                    onclick="toggleImportant({{ note.id }}, {{ 'true' if not note.is_important else 'false' }})">
                                {% if note.is_important %}{{ _('Unmark') }}{% else %}{{ _('Mark Important') }}{% endif %}
                            </button>
                            <a href="{{ url_for('client_notes.edit_note', client_id=client.id, note_id=note.id) }}" 
                               class="text-sm text-primary hover:underline">
                                {{ _('Edit') }}
                            </a>
                            {% if note.can_delete(current_user) %}
                            <form method="POST" 
                                  action="{{ url_for('client_notes.delete_note', client_id=client.id, note_id=note.id) }}" 
                                  class="inline"
                                  onsubmit="return confirm('{{ _('Are you sure you want to delete this note?') }}');">
                                <input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
                                <button type="submit" class="text-sm text-red-600 dark:text-red-400 hover:underline">
                                    {{ _('Delete') }}
                                </button>
                            </form>
                            {% endif %}
                        </div>
                        {% endif %}
                    </div>
                    <div class="text-sm whitespace-pre-wrap">{{ note.content }}</div>
                </div>
                {% endfor %}
            {% else %}
            <div class="text-center py-8 text-text-muted-light dark:text-text-muted-dark">
                <svg class="w-12 h-12 mx-auto mb-2 opacity-50" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"></path>
                </svg>
                <p>{{ _('No notes yet. Add a note to keep track of important information about this client.') }}</p>
            </div>
            {% endif %}
        </div>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    const addNoteBtn = document.getElementById('addNoteBtn');
    const addNoteForm = document.getElementById('addNoteForm');
    const cancelNoteBtn = document.getElementById('cancelNoteBtn');
    const noteContent = document.getElementById('note-content');
    
    addNoteBtn.addEventListener('click', function() {
        addNoteForm.classList.remove('hidden');
        noteContent.focus();
    });
    
    cancelNoteBtn.addEventListener('click', function() {
        addNoteForm.classList.add('hidden');
        noteContent.value = '';
    });
});

function toggleImportant(noteId, setImportant) {
    fetch(`{{ url_for('client_notes.toggle_important', client_id=client.id, note_id=0) }}`.replace('/0/', `/${noteId}/`), {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'X-CSRFToken': '{{ csrf_token() }}'
        }
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            location.reload();
        } else {
            alert('{{ _('Error updating note') }}');
        }
    })
    .catch(error => {
        console.error('Error:', error);
        alert('{{ _('Error updating note') }}');
    });
}
</script>

{% if current_user.is_admin or has_permission('delete_clients') %}
{{ confirm_dialog(
    'confirmDeleteClient-' ~ client.id,
    'Delete Client',
    'Are you sure you want to delete this client? This action cannot be undone.',
    'Delete',
    'Cancel',
    'danger'
) }}
{% endif %}
{% endblock %}
