import { useEffect, useState } from "react";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { Bell, Monitor, Pause, Play, RefreshCw, User, X } from "lucide-react";
import { SCHEMES, type Scheme, type ThemePrefs } from "../lib/theme";
import { api, type Me } from "../lib/api";
import {
  configureNotifications,
  getNotifSettings,
  notify,
  type NotifSettings,
} from "../lib/notifications";

type TabId = "appearance" | "notifications" | "sync" | "account";
const TABS: { id: TabId; label: string; icon: typeof Monitor }[] = [
  { id: "appearance", label: "Appearance", icon: Monitor },
  { id: "notifications", label: "Notifications", icon: Bell },
  { id: "sync", label: "Sync", icon: RefreshCw },
  { id: "account", label: "Account", icon: User },
];

export default function SettingsPanel({
  me,
  theme,
  setTheme,
  view,
  setView,
  onClose,
}: {
  me: Me;
  theme: ThemePrefs;
  setTheme: (t: ThemePrefs) => void;
  view: "grid" | "list";
  setView: (v: "grid" | "list") => void;
  onClose: () => void;
}) {
  const [tab, setTab] = useState<TabId>("appearance");

  useEffect(() => {
    function onKey(e: KeyboardEvent) {
      if (e.key === "Escape") onClose();
    }
    document.addEventListener("keydown", onKey);
    return () => document.removeEventListener("keydown", onKey);
  }, [onClose]);

  return (
    <div className="fixed inset-0 z-40 flex justify-end">
      <div className="absolute inset-0 bg-black/40" onClick={onClose} />
      <div className="relative w-[min(92vw,440px)] h-full bg-surface border-l border-border shadow-2xl flex flex-col animate-[fadeIn_0.15s_ease]">
        <div className="flex items-center justify-between px-4 h-14 border-b border-border shrink-0">
          <div className="text-base font-semibold">Settings</div>
          <button onClick={onClose} className="p-2 rounded-lg text-muted hover:text-fg hover:bg-card transition">
            <X className="w-5 h-5" />
          </button>
        </div>

        <div className="flex gap-1 px-3 py-2 border-b border-border shrink-0 overflow-x-auto">
          {TABS.map((t) => (
            <button
              key={t.id}
              onClick={() => setTab(t.id)}
              className={`flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-sm whitespace-nowrap transition ${
                tab === t.id ? "bg-card text-fg" : "text-muted hover:text-fg"
              }`}
            >
              <t.icon className="w-4 h-4" />
              {t.label}
            </button>
          ))}
        </div>

        <div className="flex-1 overflow-y-auto p-4">
          {tab === "appearance" && (
            <Appearance theme={theme} setTheme={setTheme} view={view} setView={setView} />
          )}
          {tab === "notifications" && <Notifications />}
          {tab === "sync" && <Sync me={me} />}
          {tab === "account" && <Account me={me} />}
        </div>
      </div>
    </div>
  );
}

function Section({ title, children }: { title: string; children: React.ReactNode }) {
  return (
    <div className="mb-6">
      <div className="text-xs uppercase tracking-wide text-muted mb-2">{title}</div>
      {children}
    </div>
  );
}

function Row({ label, children }: { label: string; children: React.ReactNode }) {
  return (
    <label className="flex items-center justify-between gap-3 py-1.5 text-sm">
      <span>{label}</span>
      {children}
    </label>
  );
}

function Switch({ checked, onChange }: { checked: boolean; onChange: (v: boolean) => void }) {
  return (
    <button
      type="button"
      onClick={() => onChange(!checked)}
      className={`w-9 h-5 rounded-full transition relative shrink-0 ${checked ? "bg-accent" : "bg-border"}`}
    >
      <span
        className={`absolute top-0.5 w-4 h-4 rounded-full bg-white transition-all ${
          checked ? "left-[18px]" : "left-0.5"
        }`}
      />
    </button>
  );
}

const PERF_KEY = "subfeed.perfMode";

function Appearance({
  theme,
  setTheme,
  view,
  setView,
}: {
  theme: ThemePrefs;
  setTheme: (t: ThemePrefs) => void;
  view: "grid" | "list";
  setView: (v: "grid" | "list") => void;
}) {
  const [perf, setPerf] = useState(() => localStorage.getItem(PERF_KEY) === "1");
  useEffect(() => {
    document.documentElement.dataset.perf = perf ? "1" : "";
  }, [perf]);
  function togglePerf(v: boolean) {
    setPerf(v);
    localStorage.setItem(PERF_KEY, v ? "1" : "0");
    api.savePrefs({ performanceMode: v }).catch(() => {});
  }

  return (
    <>
      <Section title="Color scheme">
        <div className="grid grid-cols-4 gap-2">
          {SCHEMES.map((s) => (
            <button
              key={s.id}
              onClick={() => setTheme({ ...theme, scheme: s.id as Scheme })}
              title={s.name}
              className={`h-9 rounded-lg border-2 transition ${
                theme.scheme === s.id ? "border-fg" : "border-transparent"
              }`}
              style={{ background: s.swatch }}
            />
          ))}
        </div>
      </Section>

      <Section title="Display">
        <Row label="Dark mode">
          <Switch
            checked={theme.mode === "dark"}
            onChange={(v) => setTheme({ ...theme, mode: v ? "dark" : "light" })}
          />
        </Row>
        <Row label="List view">
          <Switch checked={view === "list"} onChange={(v) => setView(v ? "list" : "grid")} />
        </Row>
        <Row label="Performance mode">
          <Switch checked={perf} onChange={togglePerf} />
        </Row>
      </Section>

      <Section title="Text size">
        <input
          type="range"
          min={0.9}
          max={1.3}
          step={0.02}
          value={theme.fontScale}
          onChange={(e) => setTheme({ ...theme, fontScale: Number(e.target.value) })}
          className="w-full accent-accent"
        />
        <div className="text-right text-xs text-muted">{Math.round(theme.fontScale * 100)}%</div>
      </Section>
    </>
  );
}

function Notifications() {
  const [cfg, setCfg] = useState<NotifSettings>(() => getNotifSettings());
  function update(p: Partial<NotifSettings>) {
    const next = { ...cfg, ...p };
    setCfg(next);
    configureNotifications(next);
    api.savePrefs({ notifications: next }).catch(() => {});
  }
  return (
    <Section title="Notifications">
      <Row label="Sound on attention-needing alerts">
        <Switch checked={cfg.sound} onChange={(v) => update({ sound: v })} />
      </Row>
      <div className="py-1.5 text-sm">
        <div className="flex items-center justify-between">
          <span>Auto-dismiss</span>
          <span className="text-muted text-xs">{(cfg.durationMs / 1000).toFixed(0)}s</span>
        </div>
        <input
          type="range"
          min={3000}
          max={15000}
          step={1000}
          value={cfg.durationMs}
          onChange={(e) => update({ durationMs: Number(e.target.value) })}
          className="w-full accent-accent mt-1"
        />
      </div>
      <button
        onClick={() => notify({ level: "info", message: "This is a test notification." })}
        className="mt-2 text-sm text-accent hover:underline"
      >
        Send a test notification
      </button>
    </Section>
  );
}

function Sync({ me }: { me: Me }) {
  const qc = useQueryClient();
  const status = useQuery({ queryKey: ["my-status"], queryFn: api.myStatus });
  const s = status.data;
  const syncSubs = useMutation({
    mutationFn: () => api.syncSubscriptions(),
    onSuccess: (r: { subscriptions?: number }) => {
      qc.invalidateQueries({ queryKey: ["my-status"] });
      qc.invalidateQueries({ queryKey: ["channels"] });
      notify({ level: "success", message: `Synced ${r.subscriptions ?? 0} subscriptions` });
    },
    onError: () => notify({ level: "error", message: "Sync failed" }),
  });
  const pauseResume = useMutation({
    mutationFn: (paused: boolean) => (paused ? api.resumeSync() : api.pauseSync()),
    onSuccess: () => qc.invalidateQueries({ queryKey: ["my-status"] }),
  });

  return (
    <>
      <Section title="My sync status">
        {s ? (
          <div className="space-y-1.5 text-sm">
            <Row label="Channels">{s.channels_total}</Row>
            <Row label="Recent synced">{`${s.channels_recent_synced}/${s.channels_total}`}</Row>
            <Row label="Full history">{`${s.channels_deep_done}/${s.channels_total}`}</Row>
            <Row label="My videos">{s.my_videos.toLocaleString()}</Row>
            <Row label="Quota left today">{s.quota_remaining_today.toLocaleString()}</Row>
          </div>
        ) : (
          <div className="text-muted text-sm">Loading…</div>
        )}
      </Section>

      <Section title="Actions">
        <button
          onClick={() => syncSubs.mutate()}
          disabled={syncSubs.isPending}
          className="flex items-center gap-2 px-3 py-2 rounded-lg border border-border text-sm hover:border-accent disabled:opacity-50 transition"
        >
          <RefreshCw className={`w-4 h-4 ${syncSubs.isPending ? "animate-spin" : ""}`} />
          Sync subscriptions
        </button>
      </Section>

      {me.role === "admin" && s && (
        <Section title="Admin">
          <button
            onClick={() => pauseResume.mutate(s.paused)}
            className="flex items-center gap-2 px-3 py-2 rounded-lg border border-border text-sm hover:border-accent transition"
          >
            {s.paused ? <Play className="w-4 h-4" /> : <Pause className="w-4 h-4" />}
            {s.paused ? "Resume background sync" : "Pause background sync"}
          </button>
        </Section>
      )}
    </>
  );
}

function Account({ me }: { me: Me }) {
  return (
    <Section title="Account">
      <div className="flex items-center gap-3 mb-3">
        {me.avatar_url ? (
          <img src={me.avatar_url} alt="" className="w-12 h-12 rounded-full" />
        ) : (
          <div className="w-12 h-12 rounded-full bg-card grid place-items-center font-semibold">
            {(me.display_name?.[0] ?? me.email[0] ?? "?").toUpperCase()}
          </div>
        )}
        <div className="min-w-0">
          <div className="font-semibold truncate">{me.display_name ?? me.email.split("@")[0]}</div>
          <div className="text-xs text-muted truncate">{me.email}</div>
          <div className="text-xs text-muted capitalize">{me.role}</div>
        </div>
      </div>
      <p className="text-xs text-muted leading-relaxed">
        Playlist editing &amp; YouTube export, and the admin approval queue, arrive in the next
        phases of this milestone.
      </p>
    </Section>
  );
}
