from discord.ext import commands
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from dotenv import load_dotenv
from os import getenv
import html
from datetime import datetime


class Mail(commands.Cog):
    def __init__(self, client:commands.Bot):
        self.client = client
        load_dotenv()
        from utils.sql_commands import DatabaseManager

        self.db = DatabaseManager()

    @commands.is_owner()
    @commands.command(name="mail_feedback")
    async def mail(self, ctx:commands.Context[commands.Bot]):
        password = getenv("EMAILPASS")
        username = getenv("EMAILUSER")
        server = getenv("EMAILSERVER")
        port = getenv("EMAILPORT")
        receiver = getenv("FEEDBACKRECEIVER")

        if None in [password, username, server, port, receiver]:
            await ctx.reply(
                "Email configuration is missing. Please check your environment variables.",
                delete_after=5,
            )
            return

        try:
            port = int(port) # type: ignore # Error invalid as for problem is taken care of above
            s = smtplib.SMTP(host=server, port=port) # type: ignore
            s.starttls()
            s.login(username, password) # type: ignore
            msg = MIMEMultipart("alternative")
            msg["To"] = receiver # type: ignore
            msg["From"] = username # type: ignore
            msg["Subject"] = "Py feedback"

            # Fetch feedback from the database
            feedback_rows:list[dict[str,str]] = self.db.fetch_all("SELECT * FROM feedback")
            all_feedback = ""
            for i, row in enumerate(feedback_rows, 1):
                content = html.escape(row["CONTENT"])
                user = html.escape(row["USER"])
                timestamp = html.escape(row["TIMESTAMP"])
                
                all_feedback += f"""
                <li style="margin-bottom:25px; border-bottom:1px solid #edf2f7; padding-bottom:20px;">
                    <div class="feedback-card" style="background:#ffffff; border-radius:8px; position:relative;">
                        <div style="display:flex; align-items:center; margin-bottom:12px;">
                            <div style="background:#4361ee; width:36px; height:36px; border-radius:50%; display:flex; align-items:center; justify-content:center; color:white; font-weight:bold; flex-shrink:0;">
                                {i}
                            </div>
                            <div style="margin-left:15px;">
                                <h3 style="margin:0; font-size:16px; color:#2d3748;">{user}</h3>
                                <p style="margin:3px 0 0; font-size:13px; color:#718096;">{timestamp}</p>
                            </div>
                        </div>
                        <div style="background:#f8f9fc; padding:15px; border-radius:8px; border-left:3px solid #4361ee;">
                            <p style="margin:0; font-size:15px; line-height:1.5; color:#4a5568;">{content}</p>
                        </div>
                    </div>
                </li>
                """

            

            text = f"""<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>User Feedback Report</title>
    <style>
        @media only screen and (max-width: 600px) {{
            .container {{
                width: 95% !important;
            }}
            .feedback-card {{
                padding: 12px !important;
            }}
        }}
    </style>
</head>
<body style="margin:0; padding:20px 0; background-color:#f7f9fc; font-family:'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;">
    <div class="container" style="max-width:600px; margin:0 auto; background:#ffffff; border-radius:10px; box-shadow:0 4px 15px rgba(0,0,0,0.05);">
        <!-- Header -->
        <div style="background: linear-gradient(135deg, #4361ee 0%, #3a0ca3 100%); padding:30px 0; border-radius:10px 10px 0 0; text-align:center;">
            <h1 style="color:#fff; margin:0; font-weight:600;">User Feedback Report</h1>
            <p style="color:rgba(255,255,255,0.8); margin:8px 0 0; font-size:18px;">New feedback submissions</p>
        </div>
        
        <!-- Summary -->
        <div style="padding:20px 30px; background:#f0f7ff; border-bottom:1px solid #e3f2fd;">
            <p style="margin:0; font-size:16px; color:#2d3748;">
                Total feedback submissions: <strong>{len(feedback_rows)}</strong>
            </p>
        </div>
        
        <!-- Feedback Items -->
        <div style="padding:10px 30px 30px;">
            <ul style="list-style:none; padding:0; margin:0;">
                {all_feedback}
            </ul>
        </div>
        
        <!-- Footer -->
        <div style="padding:20px 30px; text-align:center; background:#f8f9fa; border-top:1px solid #eaeaea; border-radius:0 0 10px 10px; color:#718096; font-size:14px;">
            <p style="margin:0;">Generated automatically by PyBot • {datetime.now().strftime('%Y-%m-%d %H:%M')}</p>
            <p style="margin:8px 0 0;">Do not reply to this automated message</p>
        </div>
    </div>
</body>
</html>
"""



            msg.attach(MIMEText(text, "html"))
            s.send_message(msg)
            await ctx.reply("Mail sent.", delete_after=2)
            s.quit()
        except Exception as e:
            await ctx.reply(f"Failed to send mail: {e}", delete_after=5)


async def setup(client:commands.Bot):
    await client.add_cog(Mail(client))
