import {
  DeesElement,
  customElement,
  html,
  css,
  cssManager,
  property,
  state,
  type TemplateResult,
} from '@design.estate/dees-element';

declare global {
  interface HTMLElementTagNameMap {
    'sz-app-store-view': SzAppStoreView;
  }
}

export interface IAppTemplate {
  id: string;
  name: string;
  description: string;
  category: string;
  iconUrl?: string;
  iconName?: string;
  image: string;
  port: number;
  envVars?: Array<{ key: string; value: string; description: string; required?: boolean }>;
  volumes?: string[];
  enableMongoDB?: boolean;
  enableS3?: boolean;
  enableClickHouse?: boolean;
}

@customElement('sz-app-store-view')
export class SzAppStoreView extends DeesElement {
  public static demo = () => html`
    <div style="padding: 24px; max-width: 1200px;">
      <sz-app-store-view
        .apps=${[
          {
            id: 'wordpress',
            name: 'WordPress',
            description: 'The world\'s most popular open-source content management system for building websites and blogs.',
            category: 'CMS',
            iconName: 'file-text',
            image: 'wordpress:latest',
            port: 80,
            envVars: [
              { key: 'WORDPRESS_DB_HOST', value: '', description: 'Database host address', required: true },
              { key: 'WORDPRESS_DB_USER', value: 'wordpress', description: 'Database username', required: true },
              { key: 'WORDPRESS_DB_PASSWORD', value: '', description: 'Database password', required: true },
              { key: 'WORDPRESS_DB_NAME', value: 'wordpress', description: 'Database name', required: true },
            ],
            volumes: ['/var/www/html'],
            enableMongoDB: false,
            enableS3: false,
          },
          {
            id: 'gitea',
            name: 'Gitea',
            description: 'A lightweight, self-hosted Git service. Painless setup for your own code hosting platform.',
            category: 'Development',
            iconName: 'git-branch',
            image: 'gitea/gitea:latest',
            port: 3000,
            envVars: [
              { key: 'GITEA__database__DB_TYPE', value: 'sqlite3', description: 'Database type', required: true },
              { key: 'GITEA__server__ROOT_URL', value: '', description: 'Public URL of the Gitea instance', required: false },
            ],
            volumes: ['/data'],
          },
          {
            id: 'ghost',
            name: 'Ghost',
            description: 'A powerful open-source publishing platform for professional bloggers and content creators.',
            category: 'CMS',
            iconName: 'book-open',
            image: 'ghost:latest',
            port: 2368,
            envVars: [
              { key: 'url', value: '', description: 'Public URL for the Ghost site', required: true },
              { key: 'database__client', value: 'sqlite3', description: 'Database client type', required: false },
            ],
            volumes: ['/var/lib/ghost/content'],
          },
          {
            id: 'nginx',
            name: 'Nginx',
            description: 'High-performance HTTP server and reverse proxy with low resource consumption.',
            category: 'Web Server',
            iconName: 'globe',
            image: 'nginx:alpine',
            port: 80,
            volumes: ['/usr/share/nginx/html', '/etc/nginx/conf.d'],
          },
          {
            id: 'redis',
            name: 'Redis',
            description: 'In-memory data store used as a database, cache, streaming engine, and message broker.',
            category: 'Database',
            iconName: 'database',
            image: 'redis:alpine',
            port: 6379,
          },
          {
            id: 'postgres',
            name: 'PostgreSQL',
            description: 'Advanced open-source relational database with strong reliability and feature set.',
            category: 'Database',
            iconName: 'database',
            image: 'postgres:16-alpine',
            port: 5432,
            envVars: [
              { key: 'POSTGRES_USER', value: 'postgres', description: 'Superuser username', required: true },
              { key: 'POSTGRES_PASSWORD', value: '', description: 'Superuser password', required: true },
              { key: 'POSTGRES_DB', value: 'postgres', description: 'Default database name', required: false },
            ],
            volumes: ['/var/lib/postgresql/data'],
          },
        ]}
      ></sz-app-store-view>
    </div>
  `;

  public static demoGroups = ['Services'];

  @property({ type: Array })
  public accessor apps: IAppTemplate[] = [];

  @state()
  private accessor selectedCategory: string = 'All';

  @state()
  private accessor searchQuery: string = '';

  public static styles = [
    cssManager.defaultStyles,
    css`
      :host {
        display: block;
      }

      .header {
        margin-bottom: 24px;
      }

      .header-title {
        font-size: 20px;
        font-weight: 600;
        color: ${cssManager.bdTheme('#18181b', '#fafafa')};
      }

      .header-subtitle {
        font-size: 14px;
        color: ${cssManager.bdTheme('#71717a', '#a1a1aa')};
        margin-top: 4px;
      }

      .filter-bar {
        display: flex;
        flex-wrap: wrap;
        align-items: center;
        gap: 12px;
        margin-bottom: 24px;
      }

      .category-pills {
        display: flex;
        flex-wrap: wrap;
        gap: 8px;
        flex: 1;
        min-width: 0;
      }

      .category-pill {
        padding: 6px 14px;
        border-radius: 9999px;
        font-size: 13px;
        font-weight: 500;
        cursor: pointer;
        transition: all 200ms ease;
        border: 1px solid ${cssManager.bdTheme('#e4e4e7', '#27272a')};
        background: ${cssManager.bdTheme('#ffffff', '#09090b')};
        color: ${cssManager.bdTheme('#71717a', '#a1a1aa')};
        white-space: nowrap;
      }

      .category-pill:hover {
        border-color: ${cssManager.bdTheme('#d4d4d8', '#3f3f46')};
        color: ${cssManager.bdTheme('#18181b', '#fafafa')};
      }

      .category-pill.active {
        background: ${cssManager.bdTheme('#18181b', '#fafafa')};
        color: ${cssManager.bdTheme('#fafafa', '#18181b')};
        border-color: ${cssManager.bdTheme('#18181b', '#fafafa')};
      }

      .search-input {
        width: 240px;
        padding: 8px 12px 8px 36px;
        background: ${cssManager.bdTheme('#ffffff', '#18181b')};
        border: 1px solid ${cssManager.bdTheme('#e4e4e7', '#27272a')};
        border-radius: 6px;
        font-size: 14px;
        color: ${cssManager.bdTheme('#18181b', '#fafafa')};
        outline: none;
        transition: border-color 200ms ease;
        box-sizing: border-box;
      }

      .search-input:focus {
        border-color: ${cssManager.bdTheme('#3b82f6', '#60a5fa')};
      }

      .search-input::placeholder {
        color: ${cssManager.bdTheme('#a1a1aa', '#52525b')};
      }

      .search-wrapper {
        position: relative;
        flex-shrink: 0;
      }

      .search-icon {
        position: absolute;
        left: 10px;
        top: 50%;
        transform: translateY(-50%);
        width: 16px;
        height: 16px;
        color: ${cssManager.bdTheme('#a1a1aa', '#52525b')};
        pointer-events: none;
      }

      .app-grid {
        display: grid;
        grid-template-columns: repeat(3, 1fr);
        gap: 16px;
      }

      @media (max-width: 1024px) {
        .app-grid {
          grid-template-columns: repeat(2, 1fr);
        }
      }

      @media (max-width: 640px) {
        .app-grid {
          grid-template-columns: 1fr;
        }

        .filter-bar {
          flex-direction: column;
          align-items: stretch;
        }

        .search-input {
          width: 100%;
        }
      }

      .app-card {
        background: ${cssManager.bdTheme('#ffffff', '#09090b')};
        border: 1px solid ${cssManager.bdTheme('#e4e4e7', '#27272a')};
        border-radius: 8px;
        padding: 20px;
        display: flex;
        flex-direction: column;
        gap: 12px;
        transition: all 200ms ease;
        cursor: default;
      }

      .app-card:hover {
        border-color: ${cssManager.bdTheme('#d4d4d8', '#3f3f46')};
        box-shadow: 0 4px 12px ${cssManager.bdTheme('rgba(0,0,0,0.05)', 'rgba(0,0,0,0.2)')};
        transform: translateY(-1px);
      }

      .card-top {
        display: flex;
        align-items: flex-start;
        gap: 14px;
      }

      .app-icon {
        width: 44px;
        height: 44px;
        border-radius: 10px;
        background: ${cssManager.bdTheme('#f4f4f5', '#18181b')};
        display: flex;
        align-items: center;
        justify-content: center;
        flex-shrink: 0;
        overflow: hidden;
      }

      .app-icon svg {
        width: 22px;
        height: 22px;
        color: ${cssManager.bdTheme('#18181b', '#fafafa')};
      }

      .app-icon img {
        width: 100%;
        height: 100%;
        object-fit: cover;
      }

      .app-icon .letter-fallback {
        font-size: 20px;
        font-weight: 600;
        color: ${cssManager.bdTheme('#18181b', '#fafafa')};
        user-select: none;
      }

      .card-info {
        flex: 1;
        min-width: 0;
      }

      .app-name {
        font-size: 15px;
        font-weight: 600;
        color: ${cssManager.bdTheme('#18181b', '#fafafa')};
        line-height: 1.3;
      }

      .category-badge {
        display: inline-flex;
        align-items: center;
        padding: 2px 8px;
        border-radius: 9999px;
        font-size: 11px;
        font-weight: 500;
        margin-top: 4px;
        background: ${cssManager.bdTheme('#eff6ff', 'rgba(59, 130, 246, 0.15)')};
        color: ${cssManager.bdTheme('#2563eb', '#60a5fa')};
      }

      .app-description {
        font-size: 13px;
        line-height: 1.5;
        color: ${cssManager.bdTheme('#71717a', '#a1a1aa')};
        display: -webkit-box;
        -webkit-line-clamp: 2;
        -webkit-box-orient: vertical;
        overflow: hidden;
        text-overflow: ellipsis;
        flex: 1;
      }

      .card-footer {
        display: flex;
        align-items: center;
        justify-content: space-between;
        padding-top: 12px;
        border-top: 1px solid ${cssManager.bdTheme('#f4f4f5', '#1a1a1e')};
        margin-top: auto;
      }

      .image-tag {
        font-family: monospace;
        font-size: 12px;
        color: ${cssManager.bdTheme('#a1a1aa', '#52525b')};
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
        max-width: 160px;
      }

      .deploy-button {
        display: inline-flex;
        align-items: center;
        gap: 6px;
        padding: 7px 16px;
        border-radius: 6px;
        font-size: 13px;
        font-weight: 500;
        cursor: pointer;
        transition: all 200ms ease;
        border: none;
        background: ${cssManager.bdTheme('#18181b', '#fafafa')};
        color: ${cssManager.bdTheme('#fafafa', '#18181b')};
        white-space: nowrap;
        flex-shrink: 0;
      }

      .deploy-button:hover {
        opacity: 0.85;
      }

      .deploy-button svg {
        width: 14px;
        height: 14px;
      }

      .details-button {
        display: inline-flex;
        align-items: center;
        gap: 6px;
        padding: 7px 12px;
        border-radius: 6px;
        font-size: 13px;
        font-weight: 500;
        cursor: pointer;
        transition: all 200ms ease;
        border: 1px solid ${cssManager.bdTheme('#e4e4e7', '#27272a')};
        background: transparent;
        color: ${cssManager.bdTheme('#71717a', '#a1a1aa')};
        white-space: nowrap;
        flex-shrink: 0;
      }

      .details-button:hover {
        border-color: ${cssManager.bdTheme('#d4d4d8', '#3f3f46')};
        color: ${cssManager.bdTheme('#18181b', '#fafafa')};
      }

      .card-actions {
        display: flex;
        align-items: center;
        gap: 8px;
      }

      .empty-state {
        grid-column: 1 / -1;
        padding: 64px 24px;
        text-align: center;
      }

      .empty-icon {
        width: 48px;
        height: 48px;
        color: ${cssManager.bdTheme('#d4d4d8', '#3f3f46')};
        margin: 0 auto 16px;
      }

      .empty-title {
        font-size: 16px;
        font-weight: 600;
        color: ${cssManager.bdTheme('#18181b', '#fafafa')};
        margin-bottom: 4px;
      }

      .empty-description {
        font-size: 14px;
        color: ${cssManager.bdTheme('#71717a', '#a1a1aa')};
      }
    `,
  ];

  private get categories(): string[] {
    const cats = new Set(this.apps.map((app) => app.category));
    return ['All', ...Array.from(cats).sort()];
  }

  private get filteredApps(): IAppTemplate[] {
    let result = this.apps;

    if (this.selectedCategory !== 'All') {
      result = result.filter((app) => app.category === this.selectedCategory);
    }

    if (this.searchQuery.trim()) {
      const query = this.searchQuery.trim().toLowerCase();
      result = result.filter(
        (app) =>
          app.name.toLowerCase().includes(query) ||
          app.description.toLowerCase().includes(query) ||
          app.category.toLowerCase().includes(query)
      );
    }

    return result;
  }

  public render(): TemplateResult {
    const filtered = this.filteredApps;

    return html`
      <div class="header">
        <div class="header-title">App Store</div>
        <div class="header-subtitle">Deploy popular applications with one click</div>
      </div>

      <div class="filter-bar">
        <div class="category-pills">
          ${this.categories.map(
            (cat) => html`
              <button
                class="category-pill ${this.selectedCategory === cat ? 'active' : ''}"
                @click=${() => { this.selectedCategory = cat; }}
              >
                ${cat}
              </button>
            `
          )}
        </div>
        <div class="search-wrapper">
          <svg class="search-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
            <circle cx="11" cy="11" r="8"></circle>
            <line x1="21" y1="21" x2="16.65" y2="16.65"></line>
          </svg>
          <input
            type="text"
            class="search-input"
            placeholder="Search apps..."
            .value=${this.searchQuery}
            @input=${(e: Event) => { this.searchQuery = (e.target as HTMLInputElement).value; }}
          >
        </div>
      </div>

      <div class="app-grid">
        ${filtered.length > 0
          ? filtered.map((app) => this.renderAppCard(app))
          : html`
              <div class="empty-state">
                <svg class="empty-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5">
                  <circle cx="11" cy="11" r="8"></circle>
                  <line x1="21" y1="21" x2="16.65" y2="16.65"></line>
                  <line x1="8" y1="11" x2="14" y2="11"></line>
                </svg>
                <div class="empty-title">No apps found</div>
                <div class="empty-description">
                  Try adjusting your search or filter to find what you're looking for.
                </div>
              </div>
            `}
      </div>
    `;
  }

  private renderAppCard(app: IAppTemplate): TemplateResult {
    return html`
      <div class="app-card">
        <div class="card-top">
          <div class="app-icon">
            ${app.iconUrl
              ? html`<img src="${app.iconUrl}" alt="${app.name}">`
              : app.iconName
                ? this.renderIconByName(app.iconName)
                : html`<span class="letter-fallback">${app.name.charAt(0).toUpperCase()}</span>`}
          </div>
          <div class="card-info">
            <div class="app-name">${app.name}</div>
            <div class="category-badge">${app.category}</div>
          </div>
        </div>
        <div class="app-description">${app.description}</div>
        <div class="card-footer">
          <span class="image-tag" title="${app.image}">${app.image}</span>
          <div class="card-actions">
            <button class="details-button" @click=${() => this.handleViewDetails(app)}>
              View Details
            </button>
            <button class="deploy-button" @click=${() => this.handleDeploy(app)}>
              <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                <polyline points="20 12 20 22 4 22 4 12"></polyline>
                <rect x="2" y="7" width="20" height="5"></rect>
                <line x1="12" y1="22" x2="12" y2="7"></line>
                <path d="M12 7H7.5a2.5 2.5 0 0 1 0-5C11 2 12 7 12 7z"></path>
                <path d="M12 7h4.5a2.5 2.5 0 0 0 0-5C13 2 12 7 12 7z"></path>
              </svg>
              Deploy
            </button>
          </div>
        </div>
      </div>
    `;
  }

  private renderIconByName(name: string): TemplateResult {
    const icons: Record<string, TemplateResult> = {
      'file-text': html`<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"></path><polyline points="14 2 14 8 20 8"></polyline><line x1="16" y1="13" x2="8" y2="13"></line><line x1="16" y1="17" x2="8" y2="17"></line><polyline points="10 9 9 9 8 9"></polyline></svg>`,
      'git-branch': html`<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><line x1="6" y1="3" x2="6" y2="15"></line><circle cx="18" cy="6" r="3"></circle><circle cx="6" cy="18" r="3"></circle><path d="M18 9a9 9 0 0 1-9 9"></path></svg>`,
      'book-open': html`<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M2 3h6a4 4 0 0 1 4 4v14a3 3 0 0 0-3-3H2z"></path><path d="M22 3h-6a4 4 0 0 0-4 4v14a3 3 0 0 1 3-3h7z"></path></svg>`,
      'globe': html`<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="10"></circle><line x1="2" y1="12" x2="22" y2="12"></line><path d="M12 2a15.3 15.3 0 0 1 4 10 15.3 15.3 0 0 1-4 10 15.3 15.3 0 0 1-4-10 15.3 15.3 0 0 1 4-10z"></path></svg>`,
      'database': html`<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><ellipse cx="12" cy="5" rx="9" ry="3"></ellipse><path d="M21 12c0 1.66-4 3-9 3s-9-1.34-9-3"></path><path d="M3 5v14c0 1.66 4 3 9 3s9-1.34 9-3V5"></path></svg>`,
      'server': html`<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="2" y="2" width="20" height="8" rx="2" ry="2"></rect><rect x="2" y="14" width="20" height="8" rx="2" ry="2"></rect><line x1="6" y1="6" x2="6.01" y2="6"></line><line x1="6" y1="18" x2="6.01" y2="18"></line></svg>`,
      'package': html`<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><line x1="16.5" y1="9.4" x2="7.5" y2="4.21"></line><path d="M21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16z"></path><polyline points="3.27 6.96 12 12.01 20.73 6.96"></polyline><line x1="12" y1="22.08" x2="12" y2="12"></line></svg>`,
      'mail': html`<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M4 4h16c1.1 0 2 .9 2 2v12c0 1.1-.9 2-2 2H4c-1.1 0-2-.9-2-2V6c0-1.1.9-2 2-2z"></path><polyline points="22,6 12,13 2,6"></polyline></svg>`,
      'shield': html`<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"></path></svg>`,
      'monitor': html`<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="2" y="3" width="20" height="14" rx="2" ry="2"></rect><line x1="8" y1="21" x2="16" y2="21"></line><line x1="12" y1="17" x2="12" y2="21"></line></svg>`,
    };

    return icons[name] || html`<span class="letter-fallback">?</span>`;
  }

  private handleViewDetails(app: IAppTemplate) {
    this.dispatchEvent(
      new CustomEvent('view-app', {
        detail: { app },
        bubbles: true,
        composed: true,
      })
    );
  }

  private handleDeploy(app: IAppTemplate) {
    this.dispatchEvent(
      new CustomEvent('deploy-app', {
        detail: { app },
        bubbles: true,
        composed: true,
      })
    );
  }
}
