import {
  ThemeDocument,
  ThemeElementStyles,
  ThemeLayoutEntry
} from '../models/theme.model';
import { THEME_LAYOUT_CONTAINERS, getLayoutEditableThemeKeys } from './theme-registry.logic';

const DEFAULT_SHELL_CSS = `/* Dark glass app shell surfaces */
app-chat-messages .chat-layout,
app-dm-chat .chat-layout {
  background-image: linear-gradient(180deg, hsl(var(--workspace-background) / 0.96), hsl(var(--background)) 38rem) !important;
}

app-chat-message-list > div {
  background: transparent !important;
}

app-chat-message-item > div[data-message-id] {
  margin: 8px 0 !important;
  border: 1px solid hsl(var(--border) / 0.56) !important;
  border-radius: 0.7rem !important;
  background: hsl(var(--card) / 0.72) !important;
  box-shadow: 0 14px 34px rgb(0 0 0 / 0.2) !important;
  backdrop-filter: blur(12px) saturate(120%) !important;
  -webkit-backdrop-filter: blur(12px) saturate(120%) !important;
}

app-chat-message-item > div[data-message-id]:hover {
  border-color: hsl(var(--primary) / 0.42) !important;
  background: hsl(var(--secondary) / 0.88) !important;
}

app-chat-message-composer,
.chat-bottom-bar {
  border-top: 0 !important;
  background: hsl(var(--background) / 0.84) !important;
  backdrop-filter: blur(16px) saturate(125%) !important;
  -webkit-backdrop-filter: blur(16px) saturate(125%) !important;
}

app-chat-message-composer textarea,
app-chat-message-composer [contenteditable="true"] {
  background: transparent !important;
}
`;

function createDefaultShellElements(): Record<string, ThemeElementStyles> {
  return {
    titleBar: {
      border: '0',
      backgroundColor: 'hsl(var(--title-bar-background) / 0.88)',
      boxShadow: '0 12px 28px rgba(0, 0, 0, 0.22)',
      backdropFilter: 'var(--theme-effect-glass-blur)'
    },
    serversRail: {
      border: '0',
      backgroundColor: 'hsl(var(--rail-background) / 0.94)',
      boxShadow: 'var(--theme-effect-panel-shadow)'
    },
    appWorkspace: {
      backgroundColor: 'hsl(var(--workspace-background))'
    },
    chatRoomChannelsPanel: {
      border: '0',
      backgroundColor: 'hsl(var(--panel-background) / 0.86)',
      backdropFilter: 'var(--theme-effect-glass-blur)'
    },
    chatRoomMembersPanel: {
      border: '0',
      backgroundColor: 'hsl(var(--panel-background) / 0.82)',
      backdropFilter: 'var(--theme-effect-glass-blur)'
    },
    chatRoomMainPanel: {
      backgroundColor: 'hsl(var(--workspace-background))'
    },
    chatSurface: {
      backgroundColor: 'transparent'
    },
    chatMessageBubble: {
      border: '1px solid hsl(var(--border) / 0.56)',
      borderRadius: '0.7rem',
      backgroundColor: 'hsl(var(--card) / 0.72)',
      boxShadow: 'var(--theme-effect-soft-shadow)',
      backdropFilter: 'blur(12px) saturate(120%)'
    },
    chatComposerBar: {
      border: '0',
      backgroundColor: 'hsl(var(--background) / 0.84)',
      backdropFilter: 'var(--theme-effect-glass-blur)'
    },
    chatComposerInput: {
      border: '1px solid hsl(var(--border) / 0.6)',
      borderRadius: '0.6rem',
      backgroundColor: 'hsl(var(--panel-background-alt) / 0.8)',
      color: 'hsl(var(--foreground))'
    }
  };
}

function createProvidedDefaultLayout(): Record<string, ThemeLayoutEntry> {
  return {
    serversRail: {
      container: 'appShell',
      grid: { x: 0, y: 0, w: 1, h: 1 }
    },
    appWorkspace: {
      container: 'appShell',
      grid: { x: 1, y: 0, w: 19, h: 1 }
    },
    chatRoomChannelsPanel: {
      container: 'roomLayout',
      grid: { x: 0, y: 0, w: 4, h: 12 }
    },
    chatRoomMainPanel: {
      container: 'roomLayout',
      grid: { x: 4, y: 0, w: 12, h: 12 }
    },
    chatRoomMembersPanel: {
      container: 'roomLayout',
      grid: { x: 16, y: 0, w: 4, h: 12 }
    }
  };
}

export function createDefaultThemeLayout(): Record<string, ThemeLayoutEntry> {
  const layoutEntries: Record<string, ThemeLayoutEntry> = {};

  for (const key of getLayoutEditableThemeKeys()) {
    if (key === 'serversRail') {
      layoutEntries[key] = {
        container: 'appShell',
        grid: { x: 0, y: 0, w: 1, h: 1 }
      };

      continue;
    }

    if (key === 'appWorkspace') {
      const appShell = THEME_LAYOUT_CONTAINERS.find((container) => container.key === 'appShell');

      layoutEntries[key] = {
        container: 'appShell',
        grid: { x: 1, y: 0, w: (appShell?.columns ?? 20) - 1, h: 1 }
      };

      continue;
    }

    if (key === 'chatRoomChannelsPanel') {
      layoutEntries[key] = {
        container: 'roomLayout',
        grid: { x: 0, y: 0, w: 4, h: 12 }
      };

      continue;
    }

    if (key === 'chatRoomMainPanel') {
      layoutEntries[key] = {
        container: 'roomLayout',
        grid: { x: 4, y: 0, w: 12, h: 12 }
      };

      continue;
    }

    if (key === 'chatRoomMembersPanel') {
      layoutEntries[key] = {
        container: 'roomLayout',
        grid: { x: 16, y: 0, w: 4, h: 12 }
      };

      continue;
    }

    if (key === 'dmConversationsPanel') {
      layoutEntries[key] = {
        container: 'dmLayout',
        grid: { x: 0, y: 0, w: 4, h: 12 }
      };

      continue;
    }

    if (key === 'dmChatPanel') {
      layoutEntries[key] = {
        container: 'dmLayout',
        grid: { x: 4, y: 0, w: 16, h: 12 }
      };
    }
  }

  return layoutEntries;
}

function hasOnlyLegacyRadius(radii: Record<string, string>): boolean {
  const keys = Object.keys(radii);

  return keys.length === 1 && radii['radius'] === '0.375rem';
}

function allElementsEmpty(elements: Record<string, ThemeElementStyles>): boolean {
  return Object.values(elements).every((elementStyles) => Object.keys(elementStyles).length === 0);
}

export interface BuiltInThemePreset {
  key: string;
  theme: ThemeDocument;
}

function createLegacyDefaultDarkThemeDocument(): ThemeDocument {
  return {
    css: '',
    meta: {
      name: 'Toju Default Dark',
      version: '2.0.0',
      description: 'Built-in dark glass theme for the full Toju app shell.'
    },
    tokens: {
      colors: {
        background: '224 28% 7%',
        foreground: '210 40% 96%',
        card: '224 25% 10%',
        cardForeground: '210 40% 96%',
        popover: '224 26% 9%',
        popoverForeground: '210 40% 96%',
        primary: '193 95% 68%',
        primaryForeground: '222 47% 11%',
        secondary: '223 19% 16%',
        secondaryForeground: '210 40% 96%',
        muted: '223 18% 14%',
        mutedForeground: '215 20% 70%',
        accent: '218 22% 18%',
        accentForeground: '210 40% 98%',
        destructive: '0 72% 55%',
        destructiveForeground: '0 0% 100%',
        border: '222 18% 22%',
        input: '222 18% 22%',
        ring: '193 95% 68%',
        railBackground: '226 33% 8%',
        workspaceBackground: '224 30% 9%',
        panelBackground: '224 24% 11%',
        panelBackgroundAlt: '222 22% 13%',
        titleBarBackground: '226 34% 7%',
        surfaceHighlight: '193 95% 68%',
        surfaceHighlightAlt: '261 82% 72%'
      },
      spacing: {},
      radii: {
        radius: '0.875rem',
        surface: '1.35rem',
        pill: '999px'
      },
      effects: {
        panelShadow: '0 24px 60px rgba(0, 0, 0, 0.42)',
        softShadow: '0 14px 36px rgba(0, 0, 0, 0.28)',
        glassBlur: 'blur(18px) saturate(135%)'
      }
    },
    layout: createProvidedDefaultLayout(),
    elements: {},
    animations: {}
  };
}

export function createWebsiteDarkThemeDocument(): ThemeDocument {
  return {
    css: DEFAULT_SHELL_CSS.replace('Dark glass app shell surfaces', 'Website-inspired app shell surfaces'),
    meta: {
      name: 'Toju Website Dark',
      version: '1.0.0',
      description: 'Website-inspired dark app theme using the charcoal, green, and amber palette from the public Toju site.'
    },
    tokens: {
      colors: {
        background: '210 18% 7%',
        foreground: '42 33% 94%',
        card: '210 17% 10%',
        cardForeground: '42 33% 94%',
        popover: '210 17% 9%',
        popoverForeground: '42 33% 94%',
        primary: '154 49% 55%',
        primaryForeground: '210 18% 7%',
        secondary: '210 14% 15%',
        secondaryForeground: '42 33% 94%',
        muted: '210 14% 15%',
        mutedForeground: '42 13% 67%',
        accent: '38 64% 61%',
        accentForeground: '210 18% 7%',
        destructive: '0 72% 55%',
        destructiveForeground: '0 0% 100%',
        border: '210 13% 22%',
        input: '210 13% 22%',
        ring: '154 49% 55%',
        railBackground: '210 19% 6%',
        workspaceBackground: '210 18% 8%',
        panelBackground: '210 17% 10%',
        panelBackgroundAlt: '210 14% 13%',
        titleBarBackground: '210 19% 6%',
        surfaceHighlight: '154 49% 55%',
        surfaceHighlightAlt: '38 64% 61%'
      },
      spacing: {},
      radii: {
        radius: '0.6rem',
        surface: '0.85rem',
        pill: '999px'
      },
      effects: {
        panelShadow: '0 28px 64px rgba(0, 0, 0, 0.34)',
        softShadow: '0 16px 36px rgba(0, 0, 0, 0.22)',
        glassBlur: 'blur(16px) saturate(125%)'
      }
    },
    layout: createDefaultThemeLayout(),
    elements: createDefaultShellElements(),
    animations: {}
  };
}

export function createDefaultThemeDocument(): ThemeDocument {
  return {
    css: DEFAULT_SHELL_CSS,
    meta: {
      name: 'Toju Default Dark 11',
      version: '2.0.0',
      description: 'Built-in dark glass theme for the full Toju app shell.'
    },
    tokens: {
      colors: {
        background: '225 6% 12%',
        foreground: '210 40% 96%',
        card: '220 6% 18%',
        cardForeground: '210 40% 96%',
        popover: '220 6% 18%',
        popoverForeground: '210 40% 96%',
        primary: '234 85% 64%',
        primaryForeground: '222 47% 11%',
        secondary: '222 10% 24%',
        secondaryForeground: '210 40% 96%',
        muted: '223 18% 14%',
        mutedForeground: '215 20% 70%',
        accent: '234 32% 28%',
        accentForeground: '210 40% 98%',
        destructive: '358 82% 59%',
        destructiveForeground: '0 0% 100%',
        border: '222 18% 22%',
        input: '222 18% 22%',
        ring: '234 85% 64%',
        railBackground: '225 6% 12%',
        workspaceBackground: '220 6% 18%',
        panelBackground: '220 6% 18%',
        panelBackgroundAlt: '225 6% 15%',
        titleBarBackground: '225 6% 9%',
        surfaceHighlight: '234 85% 64%',
        surfaceHighlightAlt: '261 82% 72%'
      },
      spacing: {},
      radii: {
        radius: '0.875rem',
        surface: '1.35rem',
        pill: '999px'
      },
      effects: {
        panelShadow: '0 24px 60px rgba(0, 0, 0, 0.42)',
        softShadow: '0 14px 36px rgba(0, 0, 0, 0.28)',
        glassBlur: 'blur(18px) saturate(135%)'
      }
    },
    layout: createDefaultThemeLayout(),
    elements: createDefaultShellElements(),
    animations: {}
  };
}

export function isLegacyDefaultThemeDocument(document: ThemeDocument): boolean {
  return (
    document.meta.name === 'Toju Default Theme' &&
    document.meta.version === '1.0.0' &&
    document.meta.description === 'Safe baseline theme that matches the built-in Toju shell layout.' &&
    Object.keys(document.tokens.colors).length === 0 &&
    Object.keys(document.tokens.spacing).length === 0 &&
    hasOnlyLegacyRadius(document.tokens.radii) &&
    Object.keys(document.tokens.effects).length === 0 &&
    allElementsEmpty(document.elements) &&
    Object.keys(document.animations).length === 0 &&
    document.css.length === 0
  );
}

export const DEFAULT_THEME_DOCUMENT: ThemeDocument = createDefaultThemeDocument();
export const BUILT_IN_THEME_PRESETS: readonly BuiltInThemePreset[] = [
  {
    key: 'toju-default-dark-11',
    theme: DEFAULT_THEME_DOCUMENT
  },
  {
    key: 'toju-website-dark',
    theme: createWebsiteDarkThemeDocument()
  },
  {
    key: 'toju-default-dark',
    theme: createLegacyDefaultDarkThemeDocument()
  }
];
export const DEFAULT_THEME_JSON = JSON.stringify(
  DEFAULT_THEME_DOCUMENT,
  null,
  2
);
