/**
 * ds-project-list.js
 * Project management component
 * Create, edit, delete, and select projects
 */

import { useProjectStore } from '../../stores/project-store.js';

export default class ProjectList extends HTMLElement {
  constructor() {
    super();
    this.projectStore = useProjectStore();
    this.state = {
      projects: this.projectStore.getProjects(),
      currentProject: this.projectStore.getCurrentProject(),
      showEditModal: false,
      editingProject: null
    };
  }

  connectedCallback() {
    this.render();
    this.setupEventListeners();
    this.unsubscribe = this.projectStore.subscribe(() => {
      this.state.projects = this.projectStore.getProjects();
      this.state.currentProject = this.projectStore.getCurrentProject();
      this.updateProjectList();
    });
  }

  disconnectedCallback() {
    if (this.unsubscribe) this.unsubscribe();
  }

  render() {
    this.innerHTML = `
      <div style="padding: 24px;">
        <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 24px;">
          <h2 style="margin: 0; font-size: 20px;">Projects</h2>
          <button id="create-project-btn" style="
            padding: 8px 16px;
            background: var(--vscode-button-background);
            color: var(--vscode-button-foreground);
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-weight: 500;
          ">
            + New Project
          </button>
        </div>

        <!-- Projects List -->
        <div id="projects-container" style="display: flex; flex-direction: column; gap: 12px;">
          ${this.renderProjectsList()}
        </div>
      </div>

      <!-- Edit Modal -->
      <div id="edit-modal" style="
        display: ${this.state.showEditModal ? 'flex' : 'none'};
        position: fixed;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        background: rgba(0, 0, 0, 0.5);
        align-items: center;
        justify-content: center;
        z-index: 1000;
      ">
        <div style="
          background: var(--vscode-editor-background);
          border: 1px solid var(--vscode-border);
          border-radius: 8px;
          padding: 24px;
          min-width: 400px;
          max-width: 500px;
          box-shadow: 0 8px 32px rgba(0, 0, 0, 0.3);
        ">
          <h3 id="modal-title" style="margin: 0 0 16px 0; font-size: 18px;">
            ${this.state.editingProject ? 'Edit Project' : 'New Project'}
          </h3>

          <!-- Project ID -->
          <div style="margin-bottom: 16px;">
            <label style="display: block; margin-bottom: 6px; font-size: 12px; font-weight: 500;">
              Project ID (Jira Key)
            </label>
            <input
              id="modal-project-id"
              type="text"
              ${this.state.editingProject ? 'disabled' : ''}
              value="${this.state.editingProject?.id || ''}"
              placeholder="E.g., DSS-123"
              style="
                width: 100%;
                padding: 8px 12px;
                border: 1px solid var(--vscode-input-border);
                background: var(--vscode-input-background);
                color: var(--vscode-foreground);
                border-radius: 4px;
                font-family: monospace;
              "
            />
            <div style="font-size: 10px; color: var(--vscode-text-dim); margin-top: 4px;">
              ${this.state.editingProject ? 'Cannot change after creation' : 'Must match Jira project key'}
            </div>
          </div>

          <!-- Project Name -->
          <div style="margin-bottom: 16px;">
            <label style="display: block; margin-bottom: 6px; font-size: 12px; font-weight: 500;">
              Project Name
            </label>
            <input
              id="modal-project-name"
              type="text"
              value="${this.state.editingProject?.name || ''}"
              placeholder="My Design System"
              style="
                width: 100%;
                padding: 8px 12px;
                border: 1px solid var(--vscode-input-border);
                background: var(--vscode-input-background);
                color: var(--vscode-foreground);
                border-radius: 4px;
              "
            />
          </div>

          <!-- Skin Selection -->
          <div style="margin-bottom: 24px;">
            <label style="display: block; margin-bottom: 6px; font-size: 12px; font-weight: 500;">
              Default Skin
            </label>
            <select
              id="modal-skin-select"
              style="
                width: 100%;
                padding: 8px 12px;
                border: 1px solid var(--vscode-input-border);
                background: var(--vscode-input-background);
                color: var(--vscode-foreground);
                border-radius: 4px;
              "
            >
              <option value="default" ${this.state.editingProject?.skinSelected === 'default' ? 'selected' : ''}>default</option>
              <option value="light" ${this.state.editingProject?.skinSelected === 'light' ? 'selected' : ''}>light</option>
              <option value="dark" ${this.state.editingProject?.skinSelected === 'dark' ? 'selected' : ''}>dark</option>
            </select>
          </div>

          <!-- Buttons -->
          <div style="display: flex; gap: 8px; justify-content: flex-end;">
            <button id="modal-cancel-btn" style="
              padding: 8px 16px;
              background: var(--vscode-button-secondaryBackground);
              color: var(--vscode-button-secondaryForeground);
              border: none;
              border-radius: 4px;
              cursor: pointer;
            ">
              Cancel
            </button>
            <button id="modal-save-btn" style="
              padding: 8px 16px;
              background: var(--vscode-button-background);
              color: var(--vscode-button-foreground);
              border: none;
              border-radius: 4px;
              cursor: pointer;
              font-weight: 500;
            ">
              ${this.state.editingProject ? 'Update' : 'Create'}
            </button>
          </div>
        </div>
      </div>
    `;
  }

  renderProjectsList() {
    if (this.state.projects.length === 0) {
      return '<div style="color: var(--vscode-text-dim); text-align: center; padding: 32px;">No projects yet. Create one to get started!</div>';
    }

    return this.state.projects.map(project => `
      <div data-project-id="${project.id}" style="
        display: flex;
        align-items: center;
        gap: 12px;
        padding: 12px;
        background: ${this.state.currentProject?.id === project.id ? 'var(--vscode-selection)' : 'var(--vscode-sidebar)'};
        border: 1px solid var(--vscode-border);
        border-radius: 4px;
        cursor: pointer;
        transition: background 0.2s;
      " onmouseover="this.style.background='var(--vscode-selection)'" onmouseout="this.style.background='${this.state.currentProject?.id === project.id ? 'var(--vscode-selection)' : 'var(--vscode-sidebar)'}'">
        <div style="flex: 1;">
          <div style="font-weight: 500; margin-bottom: 4px;">${project.name}</div>
          <div style="font-size: 11px; color: var(--vscode-text-dim);">
            ID: ${project.id} | Skin: ${project.skinSelected}
          </div>
        </div>
        <div style="display: flex; gap: 4px;">
          <button class="edit-project-btn" data-project-id="${project.id}" style="
            padding: 4px 8px;
            background: var(--vscode-button-secondaryBackground);
            color: var(--vscode-button-secondaryForeground);
            border: none;
            border-radius: 2px;
            cursor: pointer;
            font-size: 11px;
          ">
            Edit
          </button>
          <button class="delete-project-btn" data-project-id="${project.id}" style="
            padding: 4px 8px;
            background: #c1272d;
            color: white;
            border: none;
            border-radius: 2px;
            cursor: pointer;
            font-size: 11px;
          ">
            Delete
          </button>
        </div>
      </div>
    `).join('');
  }

  setupEventListeners() {
    // Create button
    this.querySelector('#create-project-btn').addEventListener('click', () => {
      this.state.editingProject = null;
      this.state.showEditModal = true;
      this.render();
      this.setupEventListeners();
    });

    // Project selection
    this.querySelectorAll('[data-project-id]').forEach(el => {
      el.addEventListener('click', (e) => {
        if (!e.target.closest('button')) {
          const projectId = el.dataset.projectId;
          this.projectStore.selectProject(projectId);
        }
      });
    });

    // Edit buttons
    this.querySelectorAll('.edit-project-btn').forEach(btn => {
      btn.addEventListener('click', (e) => {
        e.stopPropagation();
        const projectId = btn.dataset.projectId;
        this.state.editingProject = this.projectStore.getProject(projectId);
        this.state.showEditModal = true;
        this.render();
        this.setupEventListeners();
      });
    });

    // Delete buttons
    this.querySelectorAll('.delete-project-btn').forEach(btn => {
      btn.addEventListener('click', (e) => {
        e.stopPropagation();
        const projectId = btn.dataset.projectId;
        const project = this.projectStore.getProject(projectId);
        if (confirm(`Delete project "${project.name}"? This cannot be undone.`)) {
          this.projectStore.deleteProject(projectId);
        }
      });
    });

    // Modal buttons
    const modal = this.querySelector('#edit-modal');
    if (modal) {
      this.querySelector('#modal-cancel-btn').addEventListener('click', () => {
        this.state.showEditModal = false;
        this.state.editingProject = null;
        this.render();
      });

      this.querySelector('#modal-save-btn').addEventListener('click', () => {
        const id = this.querySelector('#modal-project-id').value.trim();
        const name = this.querySelector('#modal-project-name').value.trim();
        const skin = this.querySelector('#modal-skin-select').value;

        if (!id || !name) {
          alert('Please fill in all fields');
          return;
        }

        if (this.state.editingProject) {
          // Update
          this.projectStore.updateProject(this.state.editingProject.id, {
            name,
            skinSelected: skin
          });
        } else {
          // Create
          this.projectStore.createProject({ id, name, skinSelected: skin });
        }

        this.state.showEditModal = false;
        this.state.editingProject = null;
        this.render();
        this.setupEventListeners();
      });
    }
  }

  updateProjectList() {
    const container = this.querySelector('#projects-container');
    if (container) {
      container.innerHTML = this.renderProjectsList();
      this.setupEventListeners();
    }
  }
}

customElements.define('ds-project-list', ProjectList);
