"use client";

import { useCallback, useMemo, useState } from "react";
import type { CaliberDto, PlatformDto } from "../_lib/types";
import { RightDrawer } from "./RightDrawer";

type ProductVisibility = "PUBLIC" | "HIDDEN";
type ProductStatus = "ACTIVE" | "DISABLED" | "ARCHIVED";

type BulkUpdateSet = Partial<{
  visibility: ProductVisibility;
  status: ProductStatus;
  builderEligible: boolean;
  adminLocked: boolean;
  adminNote: string;

  platform: string;
  platformLocked: boolean;

  caliber: string;
  caliberGroup: string;
  caliberLocked: boolean;
  forceCaliberUpdate: boolean;

  partRole: string;
  partRoleLocked: boolean;

  classificationReason: "Admin bulk override";
}>;

export function BulkBar(props: {
  selectedCount: number;
  loading: boolean;

  // options
  platformOptions: PlatformDto[];
  roleOptions: string[];
  caliberOptions: CaliberDto[];

  // state
  bulkPlatformKey: string;
  setBulkPlatformKey: (v: string) => void;
  bulkPlatformLock: boolean;
  setBulkPlatformLock: (v: boolean) => void;

  bulkRole: string;
  setBulkRole: (v: string) => void;
  bulkRoleLock: boolean;
  setBulkRoleLock: (v: boolean) => void;

  bulkCaliber: string;
  setBulkCaliber: (v: string) => void;
  bulkCaliberGroup: string;
  setBulkCaliberGroup: (v: string) => void;
  bulkCaliberLock: boolean;
  setBulkCaliberLock: (v: boolean) => void;
  bulkForceCaliber: boolean;
  setBulkForceCaliber: (v: boolean) => void;

  // action
  runBulk: (set: BulkUpdateSet) => void;
}) {
  const {
    selectedCount,
    loading,
    platformOptions,
    roleOptions,
    caliberOptions,

    bulkPlatformKey,
    setBulkPlatformKey,
    bulkPlatformLock,
    setBulkPlatformLock,

    bulkRole,
    setBulkRole,
    bulkRoleLock,
    setBulkRoleLock,

    bulkCaliber,
    setBulkCaliber,
    bulkCaliberGroup,
    setBulkCaliberGroup,
    bulkCaliberLock,
    setBulkCaliberLock,
    bulkForceCaliber,
    setBulkForceCaliber,

    runBulk,
  } = props;

  const [open, setOpen] = useState(false);

  const disabled = loading || selectedCount <= 0;

  // one button to apply staged field updates
  const applyFieldChanges = useCallback(() => {
    const patch: BulkUpdateSet = { classificationReason: "Admin bulk override" };

    if (bulkPlatformKey) {
      patch.platform = bulkPlatformKey;
      if (bulkPlatformLock) patch.platformLocked = true;
    }

    if (bulkRole) {
      patch.partRole = bulkRole;
      patch.partRoleLocked = bulkRoleLock;
    }

    if (bulkCaliber) patch.caliber = bulkCaliber;
    if (bulkCaliberGroup.trim()) patch.caliberGroup = bulkCaliberGroup.trim();
    if (bulkCaliber || bulkCaliberGroup.trim()) {
      patch.caliberLocked = bulkCaliberLock;
      patch.forceCaliberUpdate = bulkForceCaliber;
    }

    // If user didn't stage anything, do nothing
    const keys = Object.keys(patch).filter((k) => k !== "classificationReason");
    if (keys.length === 0) return;

    runBulk(patch);
  }, [bulkPlatformKey, bulkPlatformLock, bulkRole, bulkRoleLock, bulkCaliber, bulkCaliberGroup, bulkCaliberLock, bulkForceCaliber, runBulk]);

  if (selectedCount <= 0) return null;

  let footer: JSX.Element;
  // eslint-disable-next-line react-hooks/rules-of-hooks
  footer = useMemo(() => {
    return (
        <div className="flex items-center justify-between gap-2">
          <div className="text-sm text-white/60">
            Selected: <span className="font-semibold text-white">{selectedCount}</span>
          </div>

          <button
              className="rounded-md bg-emerald-600 px-3 py-2 text-sm font-semibold hover:bg-emerald-500 disabled:opacity-50"
              disabled={disabled}
              onClick={() => {
                applyFieldChanges();
                setOpen(false);
              }}
          >
            Apply changes
          </button>
        </div>
    );
  }, [applyFieldChanges, disabled, selectedCount]);

  return (
    <>
      {/* Tiny inline bar */}
      <div className="mb-3 flex items-center justify-between rounded-md border border-zinc-800 bg-zinc-950/40 p-3">
        <div className="text-sm opacity-80">
          Selected: <span className="font-semibold">{selectedCount}</span>
        </div>

        <button
          className="rounded-md border border-zinc-700 px-3 py-2 text-sm hover:bg-zinc-900 disabled:opacity-50"
          disabled={loading}
          onClick={() => setOpen(true)}
        >
          Bulk actions
        </button>
      </div>

      {/* Drawer: all bulk controls */}
      <RightDrawer
        open={open}
        onClose={setOpen}
        title="Bulk actions"
        widthClassName="max-w-lg"
        footer={footer}
      >
        <div className="space-y-6">
          {/* Set fields */}
          <section className="rounded-lg border border-white/10 bg-white/5 p-4">
            <div className="mb-3 text-xs font-semibold uppercase tracking-wide text-white/60">
              Set fields
            </div>

            <div className="grid grid-cols-1 gap-3">
              {/* Platform */}
              <div className="grid gap-2">
                <label className="text-xs text-white/60">Platform</label>
                <div className="flex items-center gap-2">
                  <select
                    value={bulkPlatformKey}
                    onChange={(e) => setBulkPlatformKey(e.target.value)}
                    className="flex-1 rounded-md border border-zinc-700 bg-black px-3 py-2 text-sm"
                  >
                    <option value="">— No change —</option>
                    {platformOptions.map((p) => (
                      <option key={p.key} value={p.key}>
                        {p.label}
                      </option>
                    ))}
                  </select>

                  <label className="flex items-center gap-2 text-xs text-white/70">
                    <input
                      type="checkbox"
                      checked={bulkPlatformLock}
                      onChange={(e) => setBulkPlatformLock(e.target.checked)}
                    />
                    Lock
                  </label>
                </div>
              </div>

              {/* Role */}
              <div className="grid gap-2">
                <label className="text-xs text-white/60">Role</label>
                <div className="flex items-center gap-2">
                  <select
                    value={bulkRole}
                    onChange={(e) => setBulkRole(e.target.value)}
                    className="flex-1 rounded-md border border-zinc-700 bg-black px-3 py-2 text-sm"
                  >
                    <option value="">— No change —</option>
                    {roleOptions.filter(Boolean).map((r) => (
                      <option key={r} value={r}>
                        {r}
                      </option>
                    ))}
                  </select>

                  <label className="flex items-center gap-2 text-xs text-white/70">
                    <input
                      type="checkbox"
                      checked={bulkRoleLock}
                      onChange={(e) => setBulkRoleLock(e.target.checked)}
                    />
                    Lock
                  </label>
                </div>
              </div>

              {/* Caliber */}
              <div className="grid gap-2">
                <label className="text-xs text-white/60">Caliber</label>

                <select
                  value={bulkCaliber}
                  onChange={(e) => setBulkCaliber(e.target.value)}
                  className="w-full rounded-md border border-zinc-700 bg-black px-3 py-2 text-sm"
                >
                  <option value="">— No change —</option>
                  {caliberOptions
                    .filter((c) => Boolean(c && c.isActive && c.key))
                    .map((c) => (
                      <option key={c.id ?? c.key} value={c.key}>
                        {c.label || c.key}
                      </option>
                    ))}
                </select>

                <input
                  value={bulkCaliberGroup}
                  onChange={(e) => setBulkCaliberGroup(e.target.value)}
                  placeholder="Caliber group (optional)"
                  className="w-full rounded-md border border-zinc-700 bg-black px-3 py-2 text-sm"
                />

                <div className="flex flex-wrap items-center gap-4">
                  <label className="flex items-center gap-2 text-xs text-white/70">
                    <input
                      type="checkbox"
                      checked={bulkCaliberLock}
                      onChange={(e) => setBulkCaliberLock(e.target.checked)}
                    />
                    Lock caliber
                  </label>

                  <label className="flex items-center gap-2 text-xs text-white/70">
                    <input
                      type="checkbox"
                      checked={bulkForceCaliber}
                      onChange={(e) => setBulkForceCaliber(e.target.checked)}
                    />
                    Force update locked
                  </label>
                </div>
              </div>
            </div>

            <div className="mt-4 text-xs text-white/40">
              Tip: stage changes above, then use <span className="text-white/70">Apply changes</span>.
            </div>
          </section>

          {/* Quick actions */}
          <section className="rounded-lg border border-white/10 bg-white/5 p-4">
            <div className="mb-3 text-xs font-semibold uppercase tracking-wide text-white/60">
              Quick actions
            </div>

            <div className="flex flex-wrap gap-2">
              <button
                className="rounded-md border border-zinc-700 px-3 py-2 text-sm hover:bg-zinc-900 disabled:opacity-50"
                disabled={loading}
                onClick={() => runBulk({ builderEligible: false })}
              >
                Remove from Builder
              </button>

              <button
                className="rounded-md border border-zinc-700 px-3 py-2 text-sm hover:bg-zinc-900 disabled:opacity-50"
                disabled={loading}
                onClick={() => runBulk({ visibility: "HIDDEN" })}
              >
                Hide
              </button>

              <button
                className="rounded-md border border-zinc-700 px-3 py-2 text-sm hover:bg-zinc-900 disabled:opacity-50"
                disabled={loading}
                onClick={() => runBulk({ status: "DISABLED" })}
              >
                Disable
              </button>

              <button
                className="rounded-md border border-zinc-700 px-3 py-2 text-sm hover:bg-zinc-900 disabled:opacity-50"
                disabled={loading}
                onClick={() => runBulk({ adminLocked: true })}
              >
                Lock
              </button>

              <button
                className="rounded-md border border-zinc-700 px-3 py-2 text-sm hover:bg-zinc-900 disabled:opacity-50"
                disabled={loading}
                onClick={() => runBulk({ adminLocked: false })}
              >
                Unlock
              </button>
            </div>
          </section>

          {/* Danger zone */}
          <section className="rounded-lg border border-red-900/40 bg-red-950/20 p-4">
            <div className="mb-2 text-xs font-semibold uppercase tracking-wide text-red-200">
              Danger zone
            </div>

            <button
              className="rounded-md bg-red-600/80 px-3 py-2 text-sm font-semibold hover:bg-red-600 disabled:opacity-50"
              disabled={loading}
              onClick={() =>
                runBulk({
                  visibility: "HIDDEN",
                  builderEligible: false,
                  adminLocked: true,
                  adminNote: "Hidden + removed from builder (bulk)",
                })
              }
              title="Hides products, removes from builder, and locks editing"
            >
              Hide + Remove + Lock
            </button>
          </section>
        </div>
      </RightDrawer>
    </>
  );
}