import fs from 'fs';
import path from 'path';
import nodemailer from 'nodemailer';
import { toHms } from './formatDuration';
import type { DailyAttendanceRow } from '../services/employeeTracker';

const transporter = nodemailer.createTransport({
  host: process.env.EMAIL_HOST,
  port: Number(process.env.EMAIL_PORT) || 587,
  secure: process.env.EMAIL_SECURE === 'true',
  auth: {
    user: process.env.EMAIL_USER,
    pass: process.env.EMAIL_PASS,
  },
});

const LOGO_PATH = path.join(__dirname, '..', '..', 'public', 'eglogo.png');
const LOGO_CID = 'eglogics-logo';
const logoAttachment = fs.existsSync(LOGO_PATH)
  ? [{ filename: 'eglogo.png', path: LOGO_PATH, cid: LOGO_CID }]
  : [];

const BRAND_COLOR = '#335cb4';
const DARK_COLOR = '#111827';
const HEADER_BG = '#ffffff';

// ─── Shared Layout ──────────────────────────────────────────────────────────

const button = (href: string, label: string, color = BRAND_COLOR): string => `
  <table role="presentation" cellpadding="0" cellspacing="0" style="margin:24px auto;">
    <tr>
      <td align="center" style="border-radius:8px;background:${color};">
        <a href="${href}"
           style="display:inline-block;padding:14px 32px;font-size:15px;font-weight:600;color:#ffffff;text-decoration:none;border-radius:8px;font-family:'Segoe UI',Arial,sans-serif;">
          ${label}
        </a>
      </td>
    </tr>
  </table>
`;

const emailLayout = (bodyHtml: string, maxWidth = 560): string => `
<!DOCTYPE html>
<html>
  <body style="margin:0;padding:0;background-color:#f0f2f5;font-family:'Segoe UI',Arial,sans-serif;">
    <table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="background-color:#f0f2f5;padding:40px 16px;">
      <tr>
        <td align="center">
          <table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="max-width:${maxWidth}px;background:#ffffff;border-radius:14px;overflow:hidden;box-shadow:0 2px 10px rgba(17,24,39,0.08);">
            <tr>
              <td style="background:${BRAND_COLOR};height:5px;font-size:0;line-height:0;">&nbsp;</td>
            </tr>
            <tr>
              <td style="background:${HEADER_BG};padding:28px 32px;text-align:center;border-bottom:1px solid #eef0f3;">
                ${
                  logoAttachment.length
                    ? `<img src="cid:${LOGO_CID}" alt="EGLogics" height="38" style="display:inline-block;border:0;" />`
                    : `<span style="color:${DARK_COLOR};font-size:20px;font-weight:700;letter-spacing:0.5px;">EGLogics</span>`
                }
              </td>
            </tr>
            <tr>
              <td style="padding:40px 36px;color:#1f2937;font-size:15px;line-height:1.6;">
                ${bodyHtml}
              </td>
            </tr>
            <tr>
              <td style="padding:22px 36px;background:#f9fafb;text-align:center;border-top:1px solid #eef0f3;">
                <p style="margin:0;font-size:12px;color:#9ca3af;">This is an automated message from EGLogics Employee Engagement. Please do not reply to this email.</p>
                <p style="margin:6px 0 0;font-size:12px;color:#c1c5cb;">&copy; ${new Date().getFullYear()} EGLogics. All rights reserved.</p>
              </td>
            </tr>
          </table>
        </td>
      </tr>
    </table>
  </body>
</html>
`;

// ─── Interview Quiz ─────────────────────────────────────────────────────────

export const sendInterviewQuizEmail = async (to: string, quizLink: string): Promise<void> => {
  const html = emailLayout(`
    <h2 style="margin:0 0 12px;font-size:22px;color:${DARK_COLOR};">Interview Quiz Invitation</h2>
    <p style="margin:0 0 8px;">Hello,</p>
    <p style="margin:0;">You have been invited to take an interview quiz. Click the button below whenever you're ready to begin.</p>
    ${button(quizLink, 'Start Quiz')}
    <p style="margin:24px 0 0;color:#6b7280;font-size:13px;">If you did not expect this email, you can safely ignore it.</p>
  `);

  await transporter.sendMail({
    from: `"EGLogics" <${process.env.EMAIL_FROM || process.env.EMAIL_USER}>`,
    to,
    subject: 'Your Interview Quiz Link',
    html,
    attachments: logoAttachment,
  });
};

// ─── Employee Welcome ───────────────────────────────────────────────────────

export const sendEmployeeWelcomeEmail = async (
  to: string,
  name: string,
  setPasswordLink: string,
  downloadUrl: string | null,
): Promise<void> => {
  const downloadSection = downloadUrl
    ? `
      <hr style="border:none;border-top:1px solid #eef0f3;margin:32px 0;" />
      <p style="margin:0 0 4px;font-weight:600;color:${DARK_COLOR};">Get the desktop app</p>
      <p style="margin:0;">Download and install the desktop software to track your attendance.</p>
      ${button(downloadUrl, 'Download Desktop Software', DARK_COLOR)}
    `
    : '';

  const html = emailLayout(`
    <h2 style="margin:0 0 12px;font-size:22px;color:${DARK_COLOR};">Welcome to EGLogics, ${name}!</h2>
    <p style="margin:0 0 8px;">An account has been created for you on the Employee Engagement platform.</p>
    <p style="margin:0;">Set your password to activate your account and get started.</p>
    ${button(setPasswordLink, 'Set Password')}
    <p style="margin:0;color:#6b7280;font-size:13px;">This link will expire in 3 days.</p>
    ${downloadSection}
    <p style="margin:32px 0 0;color:#6b7280;font-size:13px;">If you did not expect this email, please contact your administrator.</p>
  `);

  await transporter.sendMail({
    from: `"EGLogics" <${process.env.EMAIL_FROM || process.env.EMAIL_USER}>`,
    to,
    subject: 'Welcome to EGLogics — Set Up Your Account',
    html,
    attachments: logoAttachment,
  });
};

// ─── Password Reset ─────────────────────────────────────────────────────────

export const sendPasswordResetEmail = async (to: string, resetLink: string): Promise<void> => {
  const html = emailLayout(`
    <h2 style="margin:0 0 12px;font-size:22px;color:${DARK_COLOR};">Password Reset Request</h2>
    <p style="margin:0 0 8px;">You requested a password reset for your account.</p>
    <p style="margin:0;">Click the button below to choose a new password. This link expires in <strong>15 minutes</strong>.</p>
    ${button(resetLink, 'Reset Password')}
    <p style="margin:24px 0 0;color:#6b7280;font-size:13px;">If you did not request this, you can safely ignore this email — your password will remain unchanged.</p>
  `);

  await transporter.sendMail({
    from: `"EGLogics" <${process.env.EMAIL_FROM || process.env.EMAIL_USER}>`,
    to,
    subject: 'Password Reset Request',
    html,
    attachments: logoAttachment,
  });
};

// ─── Daily Attendance Summary (admin) ───────────────────────────────────────

const escapeHtml = (value: string): string =>
  value
    .replace(/&/g, '&amp;')
    .replace(/</g, '&lt;')
    .replace(/>/g, '&gt;')
    .replace(/"/g, '&quot;')
    .replace(/'/g, '&#39;');

const STATUS_COLORS: Record<DailyAttendanceRow['status'], string> = {
  Completed: '#047857',
  'In Progress': '#b45309',
  Absent: '#b91c1c',
};

const TH_STYLE =
  'padding:10px 12px;text-align:left;font-size:12px;font-weight:600;color:#374151;background:#f3f4f6;border-bottom:1px solid #e5e7eb;white-space:nowrap;';
const TD_STYLE =
  'padding:9px 12px;font-size:13px;color:#1f2937;border-bottom:1px solid #eef0f3;white-space:nowrap;';

const statTile = (label: string, value: number, color: string): string => `
  <td style="padding:12px 16px;background:#f9fafb;border-radius:8px;text-align:center;">
    <div style="font-size:22px;font-weight:700;color:${color};">${value}</div>
    <div style="font-size:12px;color:#6b7280;">${label}</div>
  </td>
`;

// `date` is "yyyy-MM-dd" (Asia/Kolkata) and `rows` come from
// getDailyAttendanceReport, so durations are in seconds.
export const sendDailyAttendanceSummaryEmail = async (
  to: string,
  date: string,
  rows: DailyAttendanceRow[],
): Promise<void> => {
  const displayDate = date.split('-').reverse().join('-'); // yyyy-MM-dd -> dd-MM-yyyy
  const presentCount = rows.filter((r) => r.status !== 'Absent').length;
  const absentCount = rows.length - presentCount;
  const autoCount = rows.filter((r) => r.autoCheckedOut).length;

  const headers = [
    'Employee',
    'First Check-in',
    'Last Checkout',
    'Work',
    'Break',
    'Idle',
    'Interrupted',
    'Auto Checkout',
    'Status',
  ];

  const bodyRows = rows
    .map((r, i) => {
      const absent = r.status === 'Absent';
      const dur = (s: number) => (absent ? '-' : toHms(s));
      const bg = i % 2 === 1 ? 'background:#fafafa;' : '';
      return `
        <tr style="${bg}">
          <td style="${TD_STYLE}font-weight:600;">${escapeHtml(r.name)}</td>
          <td style="${TD_STYLE}">${r.firstCheckIn ?? '-'}</td>
          <td style="${TD_STYLE}">${r.lastCheckOut ?? '-'}</td>
          <td style="${TD_STYLE}">${dur(r.workingTime)}</td>
          <td style="${TD_STYLE}">${dur(r.totalBreakTime)}</td>
          <td style="${TD_STYLE}">${dur(r.totalIdleTime)}</td>
          <td style="${TD_STYLE}">${dur(r.totalInterruptedTime)}</td>
          <td style="${TD_STYLE}">${absent ? '-' : r.autoCheckedOut ? 'Yes' : 'No'}</td>
          <td style="${TD_STYLE}font-weight:600;color:${STATUS_COLORS[r.status]};">${r.status}</td>
        </tr>`;
    })
    .join('');

  const table = rows.length
    ? `
      <div style="overflow-x:auto;">
        <table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="border-collapse:collapse;border:1px solid #e5e7eb;">
          <thead><tr>${headers.map((h) => `<th style="${TH_STYLE}">${h}</th>`).join('')}</tr></thead>
          <tbody>${bodyRows}</tbody>
        </table>
      </div>`
    : `<p style="margin:0;color:#6b7280;">No active employees found.</p>`;

  const html = emailLayout(
    `
    <h2 style="margin:0 0 4px;font-size:22px;color:${DARK_COLOR};">Daily Attendance Summary</h2>
    <p style="margin:0 0 20px;color:#6b7280;">${displayDate} (IST) &middot; durations in HH:MM:SS</p>
    <table role="presentation" width="100%" cellpadding="0" cellspacing="8" style="margin:0 0 20px;">
      <tr>
        ${statTile('Present', presentCount, '#047857')}
        ${statTile('Absent', absentCount, '#b91c1c')}
        ${statTile('Auto Checkout', autoCount, '#b45309')}
      </tr>
    </table>
    ${table}
  `,
    960,
  );

  await transporter.sendMail({
    from: `"EGLogics" <${process.env.EMAIL_FROM || process.env.EMAIL_USER}>`,
    to,
    subject: `Daily Attendance Summary — ${displayDate}`,
    html,
    attachments: logoAttachment,
  });
};
