import { LitElement, css, html } from 'lit';
import { customElement, property } from 'lit/decorators.js';

import '@components/EveLink';
import { ifDefined } from 'lit/directives/if-defined.js';
import { when } from 'lit/directives/when.js';

@customElement('arx-app-icon')
export class AppIcon extends LitElement {
  @property()
  icon: string | undefined;

  @property()
  color = '#ff9900';

  @property()
  href = '#';

  @property()
  name = 'App';

  @property({ type: Boolean })
  small = false;

  @property({ type: Boolean })
  selected = false;

  private iconElement?: HTMLElement;

  static override styles = [
    css`
      :host {
        display: flex;
        --shadow-opacity: 0.2;
        --hover-lift: -6px;
        --tap-scale: 0.92;
      }

      .app-icon {
        display: flex;
        flex-direction: column;
        align-items: center;
        gap: 10px;
        text-decoration: none;
        padding: 8px;
        border-radius: 18px;
        transition: transform var(--transition);
        position: relative;
        will-change: transform;
        perspective: 800px;
      }

      .app-icon:hover {
        transform: translateY(var(--hover-lift));
      }

      .icon {
        width: 96px;
        height: 96px;
        border-radius: 24px;
        box-shadow: 0 3px 8px rgba(0, 0, 0, var(--shadow-opacity));
        display: flex;
        justify-content: center;
        align-items: center;
        border: 1px solid rgba(255, 255, 255, 0.2);
        overflow: hidden;
        position: relative;
        transition: 
          transform var(--overshoot-transition),
          box-shadow var(--overshoot-transition);
        transform-style: preserve-3d;
        &::before {
          content: "";
          position: absolute;
          inset: 0;
          background: linear-gradient(
            145deg,
            rgba(255, 255, 255, 0.25) 20%,
            rgba(255, 255, 255, 0) 60%
          );
          pointer-events: none;
          opacity: 1;
          transition: opacity var(--transition);
        }

        &::after {
          content: "";
          position: absolute;
          inset: 0;
          background: linear-gradient(
            var(--gradient-angle, 145deg),
            rgba(255, 255, 255, 0.35) 10%,
            rgba(255, 255, 255, 0) 70%
          );
          pointer-events: none;
          opacity: 0;
          transition: opacity var(--undershoot-transition);
          z-index: 1;
        }

        &:hover::before {
          opacity: 0;
        }

        &:hover::after {
          opacity: 1;
        }
      }

      :host([small]) .icon {
        width: 64px;
        height: 64px;
        border-radius: 12px;
      }

      .icon-svg {
        color: white;
        filter: drop-shadow(
          calc(cos(var(--gradient-angle, 145deg)) * 3px)
            calc(sin(var(--gradient-angle, 145deg)) * 3px) 
            rgba(0, 0, 0, 0.25)
        );
        display: flex;
        justify-content: center;
        align-items: center;
        width: 100%;
        height: 100%;
        transition: transform var(--overshoot-transition);
        z-index: 2;
      }

      .app-name {
        display: block;
        width: 100%;
        text-align: center;
        font-size: 18px;
        font-weight: 500;
        color: var(--color-base-content);
        white-space: nowrap;
        text-decoration: none;
        transition: all var(--transition);
        transform: translateZ(0);
        opacity: 0.85;
      }

      :host([selected]) .app-name {
        color: var(--color-primary-content);
      }

      :host([small]) .app-name {
        font-size: 14px;
        margin-top: 2px;
      }

      .app-icon:hover .icon {
        transform: scale(1.05) translateZ(10px) rotateX(var(--rotate-x, 0deg)) rotateY(var(--rotate-y, 0deg));
        box-shadow: 
          0 10px 20px -5px rgba(0, 0, 0, calc(var(--shadow-opacity) * 1.5)),
          0 0 0 1px rgba(255, 255, 255, 0.15);
      }

      :host([small]) .app-icon:hover .icon {
        transform: scale(1.05) translateZ(5px) rotateX(var(--rotate-x, 0deg)) rotateY(var(--rotate-y, 0deg));
      }

      .app-icon:hover .app-name {
        opacity: 1;
        transform: translateY(2px) scale(1.02);
      }

      .app-icon:hover .icon-svg {
        transform: scale(1.08) translateZ(15px);
      }

      :host([small]) .app-icon:hover .icon-svg {
        transform: scale(1.08) translateZ(8px);
      }

      .app-icon:active .icon {
        transform: scale(var(--tap-scale)) translateZ(0);
        box-shadow: 0 2px 5px rgba(0, 0, 0, calc(var(--shadow-opacity) * 0.8));
        transition: all var(--transition);
      }

      .app-icon:active .app-name {
        transform: translateY(0) scale(0.98);
        transition: all var(--transition);
      }
    `,
  ];

  override firstUpdated() {
    this.iconElement = this.shadowRoot?.querySelector('.icon') as HTMLElement;
    if (this.iconElement) {
      this.iconElement.addEventListener('mousemove', this.handleMouseMove);
      this.iconElement.addEventListener('mouseleave', this.handleMouseLeave);
    }
  }

  override disconnectedCallback() {
    super.disconnectedCallback();
    if (this.iconElement) {
      this.iconElement.removeEventListener('mousemove', this.handleMouseMove);
      this.iconElement.removeEventListener('mouseleave', this.handleMouseLeave);
    }
  }

  handleMouseMove = (e: MouseEvent) => {
    if (!this.iconElement) return;

    const rect = this.iconElement.getBoundingClientRect();
    const centerX = rect.left + rect.width / 2;
    const centerY = rect.top + rect.height / 2;

    const dx = e.clientX - centerX;
    const dy = e.clientY - centerY;
    const angle = Math.atan2(dy, dx) * (180 / Math.PI);

    const maxTilt = 20;
    const percentX = (e.clientX - rect.left) / rect.width - 0.5;
    const percentY = (e.clientY - rect.top) / rect.height - 0.5;

    const tiltX = -percentY * maxTilt * 1.2;
    const tiltY = percentX * maxTilt;

    this.iconElement.style.setProperty('--gradient-angle', `${angle}deg`);
    this.iconElement.style.setProperty('--rotate-x', `${tiltX}deg`);
    this.iconElement.style.setProperty('--rotate-y', `${tiltY}deg`);
  };

  handleMouseLeave = () => {
    if (!this.iconElement) return;

    this.iconElement.style.transition = 'transform var(--transition)';
    this.iconElement.style.setProperty('--rotate-x', '0deg');
    this.iconElement.style.setProperty('--rotate-y', '0deg');

    this.iconElement.addEventListener(
      'transitionend',
      () => {
        this.iconElement!.style.transition = '';
      },
      { once: true },
    );
  };

  override render() {
    return html`
      <arx-eve-link href="${this.href}" class="app-icon">
        <div class="icon" style="background: ${this.color};">
          ${when(
            this.icon,
            () =>
              html`<iconify-icon
                icon="${ifDefined(this.icon)}"
                class="icon-svg"
                width="${this.small ? '48' : '64'}"
                height="${this.small ? '48' : '64'}"
              ></iconify-icon>`,
          )}
        </div>
        <span class="app-name">${this.name}</span>
      </arx-eve-link>
    `;
  }
}
