"use client";

import React, { useState, useEffect, useCallback } from "react";
import toast from "react-hot-toast";
import styles from "../../commonstyle/FormStyles.module.css";
import { fetchApi } from "@/lib/api/http";

const API_BASE_URL =
  process.env.NEXT_PUBLIC_API_BASE_URL || "http://localhost:3007/api";

const MONTHS = [
  "January", "February", "March", "April", "May", "June",
  "July", "August", "September", "October", "November", "December",
];

// Values match the backend bucket keys / ReportType.
const CERT_TYPES = [
  { value: "all", label: "All categories" },
  { value: "recert", label: "Re-certification" },
  { value: "surv_1", label: "1st Surveillance" },
  { value: "surv_11", label: "2nd Surveillance" },
];

interface Bucket { key: string; label: string; count: number; }
interface CountsResponse { month: string; total: number; buckets: Bucket[]; }

interface Props {
  isOpen: boolean;
  onClose: () => void;
}

export default function SendReportModal({ isOpen, onClose }: Props) {
  const now = new Date();
  const [month, setMonth] = useState(now.getMonth() + 1);
  const [year, setYear] = useState(now.getFullYear());
  const [certType, setCertType] = useState("all");
  const [emails, setEmails] = useState("");

  const [counts, setCounts] = useState<CountsResponse | null>(null);
  const [loadingCounts, setLoadingCounts] = useState(false);
  const [sending, setSending] = useState(false);

  // ── Live preview: pull the counts whenever month/year/type changes ─────────
  const loadCounts = useCallback(async () => {
    setLoadingCounts(true);
    setCounts(null);
    try {
      const data = await fetchApi<CountsResponse>(
        `${API_BASE_URL}/report/counts?year=${year}&month=${month}&type=${certType}`,
      );
      setCounts(data);
    } catch {
      // preview is best-effort; don't block sending if it fails
      setCounts(null);
    } finally {
      setLoadingCounts(false);
    }
  }, [year, month, certType]);

  useEffect(() => {
    if (isOpen) loadCounts();
  }, [isOpen, loadCounts]);

  // ── Validate the email input (supports comma-separated list) ───────────────
  const parseEmails = (raw: string): string[] => {
    return raw
      .split(",")
      .map((e) => e.trim())
      .filter(Boolean);
  };
  const validEmails = (list: string[]) => {
    const re = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    return list.length > 0 && list.every((e) => re.test(e));
  };

  const handleSend = async () => {
    if (sending) return;
    const list = parseEmails(emails);
    if (!validEmails(list)) {
      toast.error("Enter at least one valid email (comma-separated for several)");
      return;
    }

    setSending(true);
    try {
      const data = await fetchApi<{ ok: boolean; message: string }>(
        `${API_BASE_URL}/report/send?year=${year}&month=${month}&type=${certType}&to=${encodeURIComponent(list.join(","))}`,
        { method: "POST" },
      );
      toast.success(data?.message ?? "Report emailed successfully.");
      onClose();
    } catch (err) {
      toast.error(err instanceof Error ? err.message : "Failed to send report.");
    } finally {
      setSending(false);
    }
  };

  const handleClose = () => {
    if (sending) return;
    onClose();
  };

  if (!isOpen) return null;

  return (
    <div className={styles.modalOverlay}>
      <div className={styles.modalContent} style={{ maxWidth: 520, width: "95%" }}>
        <div className={styles.modalHeader}>
          <h2 className={styles.modalTitle}>📧 Email Certification Report</h2>
          <button className={styles.closeBtn} onClick={handleClose} type="button">
            ×
          </button>
        </div>

        <div className={styles.formBody}>
          <div className={styles.alertSuccess} style={{ marginBottom: 16 }}>
            <strong>📌 How it works:</strong> Pick the month and a certificate
            type, enter the recipient email(s), and the system emails an Excel +
            PDF report for the selected category (or all three).
          </div>

          {/* Month + Year */}
          <div style={{ display: "flex", gap: 12, marginBottom: 16 }}>
            <div style={{ flex: 1 }}>
              <label style={labelStyle}>Month</label>
              <select
                value={month}
                onChange={(e) => setMonth(Number(e.target.value))}
                disabled={sending}
                style={selectStyle}
              >
                {MONTHS.map((name, i) => (
                  <option key={i + 1} value={i + 1}>{name}</option>
                ))}
              </select>
            </div>
            <div style={{ flex: 1 }}>
              <label style={labelStyle}>Year</label>
              <select
                value={year}
                onChange={(e) => setYear(Number(e.target.value))}
                disabled={sending}
                style={selectStyle}
              >
                {Array.from({ length: 7 }, (_, i) => now.getFullYear() - 3 + i).map((y) => (
                  <option key={y} value={y}>{y}</option>
                ))}
              </select>
            </div>
          </div>

          {/* Certificate type */}
          <div style={{ marginBottom: 16 }}>
            <label style={labelStyle}>Certificate type</label>
            <select
              value={certType}
              onChange={(e) => setCertType(e.target.value)}
              disabled={sending}
              style={selectStyle}
            >
              {CERT_TYPES.map((t) => (
                <option key={t.value} value={t.value}>{t.label}</option>
              ))}
            </select>
            <div style={{ fontSize: 11, color: "#94a3b8", marginTop: 5 }}>
              Choose one category, or “All” to include every type.
            </div>
          </div>

          {/* Recipient email(s) */}
          <div style={{ marginBottom: 16 }}>
            <label style={labelStyle}>Send to</label>
            <input
              type="text"
              value={emails}
              onChange={(e) => setEmails(e.target.value)}
              disabled={sending}
              placeholder="boss@company.com, manager@company.com"
              style={{ ...selectStyle, fontFamily: "inherit" }}
            />
            <div style={{ fontSize: 11, color: "#94a3b8", marginTop: 5 }}>
              Separate multiple addresses with commas.
            </div>
          </div>

          {/* Live preview of what will be sent */}
          <div
            style={{
              border: "1px solid #ede8ff",
              background: "#f8f5ff",
              borderRadius: 10,
              padding: "12px 16px",
            }}
          >
            <div style={{ fontSize: 11, fontWeight: 800, color: "#7c3aed", letterSpacing: ".06em", textTransform: "uppercase", marginBottom: 8 }}>
              Preview — {MONTHS[month - 1]} {year}
            </div>
            {loadingCounts ? (
              <div style={{ fontSize: 13, color: "#94a3b8" }}>Loading counts…</div>
            ) : counts ? (
              <table style={{ width: "100%", fontSize: 13, borderCollapse: "collapse" }}>
                <tbody>
                  {counts.buckets.map((b) => (
                    <tr key={b.key}>
                      <td style={{ padding: "3px 0", color: "#555" }}>{b.label}</td>
                      <td style={{ padding: "3px 0", textAlign: "right", fontWeight: 700, color: "#1a0440" }}>{b.count}</td>
                    </tr>
                  ))}
                  <tr>
                    <td style={{ padding: "6px 0 0", color: "#1a0440", fontWeight: 800, borderTop: "1px solid #ede8ff" }}>Total</td>
                    <td style={{ padding: "6px 0 0", textAlign: "right", color: "#1a0440", fontWeight: 800, borderTop: "1px solid #ede8ff" }}>{counts.total}</td>
                  </tr>
                </tbody>
              </table>
            ) : (
              <div style={{ fontSize: 13, color: "#94a3b8" }}>No preview available.</div>
            )}
          </div>
        </div>

        <div className={styles.modalFooter}>
          <button className={styles.btnCancel} onClick={handleClose} type="button" disabled={sending}>
            Cancel
          </button>
          <button
            className={styles.btnSubmit}
            onClick={handleSend}
            type="button"
            disabled={sending}
            style={{ opacity: sending ? 0.6 : 1 }}
          >
            {sending ? "Sending…" : "Send Report"}
          </button>
        </div>
      </div>
    </div>
  );
}

const labelStyle: React.CSSProperties = {
  fontSize: 12,
  color: "#64748b",
  display: "block",
  marginBottom: 6,
  fontWeight: 600,
};

const selectStyle: React.CSSProperties = {
  width: "100%",
  padding: "9px 11px",
  borderRadius: 8,
  border: "1px solid #d1d5db",
  fontSize: 14,
  color: "#1a0440",
  background: "#fff",
};