import {
  TrendingUp,
  Coins,
  Package,
  Gift,
  Brain,
  Shield,
  Terminal,
  Server,
  Scroll,
} from "lucide-react";
import { cn } from "../../lib/utils";
import type { GameSettings, GuildSettings, SettingsMeta } from "../../lib/useSettings";
import {
  Field,
  NumberInput,
  StringInput,
  TextArea,
  Toggle,
  SelectInput,
  RolePicker,
  ChannelPicker,
  MultiRolePicker,
  CategoryPicker,
  FeatureOverridesEditor,
  SectionCard,
} from "./SettingsFormFields";

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

function formatMs(ms: number): string {
  if (ms >= 86_400_000) return `${ms / 86_400_000}h`;
  if (ms >= 60_000) return `${ms / 60_000} min`;
  return `${ms / 1_000}s`;
}

// ---------------------------------------------------------------------------
// Section editors
// ---------------------------------------------------------------------------

export function GuildSection({
  data,
  onChange,
  meta,
}: {
  data: GuildSettings;
  onChange: (d: GuildSettings) => void;
  meta: SettingsMeta | null;
}) {
  const roles = meta?.roles ?? [];
  const channels = meta?.channels ?? [];

  return (
    <div className="space-y-6">
      <SectionCard title="Roles" icon={Server}>
        <div className="grid grid-cols-1 sm:grid-cols-2 gap-5">
          <Field label="Student Role" hint="Assigned to verified students">
            <RolePicker
              value={data.studentRoleId}
              onChange={(v) => onChange({ ...data, studentRoleId: v })}
              roles={roles}
            />
          </Field>
          <Field label="Visitor Role" hint="Assigned to unverified members">
            <RolePicker
              value={data.visitorRoleId}
              onChange={(v) => onChange({ ...data, visitorRoleId: v })}
              roles={roles}
            />
          </Field>
        </div>
        <Field label="Color Roles" hint="Roles users can self-assign for name color">
          <MultiRolePicker
            selected={data.colorRoleIds ?? []}
            onChange={(v) => onChange({ ...data, colorRoleIds: v })}
            roles={roles}
          />
        </Field>
      </SectionCard>

      <SectionCard title="Channels" icon={Server}>
        <div className="grid grid-cols-1 sm:grid-cols-2 gap-5">
          <Field label="Welcome Channel">
            <ChannelPicker
              value={data.welcomeChannelId}
              onChange={(v) => onChange({ ...data, welcomeChannelId: v })}
              channels={channels}
            />
          </Field>
          <Field label="Feedback Channel">
            <ChannelPicker
              value={data.feedbackChannelId}
              onChange={(v) => onChange({ ...data, feedbackChannelId: v })}
              channels={channels}
            />
          </Field>
          <Field label="Terminal Channel">
            <ChannelPicker
              value={data.terminalChannelId}
              onChange={(v) => onChange({ ...data, terminalChannelId: v })}
              channels={channels}
            />
          </Field>
          <Field label="Moderation Log Channel">
            <ChannelPicker
              value={data.moderationLogChannelId}
              onChange={(v) => onChange({ ...data, moderationLogChannelId: v })}
              channels={channels}
            />
          </Field>
        </div>
      </SectionCard>

      <SectionCard title="Welcome Message" icon={Server}>
        <Field label="Message" hint="Sent when a new member joins. Leave empty to disable.">
          <TextArea
            value={data.welcomeMessage ?? ""}
            onChange={(v) => onChange({ ...data, welcomeMessage: v || undefined })}
            placeholder="Welcome to the academy, {user}!"
            rows={3}
          />
        </Field>
      </SectionCard>

      <SectionCard title="Moderation" icon={Shield}>
        <div className="grid grid-cols-1 sm:grid-cols-2 gap-5">
          <Field label="DM on Warn" hint="Send a DM to users when they receive a warning">
            <Toggle
              checked={data.moderationDmOnWarn ?? true}
              onChange={(v) => onChange({ ...data, moderationDmOnWarn: v })}
            />
          </Field>
          <Field label="Auto-Timeout Threshold" hint="Warnings before auto-timeout (empty = disabled)">
            <NumberInput
              value={data.moderationAutoTimeoutThreshold ?? 0}
              onChange={(v) =>
                onChange({
                  ...data,
                  moderationAutoTimeoutThreshold: v || undefined,
                })
              }
              min={0}
            />
          </Field>
        </div>
      </SectionCard>

      <SectionCard title="Feature Overrides" icon={Server}>
        <p className="text-xs text-text-tertiary">
          Toggle feature flags for this guild. Add new flags by name.
        </p>
        <FeatureOverridesEditor
          value={data.featureOverrides ?? {}}
          onChange={(v) => onChange({ ...data, featureOverrides: v })}
        />
      </SectionCard>
    </div>
  );
}

export function LevelingSection({
  data,
  onChange,
}: {
  data: GameSettings["leveling"];
  onChange: (d: GameSettings["leveling"]) => void;
}) {
  return (
    <SectionCard title="Leveling" icon={TrendingUp}>
      <div className="grid grid-cols-1 sm:grid-cols-2 gap-5">
        <Field label="Base XP" hint="Base XP required for level 2">
          <NumberInput
            value={data.base}
            onChange={(v) => onChange({ ...data, base: v })}
            min={1}
          />
        </Field>
        <Field label="Exponent" hint="XP growth curve exponent">
          <NumberInput
            value={data.exponent}
            onChange={(v) => onChange({ ...data, exponent: v })}
            min={1}
            max={5}
            step={0.1}
          />
        </Field>
      </div>
      <h4 className="text-xs font-semibold text-text-tertiary uppercase tracking-wider pt-2">
        Chat XP
      </h4>
      <div className="grid grid-cols-1 sm:grid-cols-3 gap-5">
        <Field label="Cooldown (ms)" hint={formatMs(data.chat.cooldownMs)}>
          <NumberInput
            value={data.chat.cooldownMs}
            onChange={(v) =>
              onChange({ ...data, chat: { ...data.chat, cooldownMs: v } })
            }
            min={0}
            step={1000}
          />
        </Field>
        <Field label="Min XP">
          <NumberInput
            value={data.chat.minXp}
            onChange={(v) =>
              onChange({ ...data, chat: { ...data.chat, minXp: v } })
            }
            min={0}
          />
        </Field>
        <Field label="Max XP">
          <NumberInput
            value={data.chat.maxXp}
            onChange={(v) =>
              onChange({ ...data, chat: { ...data.chat, maxXp: v } })
            }
            min={0}
          />
        </Field>
      </div>
    </SectionCard>
  );
}

export function EconomySection({
  data,
  onChange,
}: {
  data: GameSettings["economy"];
  onChange: (d: GameSettings["economy"]) => void;
}) {
  const setDaily = (patch: Partial<GameSettings["economy"]["daily"]>) =>
    onChange({ ...data, daily: { ...data.daily, ...patch } });
  const setTransfers = (
    patch: Partial<GameSettings["economy"]["transfers"]>
  ) => onChange({ ...data, transfers: { ...data.transfers, ...patch } });
  const setExam = (patch: Partial<GameSettings["economy"]["exam"]>) =>
    onChange({ ...data, exam: { ...data.exam, ...patch } });

  return (
    <SectionCard title="Economy" icon={Coins}>
      <h4 className="text-xs font-semibold text-text-tertiary uppercase tracking-wider">
        Daily Rewards
      </h4>
      <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-5">
        <Field label="Amount (AU)">
          <StringInput
            value={data.daily.amount}
            onChange={(v) => setDaily({ amount: v })}
          />
        </Field>
        <Field label="Streak Bonus">
          <StringInput
            value={data.daily.streakBonus}
            onChange={(v) => setDaily({ streakBonus: v })}
          />
        </Field>
        <Field label="Weekly Bonus">
          <StringInput
            value={data.daily.weeklyBonus}
            onChange={(v) => setDaily({ weeklyBonus: v })}
          />
        </Field>
        <Field label="Cooldown (ms)" hint={formatMs(data.daily.cooldownMs)}>
          <NumberInput
            value={data.daily.cooldownMs}
            onChange={(v) => setDaily({ cooldownMs: v })}
            min={0}
            step={1000}
          />
        </Field>
      </div>

      <h4 className="text-xs font-semibold text-text-tertiary uppercase tracking-wider pt-2">
        Transfers
      </h4>
      <div className="grid grid-cols-1 sm:grid-cols-2 gap-5">
        <Field label="Min Amount">
          <StringInput
            value={data.transfers.minAmount}
            onChange={(v) => setTransfers({ minAmount: v })}
          />
        </Field>
        <Field label="Allow Self-Transfer">
          <Toggle
            checked={data.transfers.allowSelfTransfer}
            onChange={(v) => setTransfers({ allowSelfTransfer: v })}
          />
        </Field>
      </div>

      <h4 className="text-xs font-semibold text-text-tertiary uppercase tracking-wider pt-2">
        Exam
      </h4>
      <div className="grid grid-cols-1 sm:grid-cols-2 gap-5">
        <Field label="Min Multiplier">
          <NumberInput
            value={data.exam.multMin}
            onChange={(v) => setExam({ multMin: v })}
            min={0}
            step={0.1}
          />
        </Field>
        <Field label="Max Multiplier">
          <NumberInput
            value={data.exam.multMax}
            onChange={(v) => setExam({ multMax: v })}
            min={0}
            step={0.1}
          />
        </Field>
      </div>
    </SectionCard>
  );
}

export function InventorySection({
  data,
  onChange,
}: {
  data: GameSettings["inventory"];
  onChange: (d: GameSettings["inventory"]) => void;
}) {
  return (
    <SectionCard title="Inventory" icon={Package}>
      <div className="grid grid-cols-1 sm:grid-cols-2 gap-5">
        <Field label="Max Stack Size">
          <StringInput
            value={data.maxStackSize}
            onChange={(v) => onChange({ ...data, maxStackSize: v })}
          />
        </Field>
        <Field label="Max Slots">
          <NumberInput
            value={data.maxSlots}
            onChange={(v) => onChange({ ...data, maxSlots: v })}
            min={1}
          />
        </Field>
      </div>
    </SectionCard>
  );
}

export function LootdropSection({
  data,
  onChange,
}: {
  data: GameSettings["lootdrop"];
  onChange: (d: GameSettings["lootdrop"]) => void;
}) {
  const setReward = (patch: Partial<GameSettings["lootdrop"]["reward"]>) =>
    onChange({ ...data, reward: { ...data.reward, ...patch } });

  return (
    <SectionCard title="Lootdrops" icon={Gift}>
      <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-5">
        <Field
          label="Activity Window (ms)"
          hint={formatMs(data.activityWindowMs)}
        >
          <NumberInput
            value={data.activityWindowMs}
            onChange={(v) => onChange({ ...data, activityWindowMs: v })}
            min={0}
            step={1000}
          />
        </Field>
        <Field label="Min Messages">
          <NumberInput
            value={data.minMessages}
            onChange={(v) => onChange({ ...data, minMessages: v })}
            min={1}
          />
        </Field>
        <Field label="Spawn Chance" hint="0.0 - 1.0">
          <NumberInput
            value={data.spawnChance}
            onChange={(v) => onChange({ ...data, spawnChance: v })}
            min={0}
            max={1}
            step={0.01}
          />
        </Field>
        <Field label="Cooldown (ms)" hint={formatMs(data.cooldownMs)}>
          <NumberInput
            value={data.cooldownMs}
            onChange={(v) => onChange({ ...data, cooldownMs: v })}
            min={0}
            step={1000}
          />
        </Field>
      </div>

      <h4 className="text-xs font-semibold text-text-tertiary uppercase tracking-wider pt-2">
        Reward
      </h4>
      <div className="grid grid-cols-1 sm:grid-cols-3 gap-5">
        <Field label="Min Reward">
          <NumberInput
            value={data.reward.min}
            onChange={(v) => setReward({ min: v })}
            min={0}
          />
        </Field>
        <Field label="Max Reward">
          <NumberInput
            value={data.reward.max}
            onChange={(v) => setReward({ max: v })}
            min={0}
          />
        </Field>
        <Field label="Currency">
          <SelectInput
            value={data.reward.currency}
            onChange={(v) => setReward({ currency: v })}
            options={[
              { value: "AU", label: "AU (Astral Units)" },
              { value: "CU", label: "CU (Constellation Units)" },
            ]}
          />
        </Field>
      </div>
    </SectionCard>
  );
}

export function TriviaSection({
  data,
  onChange,
}: {
  data: GameSettings["trivia"];
  onChange: (d: GameSettings["trivia"]) => void;
}) {
  return (
    <SectionCard title="Trivia" icon={Brain}>
      <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-5">
        <Field label="Entry Fee (AU)">
          <StringInput
            value={data.entryFee}
            onChange={(v) => onChange({ ...data, entryFee: v })}
          />
        </Field>
        <Field label="Reward Multiplier">
          <NumberInput
            value={data.rewardMultiplier}
            onChange={(v) => onChange({ ...data, rewardMultiplier: v })}
            min={0}
            step={0.1}
          />
        </Field>
        <Field label="Timeout (seconds)">
          <NumberInput
            value={data.timeoutSeconds}
            onChange={(v) => onChange({ ...data, timeoutSeconds: v })}
            min={5}
          />
        </Field>
        <Field label="Cooldown (ms)" hint={formatMs(data.cooldownMs)}>
          <NumberInput
            value={data.cooldownMs}
            onChange={(v) => onChange({ ...data, cooldownMs: v })}
            min={0}
            step={1000}
          />
        </Field>
      </div>
      <div className="grid grid-cols-1 sm:grid-cols-2 gap-5">
        <Field label="Difficulty">
          <SelectInput
            value={data.difficulty}
            onChange={(v) => onChange({ ...data, difficulty: v })}
            options={[
              { value: "random", label: "Random" },
              { value: "easy", label: "Easy" },
              { value: "medium", label: "Medium" },
              { value: "hard", label: "Hard" },
            ]}
          />
        </Field>
      </div>

      <Field
        label="Categories"
        hint="Select which OpenTDB categories to pull from. Leave empty for all categories."
      >
        <CategoryPicker
          selected={data.categories ?? []}
          onChange={(v) => onChange({ ...data, categories: v })}
        />
      </Field>
    </SectionCard>
  );
}

export function ModerationSection({
  data,
  onChange,
}: {
  data: GameSettings["moderation"];
  onChange: (d: GameSettings["moderation"]) => void;
}) {
  const setPrune = (patch: Partial<GameSettings["moderation"]["prune"]>) =>
    onChange({ ...data, prune: { ...data.prune, ...patch } });

  return (
    <SectionCard title="Moderation" icon={Shield}>
      <h4 className="text-xs font-semibold text-text-tertiary uppercase tracking-wider">
        Prune
      </h4>
      <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-5">
        <Field label="Max Amount">
          <NumberInput
            value={data.prune.maxAmount}
            onChange={(v) => setPrune({ maxAmount: v })}
            min={1}
          />
        </Field>
        <Field
          label="Confirm Threshold"
          hint="Require confirmation above this"
        >
          <NumberInput
            value={data.prune.confirmThreshold}
            onChange={(v) => setPrune({ confirmThreshold: v })}
            min={1}
          />
        </Field>
        <Field label="Batch Size">
          <NumberInput
            value={data.prune.batchSize}
            onChange={(v) => setPrune({ batchSize: v })}
            min={1}
          />
        </Field>
        <Field
          label="Batch Delay (ms)"
          hint={formatMs(data.prune.batchDelayMs)}
        >
          <NumberInput
            value={data.prune.batchDelayMs}
            onChange={(v) => setPrune({ batchDelayMs: v })}
            min={0}
            step={100}
          />
        </Field>
      </div>
    </SectionCard>
  );
}

export function QuestSection({
  data,
  onChange,
}: {
  data: GameSettings["quest"];
  onChange: (d: GameSettings["quest"]) => void;
}) {
  return (
    <SectionCard title="Quests" icon={Scroll}>
      <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-5">
        <Field
          label="Max Active Quests"
          hint="How many incomplete quests a player can have at once"
        >
          <NumberInput
            value={data.maxActiveQuests}
            onChange={(v) => onChange({ ...data, maxActiveQuests: v })}
            min={1}
          />
        </Field>
      </div>
    </SectionCard>
  );
}

export function CommandsSection({
  commands,
  onChange,
  meta,
}: {
  commands: GameSettings["commands"];
  meta: SettingsMeta | null;
  onChange: (d: GameSettings["commands"]) => void;
}) {
  const grouped = (meta?.commands ?? []).reduce<
    Record<string, Array<{ name: string; category: string }>>
  >((acc, cmd) => {
    (acc[cmd.category] ??= []).push(cmd);
    return acc;
  }, {});

  const categories = Object.keys(grouped).sort();

  if (categories.length === 0) {
    return (
      <SectionCard title="Commands" icon={Terminal}>
        <p className="text-sm text-text-tertiary">
          No registered commands found. Make sure the bot is online.
        </p>
      </SectionCard>
    );
  }

  return (
    <SectionCard title="Commands" icon={Terminal}>
      <p className="text-xs text-text-tertiary">
        Toggle commands on or off. Disabled commands cannot be used by anyone.
      </p>
      <div className="space-y-6">
        {categories.map((cat) => (
          <div key={cat}>
            <h4 className="text-xs font-semibold text-text-tertiary uppercase tracking-wider mb-3">
              {cat}
            </h4>
            <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-x-6 gap-y-3">
              {grouped[cat]!.map((cmd) => {
                const enabled = commands[cmd.name] !== false;
                return (
                  <div
                    key={cmd.name}
                    className="flex items-center justify-between py-1.5"
                  >
                    <span
                      className={cn(
                        "text-sm font-mono",
                        enabled ? "text-foreground" : "text-text-disabled"
                      )}
                    >
                      /{cmd.name}
                    </span>
                    <Toggle
                      checked={enabled}
                      onChange={(v) =>
                        onChange({ ...commands, [cmd.name]: v })
                      }
                    />
                  </div>
                );
              })}
            </div>
          </div>
        ))}
      </div>
    </SectionCard>
  );
}
