import { useEffect, useState } from "react";
import { Bell, Send, Check, AlertTriangle, Loader2 } from "lucide-react";
import CmsLayout from "./CmsLayout";
import { PageHeader, SectionCard, Field, TextInput, Select, Toggle, SaveBar, Badge } from "./ui";
import {
  fetchSmtpSettings,
  updateSmtpSettings,
  sendTestEmail,
  type SmtpEncryption,
  type SmtpSettingsResponse,
} from "@/lib/smtp-settings-api";

type NotifState = {
  smtpHost: string;
  smtpPort: number;
  smtpUser: string;
  smtpPass: string; // blank means "keep existing" on save
  smtpEncryption: SmtpEncryption;
  senderName: string;
  senderEmail: string;
  replyTo: string;
  evtNewTicket: boolean;
  evtInvoice: boolean;
  evtServiceUp: boolean;
  evtServiceDown: boolean;
  evtUserRegister: boolean;
  evtPaymentFail: boolean;
};

const DEFAULTS: NotifState = {
  smtpHost: "",
  smtpPort: 587,
  smtpUser: "",
  smtpPass: "",
  smtpEncryption: "TLS",
  senderName: "DoItEasy",
  senderEmail: "",
  replyTo: "",
  evtNewTicket: true,
  evtInvoice: true,
  evtServiceUp: true,
  evtServiceDown: true,
  evtUserRegister: true,
  evtPaymentFail: true,
};

const TEMPLATES = [
  { key: "welcome", name: "Welcome Email", desc: "Sent when a new user signs up." },
  { key: "invoice", name: "Invoice Issued", desc: "Sent when an invoice is generated." },
  { key: "ticket_reply", name: "Ticket Reply", desc: "Sent when a ticket gets a response." },
  { key: "service_down", name: "Service Down Alert", desc: "Sent when monitoring detects downtime." },
  { key: "password_reset", name: "Password Reset", desc: "Sent when a user requests a reset." },
];

function responseToState(resp: SmtpSettingsResponse): NotifState {
  return {
    smtpHost: resp.smtp_host ?? "",
    smtpPort: resp.smtp_port ?? 587,
    smtpUser: resp.smtp_username ?? "",
    smtpPass: "", // never prefilled — blank = keep existing
    smtpEncryption: resp.smtp_encryption ?? "TLS",
    senderName: resp.sender_name ?? "",
    senderEmail: resp.sender_email ?? "",
    replyTo: resp.reply_to ?? "",
    evtNewTicket: resp.evt_new_ticket,
    evtInvoice: resp.evt_invoice,
    evtServiceUp: resp.evt_service_up,
    evtServiceDown: resp.evt_service_down,
    evtUserRegister: resp.evt_user_register,
    evtPaymentFail: resp.evt_payment_fail,
  };
}

export default function CmsNotifications() {
  const [state, setState] = useState<NotifState>(DEFAULTS);
  const [hasStoredPassword, setHasStoredPassword] = useState(false);
  const [loading, setLoading] = useState(true);
  const [loadError, setLoadError] = useState<string | null>(null);
  const [saving, setSaving] = useState(false);
  const [saveError, setSaveError] = useState<string | null>(null);
  const [saveOk, setSaveOk] = useState(false);

  const [testTo, setTestTo] = useState("");
  const [testStatus, setTestStatus] = useState<"idle" | "sending" | "sent" | "error">("idle");
  const [testMessage, setTestMessage] = useState<string>("");

  useEffect(() => {
    let alive = true;
    (async () => {
      try {
        const resp = await fetchSmtpSettings();
        if (!alive) return;
        setState(responseToState(resp));
        setHasStoredPassword(resp.has_password);
        setTestTo(resp.sender_email ?? "");
      } catch (err) {
        if (!alive) return;
        setLoadError(err instanceof Error ? err.message : "Failed to load SMTP settings");
      } finally {
        if (alive) setLoading(false);
      }
    })();
    return () => {
      alive = false;
    };
  }, []);

  const update = <K extends keyof NotifState>(k: K, v: NotifState[K]) =>
    setState((s) => ({ ...s, [k]: v }));

  const save = async () => {
    setSaving(true);
    setSaveError(null);
    setSaveOk(false);
    try {
      const resp = await updateSmtpSettings({
        smtp_host: state.smtpHost || null,
        smtp_port: state.smtpPort || null,
        smtp_username: state.smtpUser || null,
        // Empty string => don't overwrite existing stored password.
        smtp_password: state.smtpPass || null,
        smtp_encryption: state.smtpEncryption,
        sender_name: state.senderName || null,
        sender_email: state.senderEmail || null,
        reply_to: state.replyTo || null,
        evt_new_ticket: state.evtNewTicket,
        evt_invoice: state.evtInvoice,
        evt_service_up: state.evtServiceUp,
        evt_service_down: state.evtServiceDown,
        evt_user_register: state.evtUserRegister,
        evt_payment_fail: state.evtPaymentFail,
      });
      setState(responseToState(resp));
      setHasStoredPassword(resp.has_password);
      setSaveOk(true);
      setTimeout(() => setSaveOk(false), 2500);
    } catch (err) {
      setSaveError(err instanceof Error ? err.message : "Failed to save settings");
    } finally {
      setSaving(false);
    }
  };

  const sendTest = async () => {
    const recipient = testTo.trim();
    if (!recipient) {
      setTestStatus("error");
      setTestMessage("Enter a recipient email address first.");
      return;
    }
    setTestStatus("sending");
    setTestMessage("");
    try {
      const resp = await sendTestEmail(recipient);
      setTestStatus("sent");
      setTestMessage(resp.message);
      setTimeout(() => setTestStatus("idle"), 4000);
    } catch (err) {
      setTestStatus("error");
      setTestMessage(err instanceof Error ? err.message : "Failed to send test email");
    }
  };

  if (loading) {
    return (
      <CmsLayout>
        <PageHeader
          icon={<Bell className="w-6 h-6" />}
          title="Notifications"
          description="SMTP configuration and event-based email delivery."
        />
        <div className="flex items-center gap-2 text-slate-500 bg-white border border-slate-200 rounded-xl p-6">
          <Loader2 className="w-4 h-4 animate-spin" /> Loading SMTP settings…
        </div>
      </CmsLayout>
    );
  }

  return (
    <CmsLayout>
      <PageHeader
        icon={<Bell className="w-6 h-6" />}
        title="Notifications"
        description="SMTP configuration and event-based email delivery."
      />

      {loadError && (
        <div className="mb-4 flex items-start gap-2 rounded-xl border border-amber-300 bg-amber-50 p-4 text-sm text-amber-800">
          <AlertTriangle className="w-4 h-4 mt-0.5 shrink-0" />
          <div>
            <div className="font-semibold">Could not load saved SMTP settings</div>
            <div className="mt-0.5">{loadError}</div>
            <div className="mt-1 text-amber-700">You can still enter and save new values below.</div>
          </div>
        </div>
      )}

      <SectionCard
        title="SMTP Configuration"
        description="Outgoing mail server used for all system emails. Credentials are stored securely in the database."
      >
        <div className="grid md:grid-cols-2 gap-5">
          <Field label="SMTP Host" required>
            <TextInput
              value={state.smtpHost}
              onChange={(e) => update("smtpHost", e.target.value)}
              placeholder="smtp.example.com"
            />
          </Field>
          <Field label="SMTP Port" required>
            <TextInput
              type="number"
              value={state.smtpPort}
              onChange={(e) => update("smtpPort", Number(e.target.value))}
            />
          </Field>
          <Field label="SMTP Username" required>
            <TextInput
              value={state.smtpUser}
              onChange={(e) => update("smtpUser", e.target.value)}
              placeholder="noreply@yourdomain.com"
            />
          </Field>
          <Field
            label={hasStoredPassword ? "SMTP Password (leave blank to keep current)" : "SMTP Password"}
            required={!hasStoredPassword}
          >
            <TextInput
              type="password"
              value={state.smtpPass}
              onChange={(e) => update("smtpPass", e.target.value)}
              placeholder={hasStoredPassword ? "••••••• (stored)" : "••••••••"}
            />
          </Field>
          <Field label="Encryption">
            <Select
              value={state.smtpEncryption}
              onChange={(e) => update("smtpEncryption", e.target.value as SmtpEncryption)}
            >
              <option value="NONE">None</option>
              <option value="TLS">TLS (STARTTLS)</option>
              <option value="SSL">SSL</option>
            </Select>
          </Field>
          <Field label="Send Test Email To">
            <TextInput
              type="email"
              value={testTo}
              onChange={(e) => setTestTo(e.target.value)}
              placeholder="admin@yourdomain.com"
            />
          </Field>
        </div>

        <div className="mt-5 flex flex-col md:flex-row md:items-center gap-3">
          <button
            onClick={sendTest}
            disabled={testStatus === "sending"}
            className="h-[42px] px-5 rounded-lg bg-[#063019] text-white text-sm font-bold hover:bg-[#0b6e3e] transition inline-flex items-center justify-center gap-2 disabled:opacity-70"
          >
            {testStatus === "sending" ? (
              <>
                <Loader2 className="w-4 h-4 animate-spin" /> Sending…
              </>
            ) : testStatus === "sent" ? (
              <>
                <Check className="w-4 h-4" /> Test Email Sent
              </>
            ) : (
              <>
                <Send className="w-4 h-4" /> Send Test Email
              </>
            )}
          </button>
          {testStatus === "sent" && (
            <span className="text-sm text-emerald-700">{testMessage || "Test email sent."}</span>
          )}
          {testStatus === "error" && (
            <span className="text-sm text-red-600 inline-flex items-center gap-1">
              <AlertTriangle className="w-4 h-4" /> {testMessage}
            </span>
          )}
          <span className="text-xs text-slate-500">
            Save your changes first — the test uses the values currently stored in the database.
          </span>
        </div>
      </SectionCard>

      <div className="h-6" />
      <SectionCard title="Sender Identity">
        <div className="grid md:grid-cols-3 gap-5">
          <Field label="Sender Name">
            <TextInput value={state.senderName} onChange={(e) => update("senderName", e.target.value)} />
          </Field>
          <Field label="Sender Email">
            <TextInput
              type="email"
              value={state.senderEmail}
              onChange={(e) => update("senderEmail", e.target.value)}
            />
          </Field>
          <Field label="Reply-To">
            <TextInput type="email" value={state.replyTo} onChange={(e) => update("replyTo", e.target.value)} />
          </Field>
        </div>
      </SectionCard>

      <div className="h-6" />
      <SectionCard title="Event Notifications" description="Choose which events trigger automated emails.">
        <Toggle
          label="New Ticket Opened"
          description="Notify support team when a client opens a ticket."
          checked={state.evtNewTicket}
          onChange={(v) => update("evtNewTicket", v)}
        />
        <Toggle
          label="Invoice Issued"
          description="Email clients when a new invoice is generated."
          checked={state.evtInvoice}
          onChange={(v) => update("evtInvoice", v)}
        />
        <Toggle
          label="Service Up"
          description="Alert when a monitored service recovers."
          checked={state.evtServiceUp}
          onChange={(v) => update("evtServiceUp", v)}
        />
        <Toggle
          label="Service Down"
          description="Alert when a monitored service is detected as down."
          checked={state.evtServiceDown}
          onChange={(v) => update("evtServiceDown", v)}
        />
        <Toggle
          label="User Registration"
          description="Notify admins when a new account is created."
          checked={state.evtUserRegister}
          onChange={(v) => update("evtUserRegister", v)}
        />
        <Toggle
          label="Payment Failure"
          description="Alert when a scheduled payment fails."
          checked={state.evtPaymentFail}
          onChange={(v) => update("evtPaymentFail", v)}
        />
      </SectionCard>

      <div className="h-6" />
      <SectionCard title="Email Templates" description="Manage the content of automated emails.">
        <div className="grid md:grid-cols-2 gap-3">
          {TEMPLATES.map((t) => (
            <div
              key={t.key}
              className="flex items-center justify-between bg-slate-50 border border-slate-200 rounded-xl p-4"
            >
              <div>
                <div className="font-semibold text-slate-900">{t.name}</div>
                <div className="text-xs text-slate-500 mt-0.5">{t.desc}</div>
              </div>
              <div className="flex items-center gap-2">
                <Badge tone="green">Active</Badge>
                <button className="px-3 py-1.5 rounded-lg border border-slate-300 text-xs font-semibold hover:bg-white">
                  Edit
                </button>
              </div>
            </div>
          ))}
        </div>
      </SectionCard>

      {saveError && (
        <div className="mt-4 flex items-start gap-2 rounded-xl border border-red-300 bg-red-50 p-4 text-sm text-red-700">
          <AlertTriangle className="w-4 h-4 mt-0.5 shrink-0" />
          <div>
            <div className="font-semibold">Save failed</div>
            <div className="mt-0.5">{saveError}</div>
          </div>
        </div>
      )}
      {saveOk && (
        <div className="mt-4 flex items-start gap-2 rounded-xl border border-emerald-300 bg-emerald-50 p-4 text-sm text-emerald-700">
          <Check className="w-4 h-4 mt-0.5 shrink-0" />
          SMTP settings saved.
        </div>
      )}

      <SaveBar onSave={save} onReset={() => setState(DEFAULTS)} saving={saving} />
    </CmsLayout>
  );
}