"use client";

import React, { useState, useRef, useEffect } from "react";
import { X, Plus, ChevronDown, Check } from "lucide-react";
import { getEpcColorClass } from "@/app/utils";
import {
  FilterGroups,
  FilterGroup,
  PropertyFilter,
  FilterField,
  FilterOperator,
  DatePreset,
  EnumOption,
  PROPERTY_TYPE_OPTIONS,
  BUILT_FORM_OPTIONS,
  TENURE_OPTIONS,
  YEAR_BUILT_OPTIONS,
  MAINFUEL_OPTIONS,
} from "@/app/utils/propertyFilters";

/* -----------------------------------------------------------------------
   Constants
------------------------------------------------------------------------ */
const EPC_LETTERS = ["A", "B", "C", "D", "E", "F", "G"] as const;
type EpcLetter = (typeof EPC_LETTERS)[number];

const FIELD_OPTIONS: { value: FilterField; label: string }[] = [
  { value: "currentEpc",    label: "Current EPC" },
  { value: "lodgedEpc",     label: "Lodged EPC" },
  { value: "expectedEpc",   label: "Expected EPC" },
  { value: "epcExpiryDate", label: "EPC Expiry Date" },
  { value: "propertyType",  label: "Property Type" },
  { value: "builtForm",     label: "Built Form" },
  { value: "tenure",        label: "Tenure" },
  { value: "yearBuilt",     label: "Year Built" },
  { value: "floorArea",     label: "Floor Area (m²)" },
  { value: "co2Emissions",  label: "CO₂ Emissions (kg/m²/yr)" },
  { value: "mainfuel",      label: "Main Fuel" },
];

const EPC_OPERATOR_OPTIONS: { value: FilterOperator; label: string }[] = [
  { value: "epc_less_than",    label: "is worse than" },
  { value: "equals",           label: "equals" },
  { value: "epc_greater_than", label: "is better than" },
  { value: "epc_one_of",       label: "is one of" },
];

const DATE_OPERATOR_OPTIONS: { value: FilterOperator; label: string }[] = [
  { value: "date_before", label: "is before" },
  { value: "date_after",  label: "is after" },
  { value: "date_equals", label: "is on" },
  { value: "date_preset", label: "preset" },
];

const DATE_PRESET_OPTIONS: { value: DatePreset; label: string }[] = [
  { value: "expired",               label: "Already expired" },
  { value: "expires_this_year",     label: "Expiring this year" },
  { value: "expires_within_1_year", label: "Expiring within 1 year" },
  { value: "expires_within_2_years",label: "Expiring within 2 years" },
];

const ENUM_OPERATOR_OPTIONS: { value: FilterOperator; label: string }[] = [
  { value: "enum_one_of", label: "is one of" },
];

const NUM_OPERATOR_OPTIONS: { value: FilterOperator; label: string }[] = [
  { value: "num_gte",    label: "≥ (at least)" },
  { value: "num_lte",    label: "≤ (at most)" },
  { value: "num_equals", label: "= (equals)" },
];

const ENUM_FIELD_OPTIONS: Record<string, EnumOption[]> = {
  propertyType: PROPERTY_TYPE_OPTIONS,
  builtForm:    BUILT_FORM_OPTIONS,
  tenure:       TENURE_OPTIONS,
  yearBuilt:    YEAR_BUILT_OPTIONS,
  mainfuel:     MAINFUEL_OPTIONS,
};

/* -----------------------------------------------------------------------
   Helpers
------------------------------------------------------------------------ */
function isEpcField(field: FilterField) {
  return field === "currentEpc" || field === "lodgedEpc" || field === "expectedEpc";
}

function isEnumField(field: FilterField): boolean {
  return field in ENUM_FIELD_OPTIONS;
}

function isNumericField(field: FilterField) {
  return field === "floorArea" || field === "co2Emissions";
}

function operatorsForField(field: FilterField): { value: FilterOperator; label: string }[] {
  if (isEpcField(field)) return EPC_OPERATOR_OPTIONS;
  if (field === "epcExpiryDate") return DATE_OPERATOR_OPTIONS;
  if (isEnumField(field)) return ENUM_OPERATOR_OPTIONS;
  if (isNumericField(field)) return NUM_OPERATOR_OPTIONS;
  return [];
}

function defaultOperatorForField(field: FilterField): FilterOperator {
  return operatorsForField(field)[0]?.value ?? "equals";
}

function conditionLabel(condition: PropertyFilter): string {
  const fieldLabel = FIELD_OPTIONS.find((f) => f.value === condition.field)?.label ?? condition.field;

  if (isEpcField(condition.field)) {
    const opLabel = EPC_OPERATOR_OPTIONS.find((o) => o.value === condition.operator)?.label ?? condition.operator;
    const value =
      condition.operator === "epc_one_of"
        ? condition.value.split(",").join(", ")
        : condition.value;
    return `${fieldLabel} ${opLabel} ${value}`;
  }

  if (condition.field === "epcExpiryDate") {
    if (condition.operator === "date_preset") {
      const presetLabel = DATE_PRESET_OPTIONS.find((p) => p.value === condition.value)?.label ?? condition.value;
      return `${fieldLabel}: ${presetLabel}`;
    }
    const opLabel = DATE_OPERATOR_OPTIONS.find((o) => o.value === condition.operator)?.label ?? condition.operator;
    return `${fieldLabel} ${opLabel} ${condition.value}`;
  }

  if (isEnumField(condition.field) && condition.operator === "enum_one_of") {
    try {
      const labels: string[] = JSON.parse(condition.value);
      return `${fieldLabel} is one of: ${labels.join(", ")}`;
    } catch {
      return `${fieldLabel} is one of: ${condition.value}`;
    }
  }

  if (isNumericField(condition.field)) {
    const opLabel = NUM_OPERATOR_OPTIONS.find((o) => o.value === condition.operator)?.label ?? condition.operator;
    return `${fieldLabel} ${opLabel} ${condition.value}`;
  }

  return `${fieldLabel} ${condition.operator} ${condition.value}`;
}

/* -----------------------------------------------------------------------
   EPC Dropdown (single + multi)
------------------------------------------------------------------------ */
function EpcDropdown({
  multi,
  selected,
  onChange,
}: {
  multi: boolean;
  selected: string[];
  onChange: (letters: string[]) => void;
}) {
  const [open, setOpen] = useState(false);
  const [dropdownStyle, setDropdownStyle] = useState<React.CSSProperties>({});
  const ref = useRef<HTMLDivElement>(null);
  const buttonRef = useRef<HTMLButtonElement>(null);

  const dropdownRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    function handleOutside(e: MouseEvent) {
      if (ref.current && !ref.current.contains(e.target as Node)) {
        setOpen(false);
      }
    }
    function handleScroll(e: Event) {
      if (dropdownRef.current && dropdownRef.current.contains(e.target as Node)) return;
      setOpen(false);
    }
    if (open) {
      document.addEventListener("mousedown", handleOutside);
      window.addEventListener("scroll", handleScroll, true);
    }
    return () => {
      document.removeEventListener("mousedown", handleOutside);
      window.removeEventListener("scroll", handleScroll, true);
    };
  }, [open]);

  function openDropdown() {
    if (buttonRef.current) {
      const rect = buttonRef.current.getBoundingClientRect();
      setDropdownStyle({
        position: "fixed",
        top: rect.bottom + 4,
        left: rect.left,
        width: rect.width,
        zIndex: 9999,
      });
    }
    setOpen((o) => !o);
  }

  function toggle(letter: string) {
    if (multi) {
      onChange(
        selected.includes(letter)
          ? selected.filter((l) => l !== letter)
          : [...selected, letter]
      );
    } else {
      onChange(selected[0] === letter ? [] : [letter]);
      setOpen(false);
    }
  }

  return (
    <div className="relative" ref={ref}>
      <button
        ref={buttonRef}
        type="button"
        onClick={openDropdown}
        className="w-full flex items-center justify-between rounded-md border border-gray-300 px-2 py-1.5 text-sm bg-white hover:border-gray-400 focus:outline-none focus:ring-2 focus:ring-black/10 transition"
      >
        <span className="flex items-center gap-1 flex-wrap min-h-[1.25rem]">
          {selected.length === 0 ? (
            <span className="text-gray-400">Select rating…</span>
          ) : (
            selected.map((l) => (
              <span
                key={l}
                className={`inline-flex items-center justify-center w-5 h-5 rounded-full text-[11px] font-bold text-white ${getEpcColorClass(l)}`}
              >
                {l}
              </span>
            ))
          )}
        </span>
        <ChevronDown className={`h-4 w-4 text-gray-400 shrink-0 ml-1 transition-transform ${open ? "rotate-180" : ""}`} />
      </button>

      {open && (
        <div ref={dropdownRef} style={dropdownStyle} className="rounded-md border border-gray-200 bg-white shadow-lg py-1">
          {EPC_LETTERS.map((l) => {
            const isSelected = selected.includes(l);
            return (
              <button
                key={l}
                type="button"
                onClick={() => toggle(l)}
                className={`w-full flex items-center gap-2.5 px-3 py-1.5 text-sm transition hover:bg-gray-50 ${isSelected ? "bg-gray-50" : ""}`}
              >
                <span
                  className={`inline-flex items-center justify-center w-6 h-6 rounded-full text-xs font-bold text-white shrink-0 ${getEpcColorClass(l)}`}
                >
                  {l}
                </span>
                <span className="text-gray-700">Rating {l}</span>
                {multi ? (
                  <span
                    className={`ml-auto w-4 h-4 rounded border flex items-center justify-center shrink-0 transition ${
                      isSelected ? "bg-black border-black" : "border-gray-300"
                    }`}
                  >
                    {isSelected && <Check className="h-2.5 w-2.5 text-white" />}
                  </span>
                ) : (
                  isSelected && <Check className="ml-auto h-3.5 w-3.5 text-gray-600" />
                )}
              </button>
            );
          })}
        </div>
      )}
    </div>
  );
}

/* -----------------------------------------------------------------------
   Enum Multi-Select Dropdown
------------------------------------------------------------------------ */
function EnumMultiDropdown({
  options,
  selectedLabels,
  onChange,
}: {
  options: EnumOption[];
  selectedLabels: string[];
  onChange: (labels: string[]) => void;
}) {
  const [open, setOpen] = useState(false);
  const [dropdownStyle, setDropdownStyle] = useState<React.CSSProperties>({});
  const ref = useRef<HTMLDivElement>(null);
  const buttonRef = useRef<HTMLButtonElement>(null);
  const dropdownRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    function handleOutside(e: MouseEvent) {
      if (ref.current && !ref.current.contains(e.target as Node)) {
        setOpen(false);
      }
    }
    function handleScroll(e: Event) {
      if (dropdownRef.current && dropdownRef.current.contains(e.target as Node)) return;
      setOpen(false);
    }
    if (open) {
      document.addEventListener("mousedown", handleOutside);
      window.addEventListener("scroll", handleScroll, true);
    }
    return () => {
      document.removeEventListener("mousedown", handleOutside);
      window.removeEventListener("scroll", handleScroll, true);
    };
  }, [open]);

  function openDropdown() {
    if (buttonRef.current) {
      const rect = buttonRef.current.getBoundingClientRect();
      setDropdownStyle({
        position: "fixed",
        top: rect.bottom + 4,
        left: rect.left,
        width: Math.max(rect.width, 220),
        zIndex: 9999,
        maxHeight: 280,
        overflowY: "auto",
      });
    }
    setOpen((o) => !o);
  }

  function toggle(label: string) {
    onChange(
      selectedLabels.includes(label)
        ? selectedLabels.filter((l) => l !== label)
        : [...selectedLabels, label]
    );
  }

  return (
    <div className="relative" ref={ref}>
      <button
        ref={buttonRef}
        type="button"
        onClick={openDropdown}
        className="w-full flex items-center justify-between rounded-md border border-gray-300 px-2 py-1.5 text-sm bg-white hover:border-gray-400 focus:outline-none focus:ring-2 focus:ring-black/10 transition"
      >
        <span className="flex items-center gap-1 flex-wrap min-h-[1.25rem] text-left">
          {selectedLabels.length === 0 ? (
            <span className="text-gray-400">Select options…</span>
          ) : (
            <span className="text-gray-700 truncate">{selectedLabels.join(", ")}</span>
          )}
        </span>
        <ChevronDown className={`h-4 w-4 text-gray-400 shrink-0 ml-1 transition-transform ${open ? "rotate-180" : ""}`} />
      </button>

      {open && (
        <div ref={dropdownRef} style={dropdownStyle} className="rounded-md border border-gray-200 bg-white shadow-lg py-1">
          {options.map((opt) => {
            const isSelected = selectedLabels.includes(opt.label);
            return (
              <button
                key={opt.label}
                type="button"
                onClick={() => toggle(opt.label)}
                className={`w-full flex items-center gap-2.5 px-3 py-1.5 text-sm transition hover:bg-gray-50 text-left ${isSelected ? "bg-gray-50" : ""}`}
              >
                <span className="flex-1 text-gray-700 leading-tight">{opt.label}</span>
                <span
                  className={`ml-auto w-4 h-4 rounded border flex items-center justify-center shrink-0 transition ${
                    isSelected ? "bg-black border-black" : "border-gray-300"
                  }`}
                >
                  {isSelected && <Check className="h-2.5 w-2.5 text-white" />}
                </span>
              </button>
            );
          })}
        </div>
      )}
    </div>
  );
}

/* -----------------------------------------------------------------------
   Number Filter Input
------------------------------------------------------------------------ */
function NumberFilterInput({
  value,
  onChange,
}: {
  value: string;
  onChange: (v: string) => void;
}) {
  return (
    <input
      type="number"
      className="w-full rounded-md border border-gray-300 px-2 py-1.5 text-sm bg-white focus:outline-none focus:ring-2 focus:ring-black/10"
      placeholder="Enter value…"
      value={value}
      onChange={(e) => onChange(e.target.value)}
    />
  );
}

/* -----------------------------------------------------------------------
   Add Filter Form
------------------------------------------------------------------------ */
interface AddFilterFormProps {
  targetGroupId: string | null; // null = new group
  onConfirm: (groupId: string | null, condition: PropertyFilter) => void;
  onCancel: () => void;
}

function AddFilterForm({ targetGroupId, onConfirm, onCancel }: AddFilterFormProps) {
  const [field, setField] = useState<FilterField>("currentEpc");
  const [operator, setOperator] = useState<FilterOperator>("epc_less_than");
  const [epcSelected, setEpcSelected] = useState<string[]>([]);
  const [dateValue, setDateValue] = useState("");
  const [preset, setPreset] = useState<DatePreset>("expired");
  const [enumSelected, setEnumSelected] = useState<string[]>([]);
  const [numValue, setNumValue] = useState("");

  function handleFieldChange(newField: FilterField) {
    setField(newField);
    setOperator(defaultOperatorForField(newField));
    setEpcSelected([]);
    setDateValue("");
    setEnumSelected([]);
    setNumValue("");
  }

  function buildValue(): string {
    if (isEpcField(field)) {
      return operator === "epc_one_of" ? epcSelected.join(",") : epcSelected[0] ?? "";
    }
    if (field === "epcExpiryDate") {
      return operator === "date_preset" ? preset : dateValue;
    }
    if (isEnumField(field)) {
      return enumSelected.length > 0 ? JSON.stringify(enumSelected) : "";
    }
    if (isNumericField(field)) {
      return numValue;
    }
    return "";
  }

  function canConfirm(): boolean {
    return buildValue().length > 0;
  }

  function handleConfirm() {
    const value = buildValue();
    if (!value) return;
    const condition: PropertyFilter = {
      id: crypto.randomUUID(),
      field,
      operator,
      value,
    };
    onConfirm(targetGroupId, condition);
  }

  const selectClass =
    "w-full rounded-md border border-gray-300 px-2 py-1.5 text-sm bg-white focus:outline-none focus:ring-2 focus:ring-black/10";

  const enumOptions = isEnumField(field) ? ENUM_FIELD_OPTIONS[field] : [];

  return (
    <div className="flex flex-col gap-2 p-3 bg-gray-50 rounded-md border border-gray-200">
      {/* Field */}
      <div>
        <label className="block text-xs font-medium text-gray-500 mb-0.5">Field</label>
        <select
          className={selectClass}
          value={field}
          onChange={(e) => handleFieldChange(e.target.value as FilterField)}
        >
          {FIELD_OPTIONS.map((f) => (
            <option key={f.value} value={f.value}>{f.label}</option>
          ))}
        </select>
      </div>

      {/* Operator */}
      <div>
        <label className="block text-xs font-medium text-gray-500 mb-0.5">Condition</label>
        <select
          className={selectClass}
          value={operator}
          onChange={(e) => setOperator(e.target.value as FilterOperator)}
        >
          {operatorsForField(field).map((o) => (
            <option key={o.value} value={o.value}>{o.label}</option>
          ))}
        </select>
      </div>

      {/* Value */}
      <div>
        <label className="block text-xs font-medium text-gray-500 mb-1">Value</label>

        {isEpcField(field) && (
          <EpcDropdown
            multi={operator === "epc_one_of"}
            selected={epcSelected}
            onChange={setEpcSelected}
          />
        )}

        {field === "epcExpiryDate" && operator === "date_preset" && (
          <select
            className={selectClass}
            value={preset}
            onChange={(e) => setPreset(e.target.value as DatePreset)}
          >
            {DATE_PRESET_OPTIONS.map((p) => (
              <option key={p.value} value={p.value}>{p.label}</option>
            ))}
          </select>
        )}

        {field === "epcExpiryDate" && operator !== "date_preset" && (
          <input
            type="date"
            className="w-full rounded-md border border-gray-300 px-2 py-1.5 text-sm bg-white focus:outline-none focus:ring-2 focus:ring-black/10"
            value={dateValue}
            onChange={(e) => setDateValue(e.target.value)}
          />
        )}

        {isEnumField(field) && (
          <EnumMultiDropdown
            options={enumOptions}
            selectedLabels={enumSelected}
            onChange={setEnumSelected}
          />
        )}

        {isNumericField(field) && (
          <NumberFilterInput value={numValue} onChange={setNumValue} />
        )}
      </div>

      {/* Actions */}
      <div className="flex gap-2 pt-1">
        <button
          type="button"
          onClick={handleConfirm}
          disabled={!canConfirm()}
          className="flex-1 h-8 rounded-md bg-black text-xs font-medium text-white hover:bg-black/90 transition disabled:opacity-40 disabled:cursor-not-allowed"
        >
          Add
        </button>
        <button
          type="button"
          onClick={onCancel}
          className="h-8 px-3 text-xs text-gray-500 hover:text-gray-700"
        >
          Cancel
        </button>
      </div>
    </div>
  );
}

/* -----------------------------------------------------------------------
   Condition Row
------------------------------------------------------------------------ */
function ConditionRow({
  condition,
  onRemove,
}: {
  condition: PropertyFilter;
  onRemove: () => void;
}) {
  return (
    <div className="flex items-start gap-1 group">
      <div className="flex-1 text-xs text-gray-700 bg-white border border-gray-200 rounded px-2 py-1.5 leading-tight break-words min-w-0">
        {conditionLabel(condition)}
      </div>
      <button
        type="button"
        onClick={onRemove}
        className="shrink-0 mt-0.5 p-0.5 rounded text-gray-400 hover:text-gray-700 hover:bg-gray-100 transition"
        title="Remove condition"
      >
        <X className="h-3.5 w-3.5" />
      </button>
    </div>
  );
}

/* -----------------------------------------------------------------------
   Main Component
------------------------------------------------------------------------ */
export default function PropertyFilters({
  filterGroups,
  onChange,
}: {
  filterGroups: FilterGroups;
  onChange: (groups: FilterGroups) => void;
}) {
  // Draft state — only applied when user clicks Apply
  const [draft, setDraft] = useState<FilterGroups>(filterGroups);
  // "or" = new OR group, "and:<groupId>" = AND condition into existing group, null = hidden
  const [addMode, setAddMode] = useState<"or" | `and:${string}` | null>(null);

  function openOrGroup() {
    setAddMode("or");
  }

  function openAndCondition(groupId: string) {
    setAddMode(`and:${groupId}`);
  }

  function handleConfirm(groupId: string | null, condition: PropertyFilter) {
    setDraft((prev) => {
      if (groupId === null) {
        // New OR group
        const newGroup: FilterGroup = {
          id: crypto.randomUUID(),
          conditions: [condition],
        };
        return [...prev, newGroup];
      } else {
        // Add AND-condition to existing group
        return prev.map((g) =>
          g.id === groupId
            ? { ...g, conditions: [...g.conditions, condition] }
            : g
        );
      }
    });
    setAddMode(null);
  }

  function removeCondition(groupId: string, conditionId: string) {
    setDraft((prev) => {
      const updated = prev
        .map((g) =>
          g.id === groupId
            ? { ...g, conditions: g.conditions.filter((c) => c.id !== conditionId) }
            : g
        )
        .filter((g) => g.conditions.length > 0);
      return updated;
    });
  }

  function apply() {
    onChange(draft);
  }

  function clear() {
    setDraft([]);
    onChange([]);
  }

  const hasGroups = draft.length > 0;

  return (
    <div className="flex flex-col gap-3 p-3">
      {/* Group list */}
      {draft.map((group, groupIdx) => {
        const isAndTarget = addMode === `and:${group.id}`;
        return (
          <div key={group.id}>
            {/* OR divider between groups */}
            {groupIdx > 0 && (
              <div className="flex items-center gap-2 mb-2">
                <div className="flex-1 border-t border-blue-200" />
                <span className="text-[10px] font-bold text-blue-500 uppercase tracking-wide bg-blue-50 px-1.5 py-0.5 rounded border border-blue-200">
                  OR
                </span>
                <div className="flex-1 border-t border-blue-200" />
              </div>
            )}

            <div className="flex flex-col gap-1.5 bg-white border border-gray-200 rounded-md p-2">
              {group.conditions.map((condition, condIdx) => (
                <div key={condition.id}>
                  {/* AND label between conditions in same group */}
                  {condIdx > 0 && (
                    <div className="flex items-center gap-2 my-1">
                      <div className="flex-1 border-t border-dashed border-gray-300" />
                      <span className="text-[10px] font-bold text-gray-500 uppercase tracking-wide bg-white px-1.5 py-0.5 rounded border border-gray-300">
                        AND
                      </span>
                      <div className="flex-1 border-t border-dashed border-gray-300" />
                    </div>
                  )}
                  <ConditionRow
                    condition={condition}
                    onRemove={() => removeCondition(group.id, condition.id)}
                  />
                </div>
              ))}

              {/* AND form inline */}
              {isAndTarget ? (
                <AddFilterForm
                  targetGroupId={group.id}
                  onConfirm={handleConfirm}
                  onCancel={() => setAddMode(null)}
                />
              ) : (
                <button
                  type="button"
                  onClick={() => openAndCondition(group.id)}
                  className="self-start mt-1 flex items-center gap-1 text-[11px] font-semibold text-gray-500 hover:text-gray-700 bg-white hover:bg-gray-50 border border-gray-300 rounded px-2 py-0.5 transition"
                >
                  <Plus className="h-3 w-3" />
                  AND
                </button>
              )}
            </div>
          </div>
        );
      })}

      {/* OR: add new group form or button */}
      {addMode === "or" ? (
        <AddFilterForm
          targetGroupId={null}
          onConfirm={handleConfirm}
          onCancel={() => setAddMode(null)}
        />
      ) : (
        <div className={hasGroups ? "flex items-center gap-2" : undefined}>
          {hasGroups && (
            <>
              <div className="flex-1 border-t border-blue-200" />
              <span className="text-[10px] font-bold text-blue-400 uppercase tracking-wide px-1">
                or
              </span>
              <div className="flex-1 border-t border-blue-200" />
            </>
          )}
          <button
            type="button"
            onClick={openOrGroup}
            className={[
              "flex items-center gap-1 text-sm font-semibold transition",
              hasGroups
                ? "shrink-0 text-blue-500 hover:text-blue-700 bg-blue-50 border border-blue-200 rounded px-2 py-0.5 text-[11px] hover:border-blue-400"
                : "w-full justify-center text-gray-600 hover:text-gray-900 border border-dashed border-gray-300 rounded-md px-3 py-2 hover:border-gray-400",
            ].join(" ")}
          >
            <Plus className="h-3.5 w-3.5" />
            {hasGroups ? "OR" : "Add filter"}
          </button>
        </div>
      )}

      {/* Apply / Clear */}
      <div className="flex gap-2 pt-1 border-t border-gray-100">
        <button
          type="button"
          onClick={apply}
          className="flex-1 h-9 rounded-md bg-black text-sm font-medium text-white hover:bg-black/90 transition"
        >
          Apply
        </button>
        <button
          type="button"
          onClick={clear}
          className="h-9 px-3 text-sm text-gray-500 hover:text-gray-700"
        >
          Clear
        </button>
      </div>
    </div>
  );
}
