import { format } from "date-fns";

interface ViolationEmailData {
  ownerName: string;
  associationName: string;
  managementCompany?: string;
  associationAddress?: string;
  managementPhone?: string;
  managementEmail?: string;
  managementWebsite?: string;
  propertyAddress: string;
  violationType: string;
  noticeLevel: string;
  articleSection?: string;
  citationText?: string;
  requestedAction?: string;
  violationDate: string;
  dueDate?: string;
  description?: string;
  notes?: string;
  photoUrls?: string[];
  violationId?: string;
  appUrl?: string;
  certifiedMail?: string;
}

function getOpeningParagraph(noticeType: string, associationName: string, dueDate: string): string {
  const type = (noticeType || "").toLowerCase();
  if (type.includes("second"))
    return `This letter serves as a <strong>SECOND NOTICE</strong> regarding the violation at your property. A recent inspection has confirmed that the condition previously cited has not been corrected. As a member of the ${associationName}, you are required to maintain your property in accordance with the community's governing documents. Please rectify this violation by <strong>${dueDate}</strong> to avoid further escalation of this matter.`;
  if (type.includes("third") || type.includes("final") || type.includes("intent"))
    return `This is a <strong>FINAL NOTICE</strong> regarding the ongoing violation on your property. Despite previous communications, the violation remains uncorrected. Failure to remedy this situation by <strong>${dueDate}</strong> may result in the imposition of fines, suspension of use rights, or legal action as authorized by the ${associationName}'s governing documents and Florida Statutes. Please treat this matter with urgency.`;
  return `During a recent inspection of the community, we noted that your property is out of compliance with ${associationName}'s Covenants, Conditions, and Restrictions (CC&Rs). Your property violates the governing documents, including, but not limited to, the referenced section below. This notice is being sent as an initial friendly reminder asking that you correct the situation listed below. Please take the necessary steps to correct the situation by <strong>${dueDate || "the specified deadline"}</strong> to avoid further action.`;
}

export function generateViolationNoticeEmailHtml(data: ViolationEmailData): string {
  const {
    ownerName, associationName, managementCompany, associationAddress,
    managementPhone, managementEmail, managementWebsite,
    propertyAddress, violationType, noticeLevel, articleSection,
    citationText, requestedAction, violationDate, dueDate,
    description, notes, photoUrls, violationId, appUrl = "https://avria.cloud",
    certifiedMail,
  } = data;

  const formattedDueDate = dueDate || "N/A";
  const openingParagraph = getOpeningParagraph(noticeLevel, associationName, formattedDueDate);
  const today = format(new Date(), "MMMM d, yyyy");

  const contactParts: string[] = [];
  if (managementPhone) contactParts.push(managementPhone);
  if (managementEmail) contactParts.push(managementEmail);
  if (managementWebsite) contactParts.push(managementWebsite);

  const violationBox = `
    <table width="100%" cellpadding="12" cellspacing="0" style="border:2px solid #333;margin:16px 0;">
      <tr><td>
        <strong style="font-size:14px;">${violationType}${articleSection ? `, ${articleSection}` : ""}</strong>
        ${citationText ? `<p style="font-style:italic;color:#555;margin:8px 0 0 0;font-size:13px;">${citationText}</p>` : ""}
      </td></tr>
    </table>
  `;

  const photosHtml = (photoUrls && photoUrls.length > 0) ? `
    <div style="margin:20px 0;">
      <p style="font-weight:bold;font-size:14px;margin-bottom:10px;">Violation Evidence:</p>
      <table width="100%" cellpadding="0" cellspacing="0"><tr>
        ${photoUrls.slice(0, 3).map(url => `
          <td width="33%" style="padding:4px;vertical-align:top;">
            <img src="${url}" alt="Violation photo" style="width:100%;max-width:180px;height:auto;border:1px solid #ddd;border-radius:4px;" />
          </td>
        `).join("")}
      </tr></table>
    </div>
  ` : "";

  const responseLink = violationId ? `
    <div style="text-align:center;margin:24px 0;">
      <a href="${appUrl}/violation/${violationId}" style="display:inline-block;background-color:#1e40af;color:#ffffff;font-weight:bold;padding:12px 28px;text-decoration:none;border-radius:6px;font-size:14px;">
        View &amp; Respond to This Notice
      </a>
      <p style="font-size:12px;color:#888;margin-top:8px;">Use this link to submit your response or status update online.</p>
    </div>
  ` : "";

  const closingParagraph = `The Board's goal is to maintain a beautiful and well-kept neighborhood for all residents—supporting curb appeal and protecting property values. If you've already taken care of this or believe this notice may be in error, feel free to contact us${managementPhone ? ` via call or text at ${managementPhone}` : ""}${managementEmail ? `, or email us at ${managementEmail}` : ""}. We also encourage all homeowners to register for online portal access for easy communication and updates.`;

  return `
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1.0"></head>
<body style="margin:0;padding:0;background-color:#f4f4f5;font-family:Arial,Helvetica,sans-serif;">
  <table width="100%" cellpadding="0" cellspacing="0" style="background-color:#f4f4f5;padding:20px 0;">
    <tr><td align="center">
      <table width="600" cellpadding="0" cellspacing="0" style="background-color:#ffffff;border-radius:8px;overflow:hidden;box-shadow:0 2px 8px rgba(0,0,0,0.08);">
        
        <!-- Header -->
        <tr>
          <td style="background-color:#1e3a5f;padding:20px 30px;color:#ffffff;">
            <table width="100%" cellpadding="0" cellspacing="0">
              <tr>
                <td>
                  <p style="margin:0;font-size:18px;font-weight:bold;">${associationName}</p>
                  ${managementCompany ? `<p style="margin:4px 0 0 0;font-size:13px;opacity:0.85;">c/o ${managementCompany}</p>` : ""}
                  ${associationAddress ? `<p style="margin:2px 0 0 0;font-size:12px;opacity:0.75;">${associationAddress}</p>` : ""}
                </td>
                <td align="right" style="vertical-align:top;">
                  <p style="margin:0;font-size:12px;opacity:0.85;">${today}</p>
                </td>
              </tr>
            </table>
          </td>
        </tr>

        <!-- Notice Badge -->
        <tr>
          <td style="padding:0;">
            <table width="100%" cellpadding="0" cellspacing="0">
              <tr>
                <td style="background-color:#b91c1c;padding:10px 30px;color:#ffffff;font-weight:bold;font-size:15px;letter-spacing:0.5px;">
                  ⚠ VIOLATION NOTICE — ${(noticeLevel || "First Notice").toUpperCase()}
                </td>
              </tr>
            </table>
          </td>
        </tr>

        <!-- Body -->
        <tr>
          <td style="padding:30px;">
            <!-- Re: line -->
            <p style="margin:0 0 4px 0;font-size:14px;">
              <strong>Re:</strong> <strong>${noticeLevel || "First Notice"} — ${propertyAddress}</strong>
            </p>
            <p style="margin:0 0 20px 0;font-size:13px;color:#666;">${associationName}</p>
            ${certifiedMail ? `<p style="margin:0 0 16px 0;font-size:13px;font-weight:bold;letter-spacing:0.3px;">CERTIFIED MAIL #: ${certifiedMail}</p>` : ""}

            <!-- Greeting -->
            <p style="margin:0 0 16px 0;font-size:14px;">Dear ${ownerName || "Homeowner"},</p>

            <!-- Opening paragraph -->
            <p style="margin:0 0 20px 0;font-size:14px;line-height:1.6;color:#333;">${openingParagraph}</p>

            <!-- Violation box -->
            ${violationBox}

            ${description ? `<p style="margin:0 0 16px 0;font-size:14px;line-height:1.5;"><strong>Description:</strong> ${description}</p>` : ""}

            <!-- Requested action -->
            ${requestedAction ? `
            <table width="100%" cellpadding="0" cellspacing="0" style="margin:12px 0;">
              <tr>
                <td width="130" style="font-weight:bold;font-size:14px;vertical-align:top;padding:4px 0;">Requested Action:</td>
                <td style="font-size:14px;line-height:1.5;padding:4px 0;">${requestedAction}</td>
              </tr>
            </table>
            ` : ""}

            <!-- Deadline -->
            <table width="100%" cellpadding="0" cellspacing="0" style="margin:12px 0;">
              <tr>
                <td width="130" style="font-weight:bold;font-size:14px;vertical-align:top;padding:4px 0;">Violation Date:</td>
                <td style="font-size:14px;padding:4px 0;">${violationDate}</td>
              </tr>
              ${dueDate ? `
              <tr>
                <td width="130" style="font-weight:bold;font-size:14px;vertical-align:top;padding:4px 0;">Deadline:</td>
                <td style="font-size:14px;padding:4px 0;text-decoration:underline;">${formattedDueDate}</td>
              </tr>
              ` : ""}
            </table>

            <!-- Evidence photos -->
            ${photosHtml}

            <!-- Response link -->
            ${responseLink}

            <!-- Closing -->
            <p style="margin:20px 0 16px 0;font-size:14px;line-height:1.6;color:#333;">${closingParagraph}</p>

            <p style="margin:20px 0 4px 0;font-size:14px;">Thank you for your attention and cooperation!</p>
            <p style="margin:0 0 2px 0;font-size:14px;">Warm Regards,</p>
            ${managementCompany ? `<p style="margin:0 0 2px 0;font-size:14px;font-weight:bold;">${managementCompany}</p>` : ""}
            <p style="margin:0;font-size:13px;color:#555;">Managing Agent for ${associationName}</p>
          </td>
        </tr>

        <!-- Footer -->
        <tr>
          <td style="border-top:2px solid #1e3a5f;padding:16px 30px;background-color:#f9fafb;">
            <p style="margin:0 0 4px 0;font-size:13px;font-weight:bold;color:#333;text-align:center;">${associationName}</p>
            ${contactParts.length > 0 ? `<p style="margin:0;font-size:12px;color:#666;text-align:center;">${contactParts.join("  |  ")}</p>` : ""}
          </td>
        </tr>

        <!-- Disclaimer -->
        <tr>
          <td style="padding:12px 30px 20px;background-color:#f9fafb;">
            <p style="margin:0;font-size:10px;color:#999;line-height:1.4;text-align:center;font-style:italic;">
              This notice is issued in accordance with the Association's governing documents and Florida Statutes. Nothing herein waives or limits the Association's rights and remedies, all of which are expressly reserved.
            </p>
          </td>
        </tr>

      </table>
    </td></tr>
  </table>
</body>
</html>
  `.trim();
}
