import {
  Body,
  Controller,
  Get,
  Post,
  Request,
  UseGuards,
} from '@nestjs/common';
import { JwtAuthGuard } from '../auth/guards/jwt-auth.guard';
import { MailService } from '../mail/mail.service';
import { UsersService } from './users.service';
import { AppMailerService } from './../mailer/mailer.service';
import {
  TemplateEmailData,
  TemplateOrderData,
  TemplateOrderMail,
  TemplateOrderMail2,
} from '../mail/template/order';
import { ConfigService } from '@nestjs/config';
import { HubspotSubmitDto } from './dto/hubspot-submit.dto';
import { InjectModel } from '@nestjs/mongoose';
import { Model } from 'mongoose';
import { Quote, QuoteDocument } from '../quote/schemas/quote.schema';
import { addDays } from './hubspot-payload.builder';

@Controller({
  path: 'users',
  version: '1',
})
export class UsersController {
  constructor(
    private readonly mailService: MailService,
    private readonly usersService: UsersService,
    private readonly appMailerServices: AppMailerService,
    private readonly configService: ConfigService,
    @InjectModel(Quote.name) private readonly quoteModel: Model<QuoteDocument>,
  ) {}

  @UseGuards(JwtAuthGuard)
  @Get('profile')
  getProfile(@Request() req) {
    return {
      user: req.user,
    };
  }

  @Post('delivery')
  postDelivery(@Body() data: { postcode: string }) {
    return this.usersService.postDelivery(data);
  }

  @Post('mail/order')
  async sendOrder(@Body() body: TemplateOrderData) {
    const serveradress = this.configService.get<string>('SERVER_ADDRESS');


    // const msg = {
    //   to: body.profile.email,
    //   subject:
    //     'Geschafft! Richtpreis Ihrer Terrassendach Konfiguration ist kalkuliert',
    //   html: TemplateOrderMail(body),
    //   attachments: [
    //     {
    //       filename: 'snapshot_1.jpg',
    //       content: body.screenScene.replace(/^data:image\/png;base64,/, ''),
    //       encoding: 'base64',
    //       contentType: 'image/png',
    //       content_id: 'snapshot1',
    //       disposition: 'inline',
    //     },
    //     {
    //       filename: 'snapshot_2.jpg',
    //       content: body.screenSceneTop.replace(/^data:image\/png;base64,/, ''),
    //       encoding: 'base64',
    //       contentType: 'image/png',
    //       content_id: 'snapshot2',
    //       disposition: 'inline',
    //     },
    //   ],
    // };

    // const msg2 = {
    //   to: 'info@thermogreen.ch',
    //   bcc: 'Daniel.Tiso@thermogreen.ch',
    //   subject: `Thermogreen Konfigurator`,
    //   html: TemplateOrderMail2(body),
    //   attachments: [
    //     {
    //       filename: 'snapshot_1.jpg',
    //       content: body.screenScene.replace(/^data:image\/png;base64,/, ''),
    //       encoding: 'base64',
    //       contentType: 'image/png',
    //       content_id: 'snapshot1',
    //       disposition: 'inline',
    //     },
    //     {
    //       filename: 'snapshot_2.jpg',
    //       content: body.screenSceneTop.replace(/^data:image\/png;base64,/, ''),
    //       encoding: 'base64',
    //       contentType: 'image/png',
    //       content_id: 'snapshot2',
    //       disposition: 'inline',
    //     },
    //   ],
    // };

    // const [success, success2] = await Promise.all([
    //   this.appMailerServices.send(msg),
    //   this.appMailerServices.send(msg2),
    // ]);
    // return { success, success2 };

    const msg = {
      // to: [body.profile.email, 'dan@digitalartflow.com'],
      to: body.profile.email,
      from: 'sales@thermogreen.ch',
      subject: `Geschafft! Richtpreis Ihrer Terrassendach Konfiguration ist kalkuliert`,
      html: TemplateOrderMail(body, serveradress),
      attachments: [
        {
          filename: 'snapshot_1.jpg',
          content: body.screenScene.replace(/^data:image\/png;base64,/, ''),
          contentType: 'image/png',
          content_id: 'snapshot1',
          disposition: 'inline',
        },
        {
          filename: 'snapshot_2.jpg',
          content: body.screenSceneTop.replace(/^data:image\/png;base64,/, ''),
          contentType: 'image/png',
          content_id: 'snapshot2',
          disposition: 'inline',
        },
      ],
    };

    const msg2 = {
      // to: ['info@thermogreen.ch', 'dan@digitalartflow.com'],
      to: 'info@thermogreen.ch',
      from: 'sales@thermogreen.ch',
      bcc: ['Daniel.Tiso@thermogreen.ch'],
      subject: `Thermogreen Konfigurator`,
      html: TemplateOrderMail2(body, serveradress),
      attachments: [
        {
          filename: 'snapshot_1.jpg',
          content: body.screenScene.replace(/^data:image\/png;base64,/, ''),
          contentType: 'image/png',
          content_id: 'snapshot1',
          disposition: 'inline',
        },
        {
          filename: 'snapshot_2.jpg',
          content: body.screenSceneTop.replace(/^data:image\/png;base64,/, ''),
          contentType: 'image/png',
          content_id: 'snapshot2',
          disposition: 'inline',
        },
      ],
    };

    const [success, success2] = await Promise.all([
      this.mailService.send(msg),
      this.mailService.send(msg2),
    ]);
    return { success, success2 };

    console.log('send');
  }

  @UseGuards(JwtAuthGuard)
  @Post('mail/hubspot-progress')
  async hubspotProgress(
    @Request() req,
    @Body() body: HubspotSubmitDto,
  ) {
    await this.submitToHubspot(body, req.user?.email);
    return { success: true };
  }

  private async submitToHubspot(
    body: HubspotSubmitDto,
    salesUserEmail: string,
  ) {
    const quote = await this.quoteModel.findById(body.quoteId).lean();
    if (!quote || !quote.configurationPayload) {
      console.error('Quote or configurationPayload not found', body.quoteId);
      return;
    }

    const saved = quote.configurationPayload;
    const configurationPayload = {
      ...saved,
      sales_user: { email: salesUserEmail },
      deal: {
        ...(saved.deal ?? {}),
        close_date: addDays(60),
      },
      quote: {
        ...(saved.quote ?? {}),
        expiration_date: addDays(30),
        comments_to_buyer: `${body.comment ?? saved.quote?.comments_to_buyer ?? ''}`,
      },
    };

    const endpoint = `https://api.hsforms.com/submissions/v3/integration/submit/${this.configService.get<string>(
      'HUBSPOT_PORTAL',
    )}/${this.configService.get<string>('HUBSPOT_FORM2')}`;

    const formData = {
      fields: [
        { name: 'email', value: `${configurationPayload.contact?.email ?? ''}` },
        { name: 'config_id', value: `${configurationPayload.config_id ?? ''}` },
        { name: 'sales_user_email', value: salesUserEmail },
        {
          name: 'configuration_payload',
          value: JSON.stringify(configurationPayload),
        },
        { name: 'konfigurator_pending_flag', value: 'true' },
        { name: 'push_token', value: '5b22f9eb4c89e5954983ba982b2ba677' },
      ],
    };

    const serveradress = this.configService.get<string>('SERVER_ADDRESS');

    console.log('+++', formData);

    if (!serveradress.includes('localhost')) {
      console.log(serveradress);
      const url =
        endpoint +
        `?hapikey=${this.configService.get<string>('HUBSPOT_KEY')}`;

      try {
        const response = await fetch(url, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
          body: JSON.stringify(formData),
        });

        if (response.ok) {
          console.log('Данные успешно отправлены в HubSpot.');
        } else {
          console.error('Произошла ошибка:', response.statusText);
        }
      } catch (error) {
        console.error('Произошла ошибка при отправке запроса:', error);
      }
    }
  }

  @Post('mail/email')
  async sendEmail(@Body() body: TemplateEmailData) {
    console.log(body, 'body');

    const endpoint = `https://api.hsforms.com/submissions/v3/integration/submit/${this.configService.get<string>(
      'HUBSPOT_PORTAL',
    )}/${this.configService.get<string>('HUBSPOT_FORM1')}`;

    const formData = {
      fields: [
        {
          name: 'firstname',
          value: `${body.firstName}`,
        },
        {
          name: 'lastname',
          value: `${body.lastName}`,
        },
        {
          name: 'email',
          value: `${body.email}`,
        },

        {
          name: 'phone',
          value: `${body.phone}`,
        },

        {
          name: 'zip',
          value: `${body.postcode}`,
        },
        {
          name: 'city',
          value: `${body.location}`,
        },
      ],
    };

    const serveradress = this.configService.get<string>('SERVER_ADDRESS');

    if (!serveradress.includes('localhost')) {
      fetch(
        endpoint + `?hapikey=${this.configService.get<string>('HUBSPOT_KEY')}`,
        {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
          body: JSON.stringify(formData),
        },
      )
        .then((response) => {
          if (response.ok) {
            console.log('send to HubSpot.');
          } else {
            console.error(response.statusText);
          }
        })
        .catch((error) => {
          console.error(error);
        });
    }

    const msg = {
      // to: ['sales@thermogreen.ch', 'dan@digitalartflow.com'],
      to: 'sales@thermogreen.ch',
      from: 'sales@thermogreen.ch',
      subject: `User data`,
      html: `${body.firstName} ${body.lastName}<br/> ${body.email}<br/>${
        body.phone
      }<br/>${body.postcode}<br/>${body.location && body.location}`,
    };
    this.mailService.send(msg);
  }
}
