"use client";

import { useState, useEffect } from "react";
import { X, Plus, Loader2, Mail } from "lucide-react";
import type { ScheduleDto } from "./schedule-card";

const EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
const FREQUENCIES = [
  { id: "daily", label: "Daily" },
  { id: "weekly", label: "Weekly" },
  { id: "biweekly", label: "Bi-Weekly" },
  { id: "monthly", label: "Monthly" },
];
const DOW = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
const SECTION_OPTIONS = [
  { id: "gsc", label: "GSC Data" },
  { id: "ga4", label: "GA4 Data" },
  { id: "site_tag", label: "Site Tag Analytics" },
  { id: "audit", label: "Technical Audit" },
  { id: "rank", label: "Rank Tracking" },
  { id: "conversions", label: "Conversions" },
  { id: "lifecycle", label: "Page Lifecycle" },
  { id: "ux", label: "UX Signals" },
];

interface Props {
  brandId: string;
  open: boolean;
  editing?: ScheduleDto | null;
  onClose: () => void;
  onSaved: () => void;
}

export default function CreateScheduleModal({ brandId, open, editing, onClose, onSaved }: Props) {
  const [name, setName] = useState("");
  const [frequency, setFrequency] = useState("weekly");
  const [dayOfWeek, setDayOfWeek] = useState(1);
  const [dayOfMonth, setDayOfMonth] = useState(1);
  const [timeOfDay, setTimeOfDay] = useState("08:00");
  const [emailInput, setEmailInput] = useState("");
  const [recipients, setRecipients] = useState<string[]>([]);
  // site_tag included in defaults so a new brand's first-ever
  // schedule captures first-party analytics out of the box — users
  // can uncheck it before saving if they want a GSC-only report.
  const [sections, setSections] = useState<Set<string>>(new Set(["gsc", "ga4", "site_tag", "audit", "rank", "conversions"]));
  const [aiAnalysis, setAiAnalysis] = useState(true);
  const [competitorScan, setCompetitorScan] = useState(false);
  const [marketInsights, setMarketInsights] = useState(false);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    if (editing) {
      setName(editing.name);
      setFrequency(editing.frequency);
      setDayOfWeek(editing.dayOfWeek ?? 1);
      setDayOfMonth(editing.dayOfMonth ?? 1);
      setTimeOfDay(editing.timeOfDay);
      setRecipients([...editing.recipients]);
      setSections(new Set(editing.sections));
      setAiAnalysis(editing.includeAiAnalysis);
      setCompetitorScan(editing.includeCompetitorScan);
      setMarketInsights(editing.includeMarketInsights);
    } else {
      setName(""); setFrequency("weekly"); setRecipients([]); setEmailInput("");
      setSections(new Set(["gsc", "ga4", "audit", "rank", "conversions"]));
      setAiAnalysis(true); setCompetitorScan(false); setMarketInsights(false);
    }
  }, [editing, open]);

  if (!open) return null;

  function addEmail() {
    const email = emailInput.trim();
    if (EMAIL_RE.test(email) && !recipients.includes(email)) {
      setRecipients([...recipients, email]);
      setEmailInput("");
    }
  }

  function toggleSection(id: string) {
    setSections((prev) => { const n = new Set(prev); n.has(id) ? n.delete(id) : n.add(id); return n; });
  }

  async function submit() {
    if (!name.trim() || recipients.length === 0) return setError("Name and at least one recipient required");
    // Diagnostic log — surfaces the full payload in the browser
    // console on every Create / Update click so the next "schedule
    // didn't save" ticket can be diagnosed from a screenshot of the
    // DevTools console instead of a server log deep-dive.
    console.info("[email-reports] Create Schedule clicked", {
      mode: editing ? "edit" : "create",
      name: name.trim(),
      frequency,
      recipients,
      sections: Array.from(sections),
      aiFeatures: { aiAnalysis, competitorScan, marketInsights },
    });
    setLoading(true); setError(null);
    try {
      const body = {
        brandId, name: name.trim(), frequency, dayOfWeek, dayOfMonth, timeOfDay,
        recipients, sections: Array.from(sections),
        includeAiAnalysis: aiAnalysis, includeCompetitorScan: competitorScan, includeMarketInsights: marketInsights,
        ...(editing ? { isActive: editing.isActive } : {}),
      };
      const url = editing ? `/api/email-reports/schedules/${editing.id}` : "/api/email-reports/schedules";
      const method = editing ? "PUT" : "POST";
      const res = await fetch(url, { method, headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) });
      if (!res.ok) { const d = await res.json().catch(() => ({})); throw new Error(d.error || "Failed"); }
      onSaved(); onClose();
    } catch (err) {
      setError(err instanceof Error ? err.message : "Failed");
    } finally { setLoading(false); }
  }

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-slate-900/60 p-4" onClick={onClose}>
      <div className="bg-white rounded-2xl shadow-2xl w-full max-w-lg max-h-[90vh] flex flex-col overflow-hidden" onClick={(e) => e.stopPropagation()}>
        <div className="flex items-center justify-between border-b border-slate-200 px-5 py-4">
          <h2 className="font-bold text-slate-900">{editing ? "Edit Schedule" : "Create Email Report"}</h2>
          <button onClick={onClose} className="p-1.5 rounded-lg hover:bg-slate-100 text-slate-500"><X className="w-4 h-4" /></button>
        </div>

        <div className="flex-1 overflow-auto p-5 space-y-4">
          <div>
            <label className="block text-[11px] font-semibold text-slate-600 mb-1">Report Name</label>
            <input type="text" value={name} onChange={(e) => setName(e.target.value)} placeholder="Weekly Performance Report" className="w-full px-3 py-2 text-sm border border-slate-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-brand-500/40" />
          </div>

          <div className="grid grid-cols-2 gap-3">
            <div>
              <label className="block text-[11px] font-semibold text-slate-600 mb-1">Frequency</label>
              <select value={frequency} onChange={(e) => setFrequency(e.target.value)} className="w-full px-3 py-2 text-sm border border-slate-200 rounded-lg bg-white">
                {FREQUENCIES.map((f) => <option key={f.id} value={f.id}>{f.label}</option>)}
              </select>
            </div>
            <div>
              <label className="block text-[11px] font-semibold text-slate-600 mb-1">Send Time (UTC)</label>
              <input type="time" value={timeOfDay} onChange={(e) => setTimeOfDay(e.target.value)} className="w-full px-3 py-2 text-sm border border-slate-200 rounded-lg" />
            </div>
          </div>

          {(frequency === "weekly" || frequency === "biweekly") && (
            <div>
              <label className="block text-[11px] font-semibold text-slate-600 mb-1">Day of Week</label>
              <select value={dayOfWeek} onChange={(e) => setDayOfWeek(Number(e.target.value))} className="w-full px-3 py-2 text-sm border border-slate-200 rounded-lg bg-white">
                {DOW.map((d, i) => <option key={i} value={i}>{d}</option>)}
              </select>
            </div>
          )}
          {frequency === "monthly" && (
            <div>
              <label className="block text-[11px] font-semibold text-slate-600 mb-1">Day of Month</label>
              <select value={dayOfMonth} onChange={(e) => setDayOfMonth(Number(e.target.value))} className="w-full px-3 py-2 text-sm border border-slate-200 rounded-lg bg-white">
                {Array.from({ length: 28 }, (_, i) => <option key={i + 1} value={i + 1}>{i + 1}</option>)}
              </select>
            </div>
          )}

          {/* Recipients */}
          <div>
            <label className="block text-[11px] font-semibold text-slate-600 mb-1">Recipients</label>
            <div className="flex items-center gap-2">
              <input type="email" value={emailInput} onChange={(e) => setEmailInput(e.target.value)} onKeyDown={(e) => { if (e.key === "Enter") { e.preventDefault(); addEmail(); } }} placeholder="email@example.com" className="flex-1 px-3 py-2 text-sm border border-slate-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-brand-500/40" />
              <button onClick={addEmail} className="px-3 py-2 bg-slate-100 rounded-lg text-xs font-semibold text-slate-700 hover:bg-slate-200">Add</button>
            </div>
            {recipients.length > 0 && (
              <div className="flex flex-wrap gap-1.5 mt-2">
                {recipients.map((e) => (
                  <span key={e} className="flex items-center gap-1 px-2 py-0.5 rounded-md bg-brand-50 border border-brand-200 text-[11px] text-brand-700 font-medium">
                    <Mail className="w-3 h-3" /> {e}
                    <button onClick={() => setRecipients((r) => r.filter((x) => x !== e))} className="ml-0.5 text-brand-400 hover:text-red-600">&times;</button>
                  </span>
                ))}
              </div>
            )}
          </div>

          {/* Sections */}
          <div>
            <label className="block text-[11px] font-semibold text-slate-600 mb-1.5">Report Sections</label>
            <div className="grid grid-cols-2 gap-1.5">
              {SECTION_OPTIONS.map((s) => (
                <label key={s.id} className="flex items-center gap-2 px-3 py-2 rounded-lg border border-slate-200 cursor-pointer hover:bg-slate-50">
                  <input type="checkbox" checked={sections.has(s.id)} onChange={() => toggleSection(s.id)} className="rounded" />
                  <span className="text-xs font-medium text-slate-700">{s.label}</span>
                </label>
              ))}
            </div>
          </div>

          {/* AI toggles */}
          <div className="space-y-2 pt-2 border-t border-slate-100">
            <p className="text-[10px] font-bold uppercase tracking-widest text-slate-400">AI Features</p>
            {[
              { label: "AI Analysis", value: aiAnalysis, set: setAiAnalysis },
              { label: "Competitor Scan", value: competitorScan, set: setCompetitorScan },
              { label: "Market Insights", value: marketInsights, set: setMarketInsights },
            ].map((t) => (
              <label key={t.label} className="flex items-center justify-between">
                <span className="text-xs font-medium text-slate-700">{t.label}</span>
                <button onClick={() => t.set(!t.value)} className={`relative w-9 h-5 rounded-full transition-colors ${t.value ? "bg-brand-600" : "bg-slate-200"}`}>
                  <span className={`absolute top-0.5 ${t.value ? "left-4" : "left-0.5"} w-4 h-4 bg-white rounded-full shadow-sm transition-all`} />
                </button>
              </label>
            ))}
          </div>

          {error && <p className="text-xs text-red-600">{error}</p>}
        </div>

        <div className="flex items-center justify-end gap-2 border-t border-slate-200 px-5 py-3 bg-slate-50">
          <button onClick={onClose} className="px-4 py-2 text-xs font-semibold text-slate-600">Cancel</button>
          <button onClick={submit} disabled={loading} 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 disabled:opacity-60">
            {loading ? <Loader2 className="w-3.5 h-3.5 animate-spin" /> : <Plus className="w-3.5 h-3.5" />}
            {editing ? "Save Changes" : "Create Schedule"}
          </button>
        </div>
      </div>
    </div>
  );
}
