import { NextRequest, NextResponse } from "next/server";
import dbConnect from "@/lib/mongodb";
import Leads from "@/models/Leads";
import { sendTemplateMail } from "@/lib/email";
import GeneralSettings from "@/models/GeneralSettings";

export async function POST(req: NextRequest) {
  try {
    await dbConnect();

    const body = await req.json();

    const { name, phone_number, state, city, address, products, email } = body;

    // Validation
    if (!name?.trim()) {
      return NextResponse.json(
        {
          success: false,
          message: "Name is required",
        },
        { status: 400 },
      );
    }

    if (!phone_number?.trim()) {
      return NextResponse.json(
        {
          success: false,
          message: "Phone number is required",
        },
        { status: 400 },
      );
    }

    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    if (email && email.trim() && !emailRegex.test(email.trim())) {
      return NextResponse.json(
        {
          success: false,
          message: "Invalid email address",
        },
        { status: 400 },
      );
    }

    if (!address?.trim()) {
      return NextResponse.json(
        {
          success: false,
          message: "Address is required",
        },
        { status: 400 },
      );
    }

    const phoneRegex = /^[6-9]\d{9}$/;

    if (!phoneRegex.test(phone_number.trim())) {
      return NextResponse.json(
        {
          success: false,
          message: "Invalid Indian phone number",
        },
        { status: 400 },
      );
    }

    // Debug log
    console.log("Incoming Lead Data:", {
      name,
      phone_number,
      // state,
      // city,
      address,
    });

    const existing = await Leads.findOne({
      phone_number: phone_number.trim(),
    });

    const admindetails = await GeneralSettings.findOne();

    if (!admindetails?.email) {
      return NextResponse.json(
        {
          success:false,
          message:"Admin email not configured"
        },
        {status:500}
      );
    }

    let productsTable = "";

    if (Array.isArray(products) && products.length > 0) {
      const validProducts = products.filter((item: any) =>
        item.product?.name &&
        item.sku?.sku
      );

      if (validProducts.length > 0) {
        productsTable = `
          <p style="font-weight:600;margin-bottom:10px;">
            Product Details:
          </p>

          <table style="width:100%;border-collapse:collapse;">
            <thead>
              <tr>
                <th style="border:1px solid #ddd;padding:8px;">Product</th>
                <th style="border:1px solid #ddd;padding:8px;">SKU</th>
                <th style="border:1px solid #ddd;padding:8px;">Color</th>
                <th style="border:1px solid #ddd;padding:8px;">Size</th>
                <th style="border:1px solid #ddd;padding:8px;">Qty</th>
              </tr>
            </thead>

            <tbody>
              ${validProducts.map((item:any)=>`
                <tr>
                  <td style="border:1px solid #ddd;padding:8px;">
                    ${item.product.name}
                  </td>
                  <td style="border:1px solid #ddd;padding:8px;">
                    ${item.sku.sku}
                  </td>
                  <td style="border:1px solid #ddd;padding:8px">
                    ${item.sku.color ?? "-"}
                  </td>
                  <td style="border:1px solid #ddd;padding:8px;">
                    ${item.sku.size ?? "-"}
                  </td>
                  <td style="border:1px solid #ddd;padding:8px;">
                    ${item.quantity ?? "-"}
                  </td>
                </tr>
              `).join("")}
            </tbody>
          </table>
        `;
      }
    }
    
    // Update existing lead
    if (existing) {
      existing.name = name.trim();
      // existing.state = state.trim();
      // existing.city = city.trim();
      existing.address = address.trim();

      await existing.save();      
      
      try {
        await sendTemplateMail({
          slug: "inquiry-submit",
          to: admindetails.email,
          replyTo: admindetails.email,
          templateData: {
            name: existing.name,
            phone_number: existing.phone_number,
            ...(productsTable ? { productsTable } : {})
          },
        });
      } catch (err: any) {
        console.error("Contact notification email failed", err);
      }

      if (email && email.trim()) {
        try {
          await sendTemplateMail({
            slug: "inquery",
            to: email.trim(),
            replyTo: admindetails.email,
            templateData: {
              name,
              phone_number,
              ...(productsTable ? { productsTable } : {})
            },
          });
        } catch (err: any) {
          console.error("User inquiry email failed", err);
        }
      }

      return NextResponse.json({
        success: true,
        data: existing,
        message: "Lead updated successfully",
      });
    }

    // Create new lead
    const lead = await Leads.create({
      name: name.trim(),
      phone_number: phone_number.trim(),
      // state: state.trim(),
      // city: city.trim(),
      address: address.trim(),
    });

    try {
      await sendTemplateMail({
          slug: "inquiry-submit",
          to: admindetails.email,
          replyTo: admindetails.email,
          templateData: {
            name: lead.name,
            phone_number: lead.phone_number,
            ...(productsTable ? { productsTable } : {})
          },
        });
    } catch (err: any) {
      console.error("Lead notification email failed", err);
    }

    if (email && email.trim()) {
      try {
        await sendTemplateMail({
          slug: "inquery",
          to: email.trim(),
          replyTo: admindetails.email,
          templateData: {
            name,
            phone_number,
            ...(productsTable ? { productsTable } : {})
          },
        });
      } catch (err: any) {
        console.error("User inquiry email failed", err);
      }
    }

    return NextResponse.json(
      {
        success: true,
        message: "Thank you for your Inquiry",
        data: lead,
      },
      {
        status: 201,
      },
    );
  } catch (error: any) {
    console.error("Lead Submit Error:", error);

    return NextResponse.json(
      {
        success: false,
        message: error?.message || "Something went wrong",
      },
      {
        status: 500,
      },
    );
  }
}
