"use client";

/**
 * Email Reports — manage automated intelligence report schedules,
 * trigger sends, and browse sent-report history with inline preview.
 */

import { useCallback, useEffect, useState } from "react";
import { useBrand } from "@/context/brand-context";
import { Mail, Plus, CheckCircle2, XCircle, Eye, Loader2 } from "lucide-react";
import ScheduleCard, { type ScheduleDto } from "@/components/email-reports/schedule-card";
import CreateScheduleModal from "@/components/email-reports/create-schedule-modal";
import EmailPreviewModal, { type SentReportDto } from "@/components/email-reports/email-preview-modal";
import FeatureGate from "@/components/plan/feature-gate";

// Email Reports is a Professional+ feature. FeatureGate wrapper
// catches direct navigations that bypass the sidebar's locked-click handler.
export default function EmailReportsPageGated() {
  return (
    <FeatureGate feature="email_reports">
      <EmailReportsPage />
    </FeatureGate>
  );
}

function EmailReportsPage() {
  const { brand } = useBrand();
  const [schedules, setSchedules] = useState<ScheduleDto[]>([]);
  const [history, setHistory] = useState<SentReportDto[]>([]);
  const [historyTotal, setHistoryTotal] = useState(0);
  const [historyPage, setHistoryPage] = useState(1);
  const [loading, setLoading] = useState(true);
  const [createOpen, setCreateOpen] = useState(false);
  const [editing, setEditing] = useState<ScheduleDto | null>(null);
  const [preview, setPreview] = useState<SentReportDto | null>(null);

  const loadSchedules = useCallback(async () => {
    if (!brand?.id) return;
    const res = await fetch(`/api/email-reports/schedules?brandId=${brand.id}`);
    if (res.ok) { const d = await res.json(); setSchedules(d.schedules || []); }
  }, [brand.id]);

  const loadHistory = useCallback(async (page = 1) => {
    if (!brand?.id) return;
    const res = await fetch(`/api/email-reports/history?brandId=${brand.id}&page=${page}&pageSize=10`);
    if (res.ok) {
      const d = await res.json();
      setHistory(d.reports || []);
      setHistoryTotal(d.total || 0);
      setHistoryPage(page);
    }
  }, [brand.id]);

  const loadAll = useCallback(async () => {
    setLoading(true);
    await Promise.all([loadSchedules(), loadHistory()]);
    setLoading(false);
  }, [loadSchedules, loadHistory]);

  useEffect(() => { loadAll(); }, [loadAll]);

  async function sendNow(id: string) {
    await fetch(`/api/email-reports/send-now/${id}`, { method: "POST" });
    await loadHistory();
  }

  async function toggleActive(id: string, isActive: boolean) {
    await fetch(`/api/email-reports/schedules/${id}`, { method: "PUT", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ isActive }) });
    await loadSchedules();
  }

  async function deleteSchedule(id: string) {
    await fetch(`/api/email-reports/schedules/${id}`, { method: "DELETE" });
    await loadSchedules();
  }

  async function viewReport(report: SentReportDto) {
    // Fetch full report with htmlContent (history endpoint doesn't include it).
    // We'll use a direct query — for now re-fetch from the sent report.
    // The history endpoint only returns metadata, so we'll show what we have.
    setPreview(report);
  }

  if (loading) {
    return <div className="flex items-center justify-center h-64"><div className="w-8 h-8 border-4 border-brand-100 border-t-brand-600 rounded-full animate-spin" /></div>;
  }

  // ── Empty state ──
  if (schedules.length === 0 && history.length === 0) {
    return (
      <div className="space-y-6 max-w-5xl">
        <div>
          <h1 className="text-2xl font-bold text-slate-900">Email Reports</h1>
          <p className="text-slate-500 text-sm mt-1">Automated intelligence reports for {brand.domain}</p>
        </div>
        <div className="bg-white rounded-xl border border-slate-200 p-12 text-center">
          <Mail className="w-14 h-14 text-slate-200 mx-auto mb-4" />
          <h2 className="text-lg font-bold text-slate-900 mb-1">Automate Your Reporting</h2>
          <p className="text-sm text-slate-500 max-w-md mx-auto mb-6">
            Set up scheduled email reports to automatically send performance updates to your team and clients. Reports include AI-powered analysis, ranking changes, and actionable insights.
          </p>
          <button onClick={() => setCreateOpen(true)} className="inline-flex items-center gap-1.5 px-5 py-2.5 bg-brand-600 text-white text-sm font-semibold rounded-xl hover:bg-brand-700">
            <Plus className="w-4 h-4" /> Create Email Report
          </button>
        </div>
        <CreateScheduleModal brandId={brand.id} open={createOpen} onClose={() => setCreateOpen(false)} onSaved={loadAll} />
      </div>
    );
  }

  const totalPages = Math.ceil(historyTotal / 10);

  return (
    <div className="space-y-6 max-w-5xl">
      {/* Header */}
      <div className="flex items-start justify-between">
        <div>
          <h1 className="text-2xl font-bold text-slate-900">Email Reports</h1>
          <p className="text-slate-500 text-sm mt-1">{brand.domain} · {schedules.length} schedule{schedules.length !== 1 ? "s" : ""}</p>
        </div>
        <button onClick={() => { setEditing(null); setCreateOpen(true); }} className="flex items-center gap-1.5 px-4 py-2 bg-brand-600 text-white text-xs font-semibold rounded-lg hover:bg-brand-700">
          <Plus className="w-3.5 h-3.5" /> Create Email Report
        </button>
      </div>

      {/* Active Schedules */}
      <div>
        <h2 className="text-xs font-bold uppercase tracking-widest text-slate-400 mb-3">Active Schedules</h2>
        <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
          {schedules.map((s) => (
            <ScheduleCard
              key={s.id}
              schedule={s}
              onSendNow={sendNow}
              onToggle={toggleActive}
              onEdit={(sched) => { setEditing(sched); setCreateOpen(true); }}
              onDelete={deleteSchedule}
            />
          ))}
        </div>
      </div>

      {/* Sent History */}
      {history.length > 0 && (
        <div className="bg-white rounded-xl border border-slate-200 overflow-hidden">
          <div className="px-5 py-3.5 border-b border-slate-100 flex items-center gap-2">
            <Mail className="w-4 h-4 text-brand-600" />
            <h2 className="font-bold text-slate-800 text-sm">Sent Reports</h2>
            <span className="ml-auto text-[11px] text-slate-400">{historyTotal} total</span>
          </div>
          <div className="overflow-x-auto">
            <table className="w-full text-sm">
              <thead>
                <tr className="border-b border-slate-100 bg-slate-50/80">
                  <th className="px-4 py-2.5 text-left text-[10px] font-bold uppercase tracking-widest text-slate-400">Subject</th>
                  <th className="px-4 py-2.5 text-left text-[10px] font-bold uppercase tracking-widest text-slate-400">Sent To</th>
                  <th className="px-4 py-2.5 text-left text-[10px] font-bold uppercase tracking-widest text-slate-400">Sent At</th>
                  <th className="px-4 py-2.5 text-center text-[10px] font-bold uppercase tracking-widest text-slate-400">Status</th>
                  <th className="px-4 py-2.5 w-16" />
                </tr>
              </thead>
              <tbody>
                {history.map((r) => (
                  <tr key={r.id} className="border-b border-slate-100 hover:bg-slate-50">
                    <td className="px-4 py-2.5 font-medium text-slate-900 truncate max-w-[240px]">{r.subject}</td>
                    <td className="px-4 py-2.5 text-xs text-slate-600 truncate max-w-[200px]">{r.recipients.join(", ")}</td>
                    <td className="px-4 py-2.5 text-xs text-slate-500">{new Date(r.sentAt).toLocaleDateString("en-US", { month: "short", day: "numeric", hour: "numeric", minute: "2-digit" })}</td>
                    <td className="px-4 py-2.5 text-center">
                      {r.status === "sent" ? (
                        <span className="inline-flex items-center gap-1 text-[11px] font-semibold text-green-600"><CheckCircle2 className="w-3 h-3" /> Sent</span>
                      ) : (
                        <span className="inline-flex items-center gap-1 text-[11px] font-semibold text-red-600" title={r.error || ""}><XCircle className="w-3 h-3" /> Failed</span>
                      )}
                    </td>
                    <td className="px-4 py-2.5">
                      <button onClick={() => viewReport(r)} className="flex items-center gap-1 text-[11px] font-semibold text-brand-600 hover:text-brand-800">
                        <Eye className="w-3 h-3" /> View
                      </button>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
          {totalPages > 1 && (
            <div className="flex items-center justify-center gap-2 px-5 py-3 border-t border-slate-100">
              <button disabled={historyPage <= 1} onClick={() => loadHistory(historyPage - 1)} className="px-3 py-1 rounded-md text-xs font-semibold border border-slate-200 disabled:opacity-40">Prev</button>
              <span className="text-xs text-slate-500">Page {historyPage} of {totalPages}</span>
              <button disabled={historyPage >= totalPages} onClick={() => loadHistory(historyPage + 1)} className="px-3 py-1 rounded-md text-xs font-semibold border border-slate-200 disabled:opacity-40">Next</button>
            </div>
          )}
        </div>
      )}

      <CreateScheduleModal brandId={brand.id} open={createOpen} editing={editing} onClose={() => { setCreateOpen(false); setEditing(null); }} onSaved={loadAll} />
      <EmailPreviewModal report={preview} onClose={() => setPreview(null)} />
    </div>
  );
}
