import { readFile } from "node:fs/promises";
import { fileURLToPath } from "node:url";
import { dirname, resolve } from "node:path";

// Helper function to convert date from yyyy-mm-dd to dd.mm.yyyy
function formatDateGerman(dateString: string): string {
  const [year, month, day] = dateString.split('-');
  return `${day}.${month}.${year}`;
}

let cachedLogoDataUrl: string | null = null;

async function getLogoDataUrl(): Promise<string | null> {
  if (cachedLogoDataUrl) return cachedLogoDataUrl;
  try {
    const __filename = fileURLToPath(import.meta.url);
    const __dirname = dirname(__filename);
    const logoPath = resolve(__dirname, "../../../assets/stargilnails_logo_transparent.png");
    const buf = await readFile(logoPath);
    const base64 = buf.toString("base64");
    cachedLogoDataUrl = `data:image/png;base64,${base64}`;
    return cachedLogoDataUrl;
  } catch {
    return null;
  }
}

async function renderBrandedEmail(title: string, bodyHtml: string): Promise<string> {
  const logo = await getLogoDataUrl();
  const domain = process.env.DOMAIN || 'localhost:5173';
  const protocol = domain.includes('localhost') ? 'http' : 'https';
  const homepageUrl = `${protocol}://${domain}`;
  
  return `
  <div style="font-family: Arial, sans-serif; color: #0f172a; background:#fdf2f8; padding:24px;">
    <table role="presentation" width="100%" cellspacing="0" cellpadding="0" style="max-width:640px; margin:0 auto; background:#ffffff; border-radius:12px; overflow:hidden; box-shadow:0 1px 3px rgba(0,0,0,0.06)">
      <tr>
        <td style="padding:24px 24px 0 24px; text-align:center;">
          ${logo ? `<img src="${logo}" alt="Stargirlnails" style="width:120px; height:auto; display:inline-block;" />` : `<div style=\"font-size:24px\">💅</div>`}
          <h1 style="margin:16px 0 0 0; font-size:22px; color:#db2777;">${title}</h1>
        </td>
      </tr>
      <tr>
        <td style="padding:16px 24px 24px 24px;">
          <div style="font-size:16px; line-height:1.6; color:#334155;">
            ${bodyHtml}
          </div>
          <hr style="border:none; border-top:1px solid #f1f5f9; margin:24px 0" />
          <div style="text-align:center; margin-bottom:16px;">
            <a href="${homepageUrl}" style="display: inline-block; background-color: #db2777; color: white; padding: 12px 24px; text-decoration: none; border-radius: 6px; font-weight: 600; font-size: 14px;">Zur Website</a>
          </div>
          <div style="font-size:12px; color:#64748b; text-align:center;">
            &copy; ${new Date().getFullYear()} Stargirlnails Kiel • Professional Nail Care
          </div>
        </td>
      </tr>
    </table>
  </div>`;
}

export async function renderBookingPendingHTML(params: { name: string; date: string; time: string }) {
  const { name, date, time } = params;
  const formattedDate = formatDateGerman(date);
  const inner = `
    <p>Hallo ${name},</p>
    <p>wir haben deine Anfrage für <strong>${formattedDate}</strong> um <strong>${time}</strong> erhalten.</p>
    <p>Wir bestätigen deinen Termin in Kürze. Du erhältst eine weitere E-Mail, sobald der Termin bestätigt ist.</p>
    <p>Liebe Grüße,<br/>Stargirlnails Kiel</p>
  `;
  return renderBrandedEmail("Deine Terminanfrage ist eingegangen", inner);
}

export async function renderBookingConfirmedHTML(params: { name: string; date: string; time: string; cancellationUrl?: string }) {
  const { name, date, time, cancellationUrl } = params;
  const formattedDate = formatDateGerman(date);
  const inner = `
    <p>Hallo ${name},</p>
    <p>wir haben deinen Termin am <strong>${formattedDate}</strong> um <strong>${time}</strong> bestätigt.</p>
    <p>Wir freuen uns auf dich!</p>
    <div style="background-color: #f8fafc; border-left: 4px solid #db2777; padding: 16px; margin: 20px 0; border-radius: 4px;">
      <p style="margin: 0; font-weight: 600; color: #db2777;">📋 Wichtiger Hinweis:</p>
      <p style="margin: 8px 0 0 0; color: #475569;">Die Allgemeinen Geschäftsbedingungen (AGB) findest du im Anhang dieser E-Mail. Bitte lies sie vor deinem Termin durch.</p>
    </div>
    ${cancellationUrl ? `
    <div style="background-color: #fef3f2; border-left: 4px solid #ef4444; padding: 16px; margin: 20px 0; border-radius: 4px;">
      <p style="margin: 0; font-weight: 600; color: #ef4444;">❌ Termin stornieren:</p>
      <p style="margin: 8px 0 12px 0; color: #475569;">Falls du den Termin stornieren möchtest, kannst du das hier tun:</p>
      <a href="${cancellationUrl}" style="display: inline-block; background-color: #ef4444; color: white; padding: 12px 24px; text-decoration: none; border-radius: 6px; font-weight: 600;">Termin stornieren</a>
    </div>
    ` : ''}
    <p>Liebe Grüße,<br/>Stargirlnails Kiel</p>
  `;
  return renderBrandedEmail("Termin bestätigt", inner);
}

export async function renderBookingCancelledHTML(params: { name: string; date: string; time: string }) {
  const { name, date, time } = params;
  const formattedDate = formatDateGerman(date);
  const inner = `
    <p>Hallo ${name},</p>
    <p>dein Termin am <strong>${formattedDate}</strong> um <strong>${time}</strong> wurde abgesagt.</p>
    <p>Bitte buche einen neuen Termin. Bei Fragen helfen wir dir gerne weiter.</p>
    <p>Liebe Grüße,<br/>Stargirlnails Kiel</p>
  `;
  return renderBrandedEmail("Termin abgesagt", inner);
}

export async function renderAdminBookingNotificationHTML(params: { 
  name: string; 
  date: string; 
  time: string; 
  treatment: string;
  phone: string;
  notes?: string;
  hasInspirationPhoto: boolean;
}) {
  const { name, date, time, treatment, phone, notes, hasInspirationPhoto } = params;
  const formattedDate = formatDateGerman(date);
  const inner = `
    <p>Hallo Admin,</p>
    <p>eine neue Buchungsanfrage ist eingegangen:</p>
    <div style="background-color: #f8fafc; border-left: 4px solid #db2777; padding: 16px; margin: 20px 0; border-radius: 4px;">
      <p style="margin: 0; font-weight: 600; color: #db2777;">📅 Buchungsdetails:</p>
      <ul style="margin: 8px 0 0 0; color: #475569; list-style: none; padding: 0;">
        <li><strong>Name:</strong> ${name}</li>
        <li><strong>Telefon:</strong> ${phone}</li>
        <li><strong>Behandlung:</strong> ${treatment}</li>
        <li><strong>Datum:</strong> ${formattedDate}</li>
        <li><strong>Uhrzeit:</strong> ${time}</li>
        ${notes ? `<li><strong>Notizen:</strong> ${notes}</li>` : ''}
        <li><strong>Inspiration-Foto:</strong> ${hasInspirationPhoto ? '✅ Im Anhang verfügbar' : '❌ Kein Foto hochgeladen'}</li>
      </ul>
    </div>
    <p>Bitte logge dich in das Admin-Panel ein, um die Buchung zu bestätigen oder abzulehnen.</p>
    <p>Liebe Grüße,<br/>Stargirlnails System</p>
  `;
  return renderBrandedEmail("Neue Buchungsanfrage - Admin-Benachrichtigung", inner);
}


