"use client";

import { useEffect, useState, type FormEvent } from "react";
import { Button } from "@/components/ui/Button";
import { useToast } from "@/context/toast-context";
import type { SiteSettingsDTO } from "@/lib/settings-shared";

export default function AdminEmailSettingsPage() {
  const { toast } = useToast();
  const [form, setForm] = useState<SiteSettingsDTO | null>(null);
  const [saving, setSaving] = useState(false);
  const [testing, setTesting] = useState(false);
  const [testTo, setTestTo] = useState("");

  useEffect(() => {
    void fetch("/api/admin/settings", { credentials: "include" })
      .then((res) => res.json())
      .then((data: { settings?: SiteSettingsDTO }) => {
        if (data.settings) {
          setForm(data.settings);
          setTestTo(data.settings.supportEmail || data.settings.smtpUser);
        }
      });
  }, []);

  const onSave = async (event: FormEvent) => {
    event.preventDefault();
    if (!form) return;
    setSaving(true);
    try {
      const res = await fetch("/api/admin/settings", {
        method: "PATCH",
        headers: { "Content-Type": "application/json" },
        credentials: "include",
        body: JSON.stringify({
          smtpHost: form.smtpHost,
          smtpPort: form.smtpPort,
          smtpUser: form.smtpUser,
          smtpPass: form.smtpPass,
          smtpFrom: form.smtpFrom,
          smtpSecure: form.smtpSecure,
        }),
      });
      const data = (await res.json()) as {
        settings?: SiteSettingsDTO;
        error?: string;
      };
      if (!res.ok || !data.settings) {
        toast(data.error ?? "Could not save SMTP settings", "error");
        return;
      }
      setForm(data.settings);
      toast("SMTP settings saved");
    } finally {
      setSaving(false);
    }
  };

  const onTest = async () => {
    setTesting(true);
    try {
      const res = await fetch("/api/admin/settings/test-email", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        credentials: "include",
        body: JSON.stringify({ to: testTo }),
      });
      const data = (await res.json()) as { error?: string; to?: string };
      if (!res.ok) {
        toast(data.error ?? "SMTP test failed", "error");
        return;
      }
      toast(`Test email sent to ${data.to}`);
    } finally {
      setTesting(false);
    }
  };

  if (!form) {
    return <p className="text-sm text-muted">Loading email settings…</p>;
  }

  return (
    <form onSubmit={onSave} className="mx-auto max-w-2xl space-y-8">
      <div>
        <h1 className="text-2xl font-semibold text-foreground">SMTP / email</h1>
        <p className="mt-1 text-sm text-muted">
          Configure transactional email for order receipts and admin tests.
        </p>
      </div>

      <section className="space-y-4 rounded-2xl border border-border bg-card p-5">
        <div className="grid gap-4 sm:grid-cols-2">
          <Field
            label="SMTP host"
            value={form.smtpHost}
            onChange={(smtpHost) => setForm({ ...form, smtpHost })}
            placeholder="smtp.gmail.com"
          />
          <Field
            label="Port"
            value={String(form.smtpPort)}
            onChange={(value) =>
              setForm({ ...form, smtpPort: Number(value) || 587 })
            }
            placeholder="587"
          />
        </div>
        <Field
          label="Username"
          value={form.smtpUser}
          onChange={(smtpUser) => setForm({ ...form, smtpUser })}
        />
        <Field
          label="Password / app password"
          value={form.smtpPass}
          onChange={(smtpPass) => setForm({ ...form, smtpPass })}
          type="password"
        />
        <Field
          label="From address"
          value={form.smtpFrom}
          onChange={(smtpFrom) => setForm({ ...form, smtpFrom })}
          placeholder="BhoFit <noreply@bhofit.com>"
        />
        <label className="flex items-center gap-3 rounded-xl border border-border bg-surface px-4 py-3 text-sm text-foreground">
          <input
            type="checkbox"
            checked={form.smtpSecure}
            onChange={(event) =>
              setForm({ ...form, smtpSecure: event.target.checked })
            }
            className="accent-emerald-500"
          />
          Use TLS/SSL (usually on for port 465)
        </label>
      </section>

      <section className="space-y-3 rounded-2xl border border-border bg-card p-5">
        <p className="text-sm font-medium text-foreground">Send test email</p>
        <Field
          label="Recipient"
          value={testTo}
          onChange={setTestTo}
          placeholder="you@example.com"
        />
        <Button
          type="button"
          onClick={() => void onTest()}
          disabled={testing}
          className="h-11 rounded-xl"
        >
          {testing ? "Sending…" : "Send test email"}
        </Button>
      </section>

      <div className="flex justify-end">
        <Button type="submit" disabled={saving} className="h-11 rounded-xl">
          {saving ? "Saving…" : "Save SMTP settings"}
        </Button>
      </div>
    </form>
  );
}

function Field({
  label,
  value,
  onChange,
  type = "text",
  placeholder,
}: {
  label: string;
  value: string;
  onChange: (value: string) => void;
  type?: string;
  placeholder?: string;
}) {
  return (
    <label className="block space-y-1.5 text-sm">
      <span className="text-muted">{label}</span>
      <input
        type={type}
        value={value}
        placeholder={placeholder}
        onChange={(event) => onChange(event.target.value)}
        className="h-11 w-full rounded-xl border border-border bg-background px-3 text-sm text-foreground outline-none focus:border-emerald-500/50"
      />
    </label>
  );
}
