/* eslint-disable */
"use client";

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

type VisibleCols = {
  brand: boolean;
  platform: boolean;
  role: boolean;
  caliber: boolean;
  import: boolean;
  flags: boolean;
  updated: boolean;
};

function countActiveFilters(draft: AdminFilters) {
  const entries: [string, any][] = [
    ["platform", draft.platform],
    ["partRole", draft.partRole],
    ["caliber", draft.caliber],
    ["visibility", draft.visibility],
    ["status", draft.status],
    ["builderEligible", draft.builderEligible],
    ["adminLocked", draft.adminLocked],
  ];
  return entries.filter(([, v]) => v !== "" && v != null).length;
}

export default function ProductsToolbar({
  draft,
  setDraft,
  platformOptions,
  roleOptions,
  caliberOptions,
  loading,
  onApply,
  onClear,
  selectedCount,
  visibleCols,
  setVisibleCols,
}: {
  draft: AdminFilters;
  setDraft: React.Dispatch<React.SetStateAction<AdminFilters>>;
  platformOptions: PlatformDto[];
  roleOptions: string[];
  caliberOptions: CaliberDto[];
  loading: boolean;
  onApply: () => void;
  onClear: () => void;
  selectedCount: number;

  // column toggles
  visibleCols: VisibleCols;
  setVisibleCols: React.Dispatch<React.SetStateAction<VisibleCols>>;
}) {
  const [open, setOpen] = useState(false);

  const activeCount = useMemo(() => countActiveFilters(draft), [draft]);

  return (
    <>
      {/* Top toolbar: stays small even on 14" */}
      <div className="mb-3 rounded-md border border-zinc-800 bg-zinc-950/40 p-3">
        <div className="flex flex-wrap items-end gap-2">
          <Field label="Search" widthClass="min-w-[280px] flex-1">
            <input
              value={draft.q}
              onChange={(e) => setDraft((s) => ({ ...s, q: e.target.value }))}
              placeholder="name, slug, mpn, upc…"
              className="w-full rounded-md border border-zinc-700 bg-black px-3 py-2 text-sm"
            />
          </Field>

          <button
            className="rounded-md border border-zinc-700 px-3 py-2 text-sm hover:bg-zinc-900"
            onClick={() => setOpen(true)}
            disabled={loading}
          >
            Filters{activeCount ? ` (${activeCount})` : ""}
          </button>

          <button
            className="rounded-md border border-zinc-700 px-3 py-2 text-sm hover:bg-zinc-900 disabled:opacity-50"
            disabled={selectedCount === 0 || loading}
            title={
              selectedCount === 0
                ? "Select rows to enable bulk actions"
                : undefined
            }
            onClick={() => setOpen(true)}
          >
            Bulk ({selectedCount})
          </button>

          <div className="ml-auto flex items-center gap-2">
            <button
              className="rounded-md bg-emerald-600 px-3 py-2 text-sm hover:bg-emerald-500 disabled:opacity-50"
              onClick={onApply}
              disabled={loading}
            >
              Refresh
            </button>
          </div>
        </div>
      </div>

      {/* Drawer: all the heavy controls */}
      <RightDrawer
        open={open}
        onClose={setOpen}
        title="Filters & Actions"
        widthClassName="max-w-lg"
        footer={
          <div className="flex items-center justify-between gap-2">
            <button
              className="rounded-md border border-zinc-700 px-3 py-2 text-sm hover:bg-zinc-900 disabled:opacity-50"
              onClick={onClear}
              disabled={loading}
            >
              Clear
            </button>

            <div className="flex items-center gap-2">
              <button
                className="rounded-md bg-emerald-600 px-3 py-2 text-sm hover:bg-emerald-500 disabled:opacity-50"
                onClick={() => {
                  onApply();
                  setOpen(false);
                }}
                disabled={loading}
              >
                Apply
              </button>
            </div>
          </div>
        }
      >
        <div className="space-y-6">
          {/* Filters */}
          <div className="text-xs uppercase tracking-wide text-white/50">
            Filters
          </div>

          <div className="grid grid-cols-1 gap-3">
            <Field label="Platform">
              <select
                value={draft.platform}
                onChange={(e) =>
                  setDraft((s) => ({ ...s, platform: e.target.value }))
                }
                className="w-full rounded-md border border-zinc-700 bg-black px-3 py-2 text-sm"
              >
                <option value="">Any</option>
                {platformOptions.map((p) => (
                  <option key={p.key} value={p.key}>
                    {p.label}
                  </option>
                ))}
              </select>
            </Field>

            <Field label="Role">
              <select
                value={draft.partRole}
                onChange={(e) =>
                  setDraft((s) => ({ ...s, partRole: e.target.value }))
                }
                className="w-full rounded-md border border-zinc-700 bg-black px-3 py-2 text-sm"
              >
                <option value="">Any</option>
                {roleOptions.map((r) => (
                  <option key={r || "any"} value={r}>
                    {r || "Any"}
                  </option>
                ))}
              </select>
            </Field>

            <Field label="Caliber">
              <select
                value={draft.caliber}
                onChange={(e) =>
                  setDraft((s) => ({ ...s, caliber: e.target.value }))
                }
                className="w-full rounded-md border border-zinc-700 bg-black px-3 py-2 text-sm"
              >
                <option value="">Any</option>
                <option value="__UNSET__">— Not set —</option>
                {caliberOptions
                  .filter((c) => !!c && !!c.key)
                  .map((c) => (
                    <option key={c.id ?? c.key} value={c.key}>
                      {c.label || c.key}
                    </option>
                  ))}
              </select>
            </Field>

            <Field label="Visibility">
              <select
                value={draft.visibility}
                onChange={(e) =>
                  setDraft((s) => ({
                    ...s,
                    visibility: e.target.value as any,
                  }))
                }
                className="w-full rounded-md border border-zinc-700 bg-black px-3 py-2 text-sm"
              >
                <option value="">Any</option>
                <option value="PUBLIC">PUBLIC</option>
                <option value="HIDDEN">HIDDEN</option>
              </select>
            </Field>

            <Field label="Status">
              <select
                value={draft.status}
                onChange={(e) =>
                  setDraft((s) => ({ ...s, status: e.target.value as any }))
                }
                className="w-full rounded-md border border-zinc-700 bg-black px-3 py-2 text-sm"
              >
                <option value="">Any</option>
                <option value="ACTIVE">ACTIVE</option>
                <option value="DISABLED">DISABLED</option>
                <option value="ARCHIVED">ARCHIVED</option>
              </select>
            </Field>

            <Field label="Builder">
              <select
                value={draft.builderEligible}
                onChange={(e) =>
                  setDraft((s) => ({
                    ...s,
                    builderEligible: e.target.value as any,
                  }))
                }
                className="w-full rounded-md border border-zinc-700 bg-black px-3 py-2 text-sm"
              >
                <option value="">Any</option>
                <option value="true">Eligible</option>
                <option value="false">Not eligible</option>
              </select>
            </Field>

            <Field label="Locked">
              <select
                value={draft.adminLocked}
                onChange={(e) =>
                  setDraft((s) => ({
                    ...s,
                    adminLocked: e.target.value as any,
                  }))
                }
                className="w-full rounded-md border border-zinc-700 bg-black px-3 py-2 text-sm"
              >
                <option value="">Any</option>
                <option value="true">Locked</option>
                <option value="false">Unlocked</option>
              </select>
            </Field>
          </div>

          {/* Columns */}
          <div className="pt-2">
            <div className="text-xs uppercase tracking-wide text-white/50">
              Columns
            </div>

            <div className="mt-2 rounded-lg border border-white/10 bg-white/5 p-4">
              {/* Presets */}
              <div className="mb-3 flex flex-wrap gap-2">
                <button
                  type="button"
                  className="rounded-md border border-zinc-700 px-2.5 py-1.5 text-xs hover:bg-zinc-900"
                  onClick={() =>
                    setVisibleCols({
                      brand: true,
                      platform: true,
                      role: true,
                      caliber: true,
                      import: true,
                      flags: true,
                      updated: true,
                    })
                  }
                >
                  Full
                </button>

                <button
                  type="button"
                  className="rounded-md border border-zinc-700 px-2.5 py-1.5 text-xs hover:bg-zinc-900"
                  onClick={() =>
                    setVisibleCols({
                      brand: true,
                      platform: true,
                      role: true,
                      caliber: true,
                      import: true,
                      flags: false,
                      updated: false,
                    })
                  }
                >
                  Compact
                </button>

                <button
                  type="button"
                  className="rounded-md border border-zinc-700 px-2.5 py-1.5 text-xs hover:bg-zinc-900"
                  onClick={() =>
                    setVisibleCols({
                      brand: false,
                      platform: true,
                      role: true,
                      caliber: true,
                      import: true,
                      flags: true,
                      updated: false,
                    })
                  }
                >
                  Review
                </button>
              </div>

              {/* Toggles */}
              <div className="grid grid-cols-2 gap-2 text-sm">
                <label className="flex items-center gap-2">
                  <input
                    type="checkbox"
                    checked={visibleCols.brand}
                    onChange={() =>
                      setVisibleCols((c) => ({ ...c, brand: !c.brand }))
                    }
                  />
                  Brand
                </label>

                <label className="flex items-center gap-2">
                  <input
                    type="checkbox"
                    checked={visibleCols.platform}
                    onChange={() =>
                      setVisibleCols((c) => ({
                        ...c,
                        platform: !c.platform,
                      }))
                    }
                  />
                  Platform
                </label>

                <label className="flex items-center gap-2">
                  <input
                    type="checkbox"
                    checked={visibleCols.role}
                    onChange={() =>
                      setVisibleCols((c) => ({ ...c, role: !c.role }))
                    }
                  />
                  Role
                </label>

                <label className="flex items-center gap-2">
                  <input
                    type="checkbox"
                    checked={visibleCols.caliber}
                    onChange={() =>
                      setVisibleCols((c) => ({ ...c, caliber: !c.caliber }))
                    }
                  />
                  Caliber
                </label>

                <label className="flex items-center gap-2">
                  <input
                    type="checkbox"
                    checked={visibleCols.import}
                    onChange={() =>
                      setVisibleCols((c) => ({ ...c, import: !c.import }))
                    }
                  />
                  Import
                </label>

                <label className="flex items-center gap-2">
                  <input
                    type="checkbox"
                    checked={visibleCols.flags}
                    onChange={() =>
                      setVisibleCols((c) => ({ ...c, flags: !c.flags }))
                    }
                  />
                  Flags
                </label>

                <label className="flex items-center gap-2">
                  <input
                    type="checkbox"
                    checked={visibleCols.updated}
                    onChange={() =>
                      setVisibleCols((c) => ({ ...c, updated: !c.updated }))
                    }
                  />
                  Updated
                </label>
              </div>

              <p className="mt-3 text-xs text-white/40">
                Product + checkbox are always shown.
              </p>
            </div>
          </div>

          {/* Bulk actions placeholder */}
          <div className="pt-2">
            <div className="text-xs uppercase tracking-wide text-white/50">
              Bulk actions
            </div>
            <div className="mt-2 rounded-md border border-zinc-800 bg-black/30 p-3 text-sm text-white/70">
              {selectedCount === 0
                ? "Select rows to enable bulk actions."
                : `Ready for bulk actions on ${selectedCount} selected item(s).`}
              <div className="mt-2 text-xs text-white/40">
                (Hook your actual bulk controls here next.)
              </div>
            </div>
          </div>
        </div>
      </RightDrawer>
    </>
  );
}