import { Injectable, NotFoundException } from '@nestjs/common';
import { PrismaService } from '../../../prisma/prisma.service';
import { UpdateWidgetSettingsDto } from '../dto/widget-settings.dto';

const DEFAULT_SETTINGS = {
  title: 'Онлайн-запись',
  logoUrl: null,
  colors: {
    primary: '#3B82F6',
    primaryHover: '#2563EB',
    background: '#FFFFFF',
    text: '#1F2937',
    textSecondary: '#6B7280',
  },
  fields: {
    showEmail: true,
    requireEmail: false,
    showComment: true,
    showGroupEvents: false,
    showWeekSchedule: true,
  },
  successRedirectUrl: null,
  customCss: null,
  isEnabled: true,
};

/**
 * Widget settings are stored in BookingCrmBridge.metadata.widget
 * to avoid adding a new model just for widget config.
 */
@Injectable()
export class WidgetSettingsService {
  constructor(private readonly prisma: PrismaService) {}

  async getSettings(clubId: string) {
    const bridge = await this.prisma.bookingCrmBridge.findUnique({
      where: { clubId },
    });

    // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
    const meta = (bridge?.metadata as Record<string, any>) ?? {};
    // eslint-disable-next-line @typescript-eslint/no-unsafe-return
    return { ...DEFAULT_SETTINGS, ...meta.widget };
  }

  async getSettingsBySlug(clubSlug: string) {
    const club = await this.prisma.club.findUnique({
      where: { slug: clubSlug },
      select: { id: true, name: true, slug: true, logoUrl: true },
    });

    if (!club) throw new NotFoundException('Club not found');

    // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
    const settings = await this.getSettings(club.id);

    return {
      club: { name: club.name, slug: club.slug, logoUrl: club.logoUrl },
      // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
      widget: settings,
    };
  }

  async updateSettings(clubId: string, dto: UpdateWidgetSettingsDto) {
    const bridge = await this.prisma.bookingCrmBridge.findUnique({
      where: { clubId },
    });

    // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
    const currentMeta = (bridge?.metadata as Record<string, any>) ?? {};
    // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
    const currentWidget = currentMeta.widget ?? {};

    /* eslint-disable @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-assignment */
    const mergedColors =
      dto.colors !== undefined ? { ...currentWidget.colors, ...dto.colors } : currentWidget.colors;

    const mergedFields =
      dto.fields !== undefined ? { ...currentWidget.fields, ...dto.fields } : currentWidget.fields;
    /* eslint-enable @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-assignment */

    // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
    const newWidget = {
      ...currentWidget,
      ...(dto.title !== undefined ? { title: dto.title } : {}),
      ...(dto.logoUrl !== undefined ? { logoUrl: dto.logoUrl } : {}),
      // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
      ...(dto.colors !== undefined ? { colors: mergedColors } : {}),
      // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
      ...(dto.fields !== undefined ? { fields: mergedFields } : {}),
      ...(dto.successRedirectUrl !== undefined
        ? { successRedirectUrl: dto.successRedirectUrl }
        : {}),
      ...(dto.customCss !== undefined ? { customCss: dto.customCss } : {}),
      ...(dto.isEnabled !== undefined ? { isEnabled: dto.isEnabled } : {}),
    };

    if (bridge) {
      return this.prisma.bookingCrmBridge.update({
        where: { clubId },
        // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
        data: { metadata: { ...currentMeta, widget: newWidget } },
      });
    }

    // Create bridge record if it doesn't exist
    return this.prisma.bookingCrmBridge.create({
      data: {
        clubId,
        // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
        metadata: { widget: newWidget },
      },
    });
  }

  generateEmbedCode(clubSlug: string, apiKey: string): Record<string, string> {
    const baseUrl = process.env.API_URL ?? 'https://api.myfitcrm.ru';
    const widgetUrl = `${baseUrl}/booking/widget/${clubSlug}`;

    return {
      iframe: `<iframe src="${widgetUrl}" width="100%" height="700" frameborder="0" style="border:none;border-radius:12px;"></iframe>`,
      jsSnippet: [
        `<div id="myfitbooking-widget"></div>`,
        `<script src="${baseUrl}/booking/widget/sdk.js" data-club="${clubSlug}" data-key="${apiKey}"></script>`,
      ].join('\n'),
      buttonPopup: [
        `<button onclick="MyFitBooking.open('${clubSlug}')" style="background:#3B82F6;color:#fff;padding:12px 24px;border:none;border-radius:8px;cursor:pointer;font-size:16px;">`,
        `  Записаться онлайн`,
        `</button>`,
        `<script src="${baseUrl}/booking/widget/sdk.js" data-club="${clubSlug}" data-key="${apiKey}" data-mode="popup"></script>`,
      ].join('\n'),
    };
  }
}
