import { pool } from '../db';
import { sendMail } from '../email';

const thb = (n: number) => `฿${n.toLocaleString('th-TH', { minimumFractionDigits: 2 })}`;

const thaiMonth = (date: Date) =>
  date.toLocaleDateString('th-TH', { month: 'long', year: 'numeric' });

// ── Query ─────────────────────────────────────────────────────────────────────

interface MachineRow {
  machine_id: string;
  serial_number: string;
  color: string | null;
  cash_total: string;
  promptpay_total: string;
  grand_total: string;
  tx_count: string;
}

interface CustomerRow {
  id: string;
  name: string;
  email: string;
  phone: string;
}

async function getMonthlyData(year: number, month: number) {
  // month is 1-based
  const from = `${year}-${String(month).padStart(2, '0')}-01`;
  const to   = new Date(year, month, 0).toISOString().slice(0, 10); // last day

  const customers = await pool.query<CustomerRow>(
    `SELECT id, name, email, phone
     FROM simo_customers
     WHERE email IS NOT NULL AND email != ''
     ORDER BY name`,
  );

  const results = [];

  for (const c of customers.rows) {
    const machines = await pool.query<MachineRow>(
      `SELECT
         m.id                                        AS machine_id,
         m.serial_number,
         m.color,
         COALESCE(SUM(ap.coin), 0)::float            AS cash_total,
         COALESCE(SUM(ap.pay_by_wechat + ap.pay_by_rabbit_line_pay
                      + ap.pay_by_promptpay + ap.pay_by_truemoney
                      + ap.pay_by_point), 0)::float  AS promptpay_total,
         COALESCE(SUM(ap.coin + ap.pay_by_wechat + ap.pay_by_rabbit_line_pay
                      + ap.pay_by_promptpay + ap.pay_by_truemoney
                      + ap.pay_by_point), 0)::float  AS grand_total,
         COUNT(ap.id)::int                           AS tx_count
       FROM simo_machines m
       LEFT JOIN amount_payment ap
         ON ap.serial_no = m.serial_number
         AND ap.time1 >= m.purchase_date
         AND ap.time1 BETWEEN $1 AND $2::date + INTERVAL '1 day'
       WHERE m.customer_id = $3
       GROUP BY m.id, m.serial_number, m.color
       ORDER BY m.serial_number`,
      [from, to, c.id],
    );

    const totalRevenue = machines.rows.reduce((s, m) => s + Number(m.grand_total), 0);

    results.push({ customer: c, machines: machines.rows, totalRevenue, from, to });
  }

  return results;
}

// ── Email HTML Template ───────────────────────────────────────────────────────

function buildHtml(
  customer: CustomerRow,
  machines: MachineRow[],
  totalRevenue: number,
  monthLabel: string,
) {
  const machineRows = machines.map((m, i) => {
    const cash       = Number(m.cash_total);
    const promptpay  = Number(m.promptpay_total);
    const total      = Number(m.grand_total);
    const txCount    = Number(m.tx_count);
    return `
    <tr>
      <td style="padding:14px 16px;border-bottom:1px solid #F1F5F9;color:#1E293B;font-weight:600">
        เครื่องที่ ${i + 1}<br>
        <span style="font-family:monospace;font-size:12px;color:#64748B;font-weight:400">${m.serial_number}</span>
        ${m.color ? `<span style="font-size:11px;color:#94A3B8;margin-left:4px">(${m.color})</span>` : ''}
      </td>
      <td style="padding:14px 16px;border-bottom:1px solid #F1F5F9;text-align:center;color:#64748B;font-size:13px">${txCount} รายการ</td>
      <td style="padding:14px 16px;border-bottom:1px solid #F1F5F9;text-align:right;color:#059669;font-weight:600">${thb(cash)}</td>
      <td style="padding:14px 16px;border-bottom:1px solid #F1F5F9;text-align:right;color:#2563EB;font-weight:600">${thb(promptpay)}</td>
      <td style="padding:14px 16px;border-bottom:1px solid #F1F5F9;text-align:right;color:#1E293B;font-weight:700">${thb(total)}</td>
    </tr>`;
  }).join('');

  const totalTx = machines.reduce((s, m) => s + Number(m.tx_count), 0);

  return `<!DOCTYPE html>
<html lang="th">
<head><meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1"></head>
<body style="margin:0;padding:0;background:#F8FAFC;font-family:'Segoe UI',sans-serif">
  <div style="max-width:600px;margin:32px auto;background:#FFFFFF;border-radius:16px;overflow:hidden;box-shadow:0 4px 24px rgba(0,0,0,0.08)">

    <!-- Header -->
    <div style="background:linear-gradient(135deg,#0F172A 0%,#1E3A5F 60%,#1E40AF 100%);padding:32px 32px 28px">
      <div style="display:inline-block;background:rgba(255,255,255,0.15);border-radius:12px;padding:10px 14px;margin-bottom:16px">
        <span style="color:#FFFFFF;font-size:22px;font-weight:800;letter-spacing:-0.5px">SIMO 1</span>
      </div>
      <h1 style="margin:0 0 6px;color:#FFFFFF;font-size:20px;font-weight:700">สรุปยอดรายรับประจำเดือน</h1>
      <p style="margin:0;color:#93C5FD;font-size:14px">${monthLabel}</p>
    </div>

    <!-- Greeting -->
    <div style="padding:28px 32px 0">
      <p style="margin:0 0 8px;color:#475569;font-size:14px">เรียน คุณ${customer.name}</p>
      <p style="margin:0;color:#64748B;font-size:13px;line-height:1.6">
        ขอนำส่งสรุปยอดรายรับสาขาของท่านประจำเดือน${monthLabel} โดยมีรายละเอียดดังต่อไปนี้
      </p>
    </div>

    <!-- Total card -->
    <div style="margin:24px 32px;background:linear-gradient(135deg,#EFF6FF,#DBEAFE);border-radius:12px;padding:20px 24px;border:1px solid #BFDBFE">
      <div style="color:#1E40AF;font-size:12px;font-weight:600;text-transform:uppercase;letter-spacing:0.5px;margin-bottom:6px">ยอดรายรับรวมทั้งหมด</div>
      <div style="color:#1E3A8A;font-size:32px;font-weight:800">${thb(totalRevenue)}</div>
      <div style="color:#3B82F6;font-size:12px;margin-top:4px">${totalTx} รายการ · ${machines.length} เครื่อง</div>
    </div>

    <!-- Machine table -->
    <div style="padding:0 32px">
      <h2 style="margin:0 0 12px;color:#1E293B;font-size:14px;font-weight:700">รายละเอียดแยกตามเครื่อง</h2>
      <table style="width:100%;border-collapse:collapse;border-radius:12px;overflow:hidden;border:1px solid #E2E8F0">
        <thead>
          <tr style="background:#F8FAFC">
            <th style="padding:12px 16px;text-align:left;color:#64748B;font-size:12px;font-weight:600">เครื่อง</th>
            <th style="padding:12px 16px;text-align:center;color:#64748B;font-size:12px;font-weight:600">รายการ</th>
            <th style="padding:12px 16px;text-align:right;color:#059669;font-size:12px;font-weight:600">เงินสด</th>
            <th style="padding:12px 16px;text-align:right;color:#2563EB;font-size:12px;font-weight:600">พร้อมเพย์</th>
            <th style="padding:12px 16px;text-align:right;color:#1E293B;font-size:12px;font-weight:600">รวม</th>
          </tr>
        </thead>
        <tbody>${machineRows}</tbody>
        <tfoot>
          <tr style="background:#F8FAFC">
            <td colspan="2" style="padding:14px 16px;color:#1E293B;font-weight:700;font-size:14px">รวมทั้งสิ้น</td>
            <td style="padding:14px 16px;text-align:right;color:#059669;font-weight:700">
              ${thb(machines.reduce((s, m) => s + Number(m.cash_total), 0))}
            </td>
            <td style="padding:14px 16px;text-align:right;color:#2563EB;font-weight:700">
              ${thb(machines.reduce((s, m) => s + Number(m.promptpay_total), 0))}
            </td>
            <td style="padding:14px 16px;text-align:right;color:#1E3A8A;font-weight:800;font-size:15px">
              ${thb(totalRevenue)}
            </td>
          </tr>
        </tfoot>
      </table>
    </div>

    <!-- Note -->
    <div style="margin:24px 32px;background:#FFFBEB;border-radius:10px;padding:14px 16px;border-left:3px solid #F59E0B">
      <p style="margin:0;color:#92400E;font-size:12px;line-height:1.6">
        หากพบข้อมูลไม่ถูกต้อง กรุณาติดต่อเจ้าหน้าที่เพื่อตรวจสอบ
      </p>
    </div>

    <!-- Footer -->
    <div style="padding:20px 32px 28px;border-top:1px solid #F1F5F9">
      <p style="margin:0;color:#94A3B8;font-size:11px;text-align:center;line-height:1.6">
        © 2026 SIMO 1 Massage Chair System · อีเมลนี้ถูกส่งโดยอัตโนมัติ กรุณาอย่าตอบกลับ
      </p>
    </div>

  </div>
</body>
</html>`;
}

// ── Main export ───────────────────────────────────────────────────────────────

export async function sendMonthlyReports(year: number, month: number) {
  const data   = await getMonthlyData(year, month);
  const date   = new Date(year, month - 1, 1);
  const label  = thaiMonth(date);
  const subject = `SIMO 1 — สรุปยอดรายรับ ${label}`;

  let sent = 0;
  let skipped = 0;
  const errors: string[] = [];

  for (const { customer, machines, totalRevenue } of data) {
    if (machines.length === 0) { skipped++; continue; }
    try {
      const html = buildHtml(customer, machines, totalRevenue, label);
      await sendMail(customer.email, subject, html);
      sent++;
      console.log(`✅ ส่งให้ ${customer.name} (${customer.email})`);
    } catch (e) {
      errors.push(`${customer.email}: ${String(e)}`);
      console.error(`❌ ส่งไม่สำเร็จ ${customer.email}:`, e);
    }
  }

  return { sent, skipped, errors, total: data.length };
}
