import { ReactNode } from 'react';
import clsx from 'clsx';
import { GroupBase, SingleValue } from 'react-select';
import Select from 'react-select';
import CircularTab from './CircularTab';
import IconSearch from './Icon/IconSearch';
import Flatpickr from 'react-flatpickr';
import 'flatpickr/dist/flatpickr.css';
import IconCalendar from './Icon/IconCalendar';

export type FilterConfig = {
  key: string;
  placeholder?: string;
  options: FilterOption[];
  value: FilterOption | null;
  onChange: (value: FilterOption | null) => void;
  icon?: ReactNode;
};

export type FilterOption = {
  label: string;
  value: string;
};

type Variant = 'filled' | 'outline' | 'ghost';
type Color = 'rose' | 'blue' | 'green' | 'slate';

export type TabConfig = {
  label: string;
  value: string;
  count?: number;
};


type Props = {
  /** Search input — omit `search` entirely to hide the search box */
  search?: {
    value: string;
    onChange: (value: string) => void;
    placeholder?: string;
  };
  /** Date range filter */
  dateRange?: {
    value: any;
    onChange: (date: any) => void;
    placeholder?: string;
  };
  /** Any number of dropdown filters — omit or pass [] to hide */
  filters?: FilterConfig[];
  /** Pill-style tabs (e.g. All / In Stock / Low Stock / Out of Stock) — omit to hide */
  tabs?: ReactNode;
  activeTab?: string;
  onTabChange?: (value: string) => void;
  /** Primary action button (e.g. "+ Add Product") — omit to hide */
  action?: ReactNode;
  /** Optional leading icon shown before the filters group */
  filterIcon?: ReactNode;
  className?: string;
};

const COLORS = {
  cream: "#FBF6ED",
  card: "#FFFFFF",
  line: "#ECE2D2",
  ink: "#3B2F28",
  sub: "#9C8C7C",
  burgundy: "#7A2E1D",
  gold: "#C9974A",
  goldSoft: "#F6E9D2",
};

const inputStyle: React.CSSProperties = {
  width: "100%", border: `1px solid ${COLORS.line}`, background: COLORS.cream,
  borderRadius: 10, padding: "10px 14px", fontSize: 14, color: COLORS.ink, outline: "none",
  boxSizing: "border-box",
};
const selectStyles = {
  control: (base: any, state: any) => ({
    ...base,
    transition: "all 0.2s ease",
    backgroundColor: "#FBF6ED",
    borderColor: state.isFocused ? "#CF8F42" : "#ECE2D2",
    boxShadow: state.isFocused
      ? "0 0 0 3px rgba(207, 143, 66, 0.15)"
      : "none",
    borderRadius: "10px",
    padding: "2px 6px",
    minHeight: "42px",
    fontSize: "14px",
    color: "#3B2F28",
    "&:hover": {
      borderColor: "#CF8F42",
    },
  }),
  valueContainer: (base: any) => ({
    ...base,
    padding: "2px 6px",
  }),

  input: (base: any) => ({
    ...base,
    color: "#3B2F28",
  }),

  placeholder: (base: any) => ({
    ...base,
    color: "#9A8F86",
    fontSize: "14px",
  }),

  singleValue: (base: any) => ({
    ...base,
    color: "#3B2F28",
    fontSize: "14px",
  }),

  menu: (base: any) => ({
    ...base,
    borderRadius: "10px",
    overflow: "hidden",
    marginTop: 6,
    zIndex: 9999,
    backgroundColor: "#ffffff",
    border: "1px solid #ECE2D2",
  }),
  menuPortal: (base: any) => ({  // ← add this entire block
    ...base,
    zIndex: 9999,
  }),

  option: (base: any, state: any) => ({
    ...base,
    fontSize: "14px",
    backgroundColor: state.isFocused
      ? "#FBF6ED"
      : state.isSelected
        ? "#F3E3C7"
        : "#fff",
    color: "#3B2F28",
    cursor: "pointer",
    zIndex: 9999,
  }),

  dropdownIndicator: (base: any) => ({
    ...base,
    color: "#3B2F28",
    "&:hover": {
      color: "#CF8F42",
    },
  }),

  indicatorSeparator: () => ({
    display: "none",
  }),
};
const Toolbar = ({
  search,
  dateRange,
  filters,
  tabs,
  activeTab,
  onTabChange,
  action,
  filterIcon,
  className,
}: Props) => {
  const hasFilters = filters && filters.length > 0;

  return (
    <div
      className={clsx(
        'flex flex-col gap-3 rounded-xl border border-slate-100 bg-white p-3.5 shadow-2xs',
        className
      )}
    >
      {/* Top Row: Search Box, Date Range, and Right-Aligned Actions */}
      <div className="flex flex-wrap lg:flex-nowrap items-center justify-between gap-3 w-full">
        {/* Left: Search Box & Date Range */}
        <div className="flex flex-wrap sm:flex-nowrap items-center gap-2.5 flex-1 min-w-[240px]">
          {search && (
            <div className="flex-1 min-w-[200px]" style={{ position: "relative" }}>
              <span style={{ position: "absolute", left: 14, top: "50%", transform: "translateY(-50%)", color: COLORS.sub }}>
                <IconSearch />
              </span>
              <input
                value={search.value}
                onChange={(e) => search.onChange(e.target.value)}
                placeholder={search.placeholder || "Search by name..."}
                style={{ ...inputStyle, paddingLeft: 38, background: COLORS.cream }}
              />
            </div>
          )}

          {dateRange && (
            <div className="w-full sm:w-56 shrink-0" style={{ position: "relative" }}>
              <span style={{ position: "absolute", left: 14, top: "50%", transform: "translateY(-50%)", color: COLORS.sub }}>
                <IconCalendar />
              </span>
              <Flatpickr
                options={{
                  mode: 'range',
                  dateFormat: 'Y-m-d',
                }}
                value={dateRange.value}
                className="w-full"
                style={{ ...inputStyle, paddingLeft: 38, background: COLORS.cream }}
                placeholder={dateRange.placeholder || "Select date range"}
                onChange={(date) => dateRange.onChange(date)}
              />
            </div>
          )}
        </div>

        {/* Right: Actions & Tabs (Right-aligned, never pushed off-screen) */}
        {(tabs || action) && (
          <div className="flex items-center gap-2 shrink-0 ml-auto">
            {tabs}
            {action}
          </div>
        )}
      </div>

      {/* Filter Row: Renders cleanly below without crowding search or action buttons */}
      {hasFilters && (
        <div className="flex flex-wrap items-center gap-2.5 pt-2 border-t border-slate-100/80 w-full">
          {filterIcon && <span className="text-slate-400 shrink-0">{filterIcon}</span>}
          {filters!.map((f) => (
            <div key={f.key} className="flex-1 min-w-[130px] max-w-[200px]">
              <Select
                value={f.value}
                onChange={(val) => f.onChange(val)}
                options={f.options}
                placeholder={f.placeholder ?? 'Select...'}
                isClearable
                classNamePrefix="react-select"
                menuPortalTarget={document.body}
                menuPosition="fixed"
                styles={selectStyles}
              />
            </div>
          ))}
        </div>
      )}
    </div>
  );
};

export default Toolbar;