import { Request, Response } from 'express';
import * as captureLeadService from './captureLead.service';
import catchAsync from '@/shared/utils/catchAsync';
import responseCodes from '@/shared/utils/responseCode/responseCode';
import { pick } from '@/shared/utils';
import config from '@/shared/config/config';
import {
  authenticateCompanyMetaAccount,
  companyMetaAccountCallback,
} from '../meta/meta.platform';

const { CaptureLeadResponseCodes } = responseCodes;

export const createCaptureLead = catchAsync(
  async (req: Request, res: Response) => {
    const companyId = req.user.company.id;
    const userId = req.user.id;

    const payload = {
      ...req.body,
      company: companyId,
    };

    const lead = await captureLeadService.createCaptureLead(payload, userId);

    const responseData: any = { ...lead };
    if (String(lead.platform) === 'custom_form') {
      const webhookUrl =
        lead.webhookUrl ||
        `${config.backendUrl}/webhook/leads/${companyId}/${lead.id}`;
      responseData.formEmbedHtml = `
<form 
  action="${webhookUrl}" 
  method="POST"
  target="mkf_hidden_iframe"
  onsubmit="(function(f){var b=f.querySelector('button[type=submit]');if(b){b.disabled=true;b.style.opacity='0.8';b.style.cursor='not-allowed';b.innerHTML='<svg xmlns=&quot;http://www.w3.org/2000/svg&quot; width=&quot;18&quot; height=&quot;18&quot; viewBox=&quot;0 0 24 24&quot; fill=&quot;none&quot; stroke=&quot;white&quot; stroke-width=&quot;2&quot; stroke-linecap=&quot;round&quot; stroke-linejoin=&quot;round&quot; style=&quot;margin-right:8px;vertical-align:-3px;&quot;><circle cx=&quot;12&quot; cy=&quot;12&quot; r=&quot;10&quot; opacity=&quot;.25&quot;></circle><path d=&quot;M12 2a10 10 0 0 1 10 10&quot;><animateTransform attributeName=&quot;transform&quot; attributeType=&quot;XML&quot; type=&quot;rotate&quot; from=&quot;0 12 12&quot; to=&quot;360 12 12&quot; dur=&quot;0.8s&quot; repeatCount=&quot;indefinite&quot;/></path></svg>Sending…';}})(this)"
  style="
    max-width: 420px;
    margin: 60px auto;
    padding: 32px 26px;
    border-radius: 14px;
    box-shadow: 0 4px 20px rgba(0,0,0,0.08);
    background: #fff;
    font-family: 'Inter', 'Segoe UI', sans-serif;
  "
>
  <div style="text-align:center; margin-bottom:22px;">
    <img 
      src='https://makanify.com/logo.png' 
      alt='Makanify Logo' 
      style="height:48px; margin-bottom:10px;"
      onerror="this.style.display='none'"
    />
    <h2 style="color:#222; font-weight:600; margin:0;">Contact Form</h2>
  </div>

  <input 
    type="text" 
    name="name" 
    placeholder="Your Name" 
    required
    style="
      width:100%;
      padding:12px 14px;
      margin-bottom:16px;
      border:1px solid #e0e0e0;
      border-radius:8px;
      font-size:15px;
      outline:none;
      transition:0.25s;
      box-sizing:border-box;
    "
    onfocus="this.style.borderColor='#F15A29'"
    onblur="this.style.borderColor='#e0e0e0'"
  />

  <input 
    type="email" 
    name="email" 
    placeholder="Your Email" 
    required
    style="
      width:100%;
      padding:12px 14px;
      margin-bottom:16px;
      border:1px solid #e0e0e0;
      border-radius:8px;
      font-size:15px;
      outline:none;
      transition:0.25s;
      box-sizing:border-box;
    "
    onfocus="this.style.borderColor='#F15A29'"
    onblur="this.style.borderColor='#e0e0e0'"
  />

  <input 
    type="tel" 
    name="phone" 
    placeholder="Your Phone" 
    required
    style="
      width:100%;
      padding:12px 14px;
      margin-bottom:16px;
      border:1px solid #e0e0e0;
      border-radius:8px;
      font-size:15px;
      outline:none;
      transition:0.25s;
      box-sizing:border-box;
    "
    onfocus="this.style.borderColor='#F15A29'"
    onblur="this.style.borderColor='#e0e0e0'"
  />

  <textarea 
    name="message" 
    placeholder="Message"
    style="
      width:100%;
      padding:12px 14px;
      height:110px;
      margin-bottom:22px;
      border:1px solid #e0e0e0;
      border-radius:8px;
      font-size:15px;
      outline:none;
      resize:none;
      transition:0.25s;
      box-sizing:border-box;
    "
    onfocus="this.style.borderColor='#F15A29'"
    onblur="this.style.borderColor='#e0e0e0'"
  ></textarea>

  <button 
    type="submit"
    style="
      width:100%;
      padding:14px;
      background:#F15A29;
      color:#fff;
      border:none;
      border-radius:8px;
      font-size:16px;
      font-weight:500;
      cursor:pointer;
      transition:0.25s;
    "
    onmouseover="this.style.background='#d94d22'"
    onmouseout="this.style.background='#F15A29'"
  >
    Submit
  </button>
  <div class="mkf-toast" style="display:none;position:fixed;left:50%;bottom:26px;transform:translateX(-50%);background:#16a34a;color:#fff;border-radius:12px;padding:12px 16px;font-size:14px;box-shadow:0 10px 24px rgba(2,6,23,0.18);">We received your message — we will contact you soon.</div>
</form>
<iframe name="mkf_hidden_iframe" style="display:none" onload="(function(iframe){var f=iframe.previousElementSibling; if(!f||f.tagName!=='FORM') return; var b=f.querySelector('button[type=submit]'); if(b){b.disabled=false;b.style.opacity='';b.style.cursor='';b.textContent='Submit';} var t=f.querySelector('.mkf-toast'); if(t){t.style.display='block'; t.style.opacity='1'; setTimeout(function(){t.style.opacity='0'; t.style.display='none';}, 3500);} try{f.reset();}catch(e){} })(this)"></iframe>`;
    }

    res.success(
      responseData,
      CaptureLeadResponseCodes.SUCCESS,
      'Capture Lead Created Successfully',
    );
  },
);

export const updateCaptureLead = catchAsync(
  async (req: Request, res: Response) => {
    const { id } = pick(req.params, ['id']);
    const data = await captureLeadService.updateCaptureLead(
      id,
      req.body,
      req.user,
    );
    res.success(
      data,
      CaptureLeadResponseCodes.SUCCESS,
      'Capture Lead Updated Successfully',
    );
  },
);

export const getCaptureLeadById = catchAsync(
  async (req: Request, res: Response) => {
    const { id } = pick(req.params, ['id']);
    const lead = await captureLeadService.getCaptureLeadById(id);
    res.success(
      lead,
      CaptureLeadResponseCodes.SUCCESS,
      'Capture Lead Fetched Successfully',
    );
  },
);

export const getCaptureLead = catchAsync(
  async (req: Request, res: Response) => {
    const filter = pick(req.query, [
      'search',
      'platform',
      'interestType',
      'sourceId',
      'projectId',
      'isActive',
    ]);
    const options = pick(req.query, [
      'sortBy',
      'limit',
      'page',
      'fields',
      'populate',
      'includeTimeStamps',
    ]);

    const leads = await captureLeadService.queryCaptureLead(
      { ...filter, company: req.user.company.id },
      options,
    );
    res.success(
      leads,
      CaptureLeadResponseCodes.SUCCESS,
      'Capture Leads Fetched Successfully',
    );
  },
);

export const deleteCaptureLeadById = catchAsync(
  async (req: Request, res: Response) => {
    const { id } = pick(req.params, ['id']);
    const data = await captureLeadService.deleteCaptureLead(id, req.user);
    res.success(
      data,
      CaptureLeadResponseCodes.SUCCESS,
      'Capture Lead Deleted Successfully',
    );
  },
);

export const authCompanyMetaAccount = catchAsync(
  async (req: Request, res: Response) => {
    const {
      company: { id: companyId },
      id: userId,
    } = req.user;

    const data = await authenticateCompanyMetaAccount(companyId, userId);
    res.success(
      data,
      CaptureLeadResponseCodes.SUCCESS,
      'Meta Account Authenticated Successfully',
    );
  },
);
export const authCompanyMetaAccountCallback = catchAsync(
  async (req: Request, res: Response) => {
    const { code, state } = pick(req.query, ['code', 'state']);

    if (!state || typeof state !== 'string') {
      console.error('OAuth state parameter missing or invalid.');
      return;
    }

    let stateObject;
    try {
      const decodedStateUri = decodeURIComponent(state);

      const buffer = Buffer.from(decodedStateUri, 'base64');
      const stateJson = buffer.toString('utf8');

      stateObject = JSON.parse(stateJson);
    } catch (_error) {
      throw new Error('Invalid state parameter format.');
    }

    const { userId, companyId } = stateObject;

    const data = await companyMetaAccountCallback(companyId, userId, code);

    // ensure we send proper content-type
    res.setHeader('Content-Type', 'text/html; charset=utf-8');
    return res.status(200).send(data);
  },
);
