// @File: src/pages/admin/cms/CmsVisitorSettings.tsx
// @Desc: Privacy & security settings for the Visitor Monitor.
import { useCallback, useEffect, useState } from "react";
import { Loader2, ShieldCheck } from "lucide-react";
import CmsLayout from "./CmsLayout";
import {
  Field,
  PageHeader,
  SaveBar,
  SectionCard,
  TextArea,
  TextInput,
  Toggle,
} from "./ui";
import { vmGetSettings, vmUpdateSettings, type VmSettings } from "@/lib/adminApi";

const DEFAULT_SETTINGS: VmSettings = {
  tracking_enabled: true,
  retention_days: 90,
  excluded_ips: [],
  exclude_staff: true,
  mask_sensitive: true,
  updated_at: null,
};

export default function CmsVisitorSettings() {
  const [settings, setSettings] = useState<VmSettings>(DEFAULT_SETTINGS);
  const [excludedText, setExcludedText] = useState("");
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [notice, setNotice] = useState<string | null>(null);

  const load = useCallback(async () => {
    setLoading(true);
    setError(null);
    try {
      const s = await vmGetSettings();
      setSettings(s);
      setExcludedText((s.excluded_ips || []).join("\n"));
    } catch (err) {
      setError(err instanceof Error ? err.message : "Failed to load settings");
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => {
    void load();
  }, [load]);

  const save = async () => {
    setSaving(true);
    setError(null);
    setNotice(null);
    try {
      const ips = excludedText
        .split(/[\n,]/)
        .map((s) => s.trim())
        .filter(Boolean);
      const updated = await vmUpdateSettings({
        tracking_enabled: settings.tracking_enabled,
        retention_days: settings.retention_days,
        excluded_ips: ips,
        exclude_staff: settings.exclude_staff,
        mask_sensitive: settings.mask_sensitive,
      });
      setSettings(updated);
      setExcludedText(updated.excluded_ips.join("\n"));
      setNotice("Saved.");
      setTimeout(() => setNotice(null), 2000);
    } catch (err) {
      setError(err instanceof Error ? err.message : "Save failed");
    } finally {
      setSaving(false);
    }
  };

  if (loading) {
    return (
      <CmsLayout>
        <div className="flex items-center gap-2 text-slate-500 text-sm">
          <Loader2 className="w-4 h-4 animate-spin" />
          Loading settings…
        </div>
      </CmsLayout>
    );
  }

  return (
    <CmsLayout>
      <PageHeader
        title="Privacy & Security"
        description="Control retention, IP exclusions and data masking for the visitor monitor."
        icon={<ShieldCheck className="w-6 h-6" />}
      />

      {error && (
        <div className="mb-4 p-3 rounded-lg bg-red-50 border border-red-200 text-sm text-red-700">
          {error}
        </div>
      )}
      {notice && (
        <div className="mb-4 p-3 rounded-lg bg-emerald-50 border border-emerald-200 text-sm text-emerald-700">
          {notice}
        </div>
      )}

      <SectionCard title="Tracking">
        <Toggle
          checked={settings.tracking_enabled}
          onChange={(v) => setSettings((s) => ({ ...s, tracking_enabled: v }))}
          label="Enable visitor tracking"
          description="When off, new pageviews and events are ignored."
        />
        <Toggle
          checked={settings.exclude_staff}
          onChange={(v) => setSettings((s) => ({ ...s, exclude_staff: v }))}
          label="Exclude admins and staff"
          description="Visitors logged in with the admin or staff role are marked excluded."
        />
        <Toggle
          checked={settings.mask_sensitive}
          onChange={(v) => setSettings((s) => ({ ...s, mask_sensitive: v }))}
          label="Mask sensitive data"
          description="Masks the last octet of IP addresses shown in admin views."
        />
      </SectionCard>

      <div className="h-4" />

      <SectionCard title="Retention & Exclusions">
        <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
          <Field label="Retention (days)" hint="Older data can be purged by cleanup jobs">
            <TextInput
              type="number"
              min={1}
              max={3650}
              value={settings.retention_days}
              onChange={(e) =>
                setSettings((s) => ({
                  ...s,
                  retention_days: Math.max(1, Math.min(3650, Number(e.target.value) || 90)),
                }))
              }
            />
          </Field>
          <Field label="Last updated">
            <div className="text-sm text-slate-600 px-3 py-2.5">
              {settings.updated_at ? new Date(settings.updated_at).toLocaleString() : "—"}
            </div>
          </Field>
        </div>
        <Field
          label="Excluded IPs / CIDRs"
          hint="One per line. Supports IPv4, IPv6 and CIDR ranges."
        >
          <TextArea
            rows={5}
            value={excludedText}
            onChange={(e) => setExcludedText(e.target.value)}
            placeholder={"10.0.0.0/8\n203.0.113.42"}
            className="font-mono"
          />
        </Field>
        <div className="p-4 rounded-lg bg-slate-50 border border-slate-200 text-xs text-slate-600">
          <div className="font-semibold text-slate-800 mb-1">Data minimisation</div>
          Passwords and payment data are never stored. Event payload keys matching common
          sensitive patterns (password, pwd, card, cvv, token, secret, pin, ssn) are stripped
          on ingest.
        </div>
      </SectionCard>

      <SaveBar onSave={() => void save()} saving={saving} />
    </CmsLayout>
  );
}