import { useCallback, useEffect, useState } from "react";
import {
  Loader2,
  AlertTriangle,
  Save,
  Check,
  TrendingUp,
  Coins,
  Package,
  Gift,
  Brain,
  Shield,
  Terminal,
  RotateCcw,
  Server,
  Scroll,
} from "lucide-react";
import { cn } from "../lib/utils";
import {
  useSettings,
  type GameSettings,
  type GuildSettings,
  type SettingsMeta,
} from "../lib/useSettings";
import {
  GuildSection,
  LevelingSection,
  EconomySection,
  InventorySection,
  LootdropSection,
  TriviaSection,
  ModerationSection,
  QuestSection,
  CommandsSection,
} from "./components/SettingsSections";

// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------

type SettingsSection =
  | "guild"
  | "leveling"
  | "economy"
  | "inventory"
  | "lootdrop"
  | "trivia"
  | "moderation"
  | "quest"
  | "commands";

const sections: {
  key: SettingsSection;
  label: string;
  icon: React.ComponentType<{ className?: string }>;
}[] = [
  { key: "guild", label: "Guild", icon: Server },
  { key: "leveling", label: "Leveling", icon: TrendingUp },
  { key: "economy", label: "Economy", icon: Coins },
  { key: "inventory", label: "Inventory", icon: Package },
  { key: "lootdrop", label: "Lootdrops", icon: Gift },
  { key: "trivia", label: "Trivia", icon: Brain },
  { key: "moderation", label: "Moderation", icon: Shield },
  { key: "quest", label: "Quests", icon: Scroll },
  { key: "commands", label: "Commands", icon: Terminal },
];

// ---------------------------------------------------------------------------
// Default guild settings (used when guild has no config yet)
// ---------------------------------------------------------------------------

const defaultGuildSettings: GuildSettings = {
  guildId: "",
  configured: false,
  colorRoleIds: [],
  moderationDmOnWarn: true,
  featureOverrides: {},
};

// ---------------------------------------------------------------------------
// Main Settings page
// ---------------------------------------------------------------------------

export default function Settings() {
  const {
    settings,
    guildSettings,
    meta,
    loading,
    saving,
    error,
    saveSettings,
    saveGuildSettings,
  } = useSettings();

  const [gameDraft, setGameDraft] = useState<GameSettings | null>(null);
  const [guildDraft, setGuildDraft] = useState<GuildSettings | null>(null);
  const [activeSection, setActiveSection] =
    useState<SettingsSection>("guild");
  const [saveSuccess, setSaveSuccess] = useState(false);

  // Sync drafts when data loads
  useEffect(() => {
    if (settings && !gameDraft) {
      setGameDraft(structuredClone(settings));
    }
  }, [settings, gameDraft]);

  useEffect(() => {
    if (!guildDraft) {
      setGuildDraft(
        guildSettings
          ? structuredClone(guildSettings)
          : { ...defaultGuildSettings, guildId: meta?.guildId ?? "" }
      );
    }
  }, [guildSettings, guildDraft, meta?.guildId]);

  const isGuildTab = activeSection === "guild";

  const gameDirty =
    gameDraft && settings
      ? JSON.stringify(gameDraft) !== JSON.stringify(settings)
      : false;

  const guildDirty =
    guildDraft && guildSettings
      ? JSON.stringify(guildDraft) !== JSON.stringify(guildSettings)
      : guildDraft
      ? JSON.stringify(guildDraft) !==
        JSON.stringify({ ...defaultGuildSettings, guildId: meta?.guildId ?? "" })
      : false;

  const dirty = isGuildTab ? guildDirty : gameDirty;

  const handleSave = useCallback(async () => {
    let ok: boolean;
    if (isGuildTab && guildDraft) {
      ok = await saveGuildSettings(guildDraft);
    } else if (gameDraft) {
      ok = await saveSettings(
        gameDraft as unknown as Record<string, unknown>
      );
    } else {
      return;
    }
    if (ok) {
      setSaveSuccess(true);
      setTimeout(() => setSaveSuccess(false), 2000);
      // Reset drafts so they re-sync from server
      if (isGuildTab) setGuildDraft(null);
      else setGameDraft(null);
    }
  }, [isGuildTab, gameDraft, guildDraft, saveSettings, saveGuildSettings]);

  const handleReset = useCallback(() => {
    if (isGuildTab) {
      setGuildDraft(
        guildSettings
          ? structuredClone(guildSettings)
          : { ...defaultGuildSettings, guildId: meta?.guildId ?? "" }
      );
    } else if (settings) {
      setGameDraft(structuredClone(settings));
    }
  }, [isGuildTab, settings, guildSettings, meta?.guildId]);

  if (loading) {
    return (
      <div className="flex items-center justify-center py-32">
        <Loader2 className="w-6 h-6 animate-spin text-primary" />
      </div>
    );
  }

  if (error && !settings) {
    return (
      <div className="flex items-center justify-center py-32">
        <div className="text-center">
          <AlertTriangle className="w-8 h-8 text-warning mx-auto mb-3" />
          <p className="text-sm text-text-tertiary">{error}</p>
        </div>
      </div>
    );
  }

  if (!gameDraft || !guildDraft) return null;

  const updateGameSection = <K extends keyof GameSettings>(
    key: K,
    value: GameSettings[K]
  ) => setGameDraft((prev) => (prev ? { ...prev, [key]: value } : prev));

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div>
          <h1 className="font-display text-2xl font-bold tracking-tight">
            Settings
          </h1>
          <p className="text-sm text-text-tertiary mt-1">
            Configure guild, bot systems, economy, and command access
          </p>
        </div>
        <div className="flex items-center gap-3">
          {dirty && (
            <button
              onClick={handleReset}
              className="inline-flex items-center gap-2 rounded-md border border-border px-4 py-2 text-sm font-medium text-text-secondary hover:bg-primary/10 transition-colors"
            >
              <RotateCcw className="w-4 h-4" />
              Discard
            </button>
          )}
          <button
            onClick={handleSave}
            disabled={!dirty || saving}
            className={cn(
              "inline-flex items-center gap-2 rounded-md px-5 py-2 text-sm font-medium transition-colors",
              dirty
                ? "bg-primary text-primary-foreground hover:bg-primary/90 shadow-sm shadow-primary/30"
                : "bg-primary/30 text-primary-foreground/50 cursor-not-allowed"
            )}
          >
            {saving ? (
              <Loader2 className="w-4 h-4 animate-spin" />
            ) : saveSuccess ? (
              <Check className="w-4 h-4" />
            ) : (
              <Save className="w-4 h-4" />
            )}
            {saving ? "Saving\u2026" : saveSuccess ? "Saved" : "Save Changes"}
          </button>
        </div>
      </div>

      {/* Error banner */}
      {error && (
        <div className="flex items-center gap-3 bg-destructive/10 border border-destructive/30 rounded-lg px-5 py-3">
          <AlertTriangle className="w-4 h-4 text-destructive shrink-0" />
          <span className="text-sm text-destructive">{error}</span>
        </div>
      )}

      {/* Section tabs */}
      <div className="flex gap-1 overflow-x-auto border-b border-border pb-px">
        {sections.map(({ key, label, icon: Icon }) => (
          <button
            key={key}
            onClick={() => setActiveSection(key)}
            className={cn(
              "inline-flex items-center gap-2 px-4 py-2.5 text-sm font-medium whitespace-nowrap transition-colors border-b-2 -mb-px",
              activeSection === key
                ? "border-primary text-primary"
                : "border-transparent text-text-tertiary hover:text-foreground hover:border-primary/30"
            )}
          >
            <Icon className="w-4 h-4" />
            {label}
          </button>
        ))}
      </div>

      {/* Active section content */}
      <div>
        {activeSection === "guild" && (
          <GuildSection
            data={guildDraft}
            onChange={setGuildDraft}
            meta={meta}
          />
        )}
        {activeSection === "leveling" && (
          <LevelingSection
            data={gameDraft.leveling}
            onChange={(v) => updateGameSection("leveling", v)}
          />
        )}
        {activeSection === "economy" && (
          <EconomySection
            data={gameDraft.economy}
            onChange={(v) => updateGameSection("economy", v)}
          />
        )}
        {activeSection === "inventory" && (
          <InventorySection
            data={gameDraft.inventory}
            onChange={(v) => updateGameSection("inventory", v)}
          />
        )}
        {activeSection === "lootdrop" && (
          <LootdropSection
            data={gameDraft.lootdrop}
            onChange={(v) => updateGameSection("lootdrop", v)}
          />
        )}
        {activeSection === "trivia" && (
          <TriviaSection
            data={gameDraft.trivia}
            onChange={(v) => updateGameSection("trivia", v)}
          />
        )}
        {activeSection === "moderation" && (
          <ModerationSection
            data={gameDraft.moderation}
            onChange={(v) => updateGameSection("moderation", v)}
          />
        )}
        {activeSection === "quest" && (
          <QuestSection
            data={gameDraft.quest}
            onChange={(v) => updateGameSection("quest", v)}
          />
        )}
        {activeSection === "commands" && (
          <CommandsSection
            commands={gameDraft.commands}
            meta={meta}
            onChange={(v) => updateGameSection("commands", v)}
          />
        )}
      </div>

      {/* Dirty indicator footer */}
      {dirty && (
        <div className="sticky bottom-0 -mx-6 px-6 py-3 bg-background/80 backdrop-blur border-t border-border flex items-center justify-between">
          <span className="text-sm text-warning font-medium">
            You have unsaved changes
          </span>
          <div className="flex items-center gap-3">
            <button
              onClick={handleReset}
              className="text-sm text-text-tertiary hover:text-foreground transition-colors"
            >
              Discard
            </button>
            <button
              onClick={handleSave}
              disabled={saving}
              className="inline-flex items-center gap-2 rounded-md bg-primary text-primary-foreground px-4 py-1.5 text-sm font-medium hover:bg-primary/90 transition-colors"
            >
              {saving ? (
                <Loader2 className="w-3.5 h-3.5 animate-spin" />
              ) : (
                <Save className="w-3.5 h-3.5" />
              )}
              Save
            </button>
          </div>
        </div>
      )}
    </div>
  );
}
