"use client";

import React from "react";
import { Combobox } from "@headlessui/react";
import { CheckIcon, ChevronUpDownIcon } from "@heroicons/react/20/solid";
import { useRef, useState } from "react";

const PRIMARY_COLOR = "#428B4D";

// ─── Types ────────────────────────────────────────────────────────────────────

export interface TransactionOption {
  label: string;
  value: string;
}

interface TransactionTypeSelectProps<T extends string> {
  t_o_t: TransactionOption | null;
  sett_o_t: (value: TransactionOption | null) => void;
  staticOptions: TransactionOption[];
  clearError?: (field: T) => void;
  errors?: { t_o_t?: string };
  handleFieldBlur?: (field: T, validateField: (field: T) => string | undefined) => void;
  validateField?: (field: T) => string | undefined;
  isDisabled?: boolean;
}

// ─── Component ────────────────────────────────────────────────────────────────

const TransactionTypeSelect = <T extends string>({
  t_o_t,
  sett_o_t,
  staticOptions,
  clearError,
  errors,
  handleFieldBlur,
  validateField,
  isDisabled,
}: TransactionTypeSelectProps<T>) => {
  const [query, setQuery] = useState("");
  const buttonRef = useRef<HTMLButtonElement | null>(null);

  const filtered = query.trim()
    ? staticOptions.filter((o) =>
        o.label.toLowerCase().includes(query.trim().toLowerCase())
      )
    : staticOptions;

  const handleChange = (option: TransactionOption | null) => {
    sett_o_t(option);
    if (clearError) clearError("t_o_t" as T);
  };

  const handleBlur = () => {
    if (handleFieldBlur && validateField) {
      handleFieldBlur("t_o_t" as T, validateField);
    }
  };

  const error = errors?.t_o_t;

  const inputClasses = `w-full rounded-lg border ${
    error
      ? "border-red-400 focus:border-red-500 focus:ring-red-400/40"
      : "border-gray-200 hover:border-[#428B4D]/60 focus:border-[#428B4D]"
  } bg-white px-3 py-1.5 pr-10 text-sm leading-5 min-h-[2.25rem] transition-all duration-200 ease-in-out focus:outline-none focus:ring-1 focus:ring-[#428B4D]/15 placeholder:text-gray-400 disabled:bg-gray-100 disabled:text-gray-500 disabled:cursor-not-allowed disabled:hover:border-gray-200`;

  return (
    <div className="group flex items-end gap-2 transition-all duration-200 hover:shadow-md hover:shadow-[#428B4D]/10">
      <div className="flex-1 w-full">
        <label className="block mb-1 text-xs font-semibold uppercase tracking-wide text-gray-600">
          Type of Transaction
        </label>

        <Combobox
          value={t_o_t}
          onChange={handleChange}
          disabled={isDisabled}
          by="value"
        >
          {({ open }) => {
            const ensureOpen = () => {
              if (isDisabled) return;
              if (!open) buttonRef.current?.click();
            };

            return (
              <div className="relative group">
                <Combobox.Input
                  className={inputClasses}
                  displayValue={(opt: TransactionOption | null) => opt?.label || ""}
                  onChange={(e) => setQuery(e.target.value)}
                  onFocus={(e) => {
                    ensureOpen();
                    if (!error) {
                      e.currentTarget.style.borderColor = PRIMARY_COLOR;
                      e.currentTarget.style.boxShadow = `0 0 0 1px ${PRIMARY_COLOR}15`;
                    }
                  }}
                  onClick={ensureOpen}
                  placeholder="Select transaction type..."
                  onBlur={(e) => {
                    handleBlur();
                    if (!error) {
                      e.currentTarget.style.borderColor = "";
                      e.currentTarget.style.boxShadow = "";
                    }
                  }}
                  onMouseEnter={(e) => {
                    if (!error && document.activeElement !== e.currentTarget && !e.currentTarget.disabled) {
                      e.currentTarget.style.borderColor = `${PRIMARY_COLOR}99`;
                    }
                  }}
                  onMouseLeave={(e) => {
                    if (!error && document.activeElement !== e.currentTarget) {
                      e.currentTarget.style.borderColor = "";
                    }
                  }}
                />

                <Combobox.Button
                  ref={buttonRef}
                  disabled={isDisabled}
                  className="absolute inset-y-0 right-0 flex items-center px-2 text-gray-400 transition-all duration-200 rounded-r-lg hover:bg-[#428B4D]/5"
                  style={{ color: "rgb(156, 163, 175)" }}
                  onMouseEnter={(e) => { e.currentTarget.style.color = PRIMARY_COLOR; }}
                  onMouseLeave={(e) => { e.currentTarget.style.color = ""; }}
                >
                  <ChevronUpDownIcon className="h-4 w-4 transition-transform duration-200 group-hover:scale-110" />
                </Combobox.Button>

                <Combobox.Options className="absolute mt-1 w-full max-h-60 overflow-auto rounded-lg bg-white border border-gray-200 text-sm focus:outline-none shadow-lg z-50">
                  {filtered.length === 0 ? (
                    <div className="cursor-default select-none px-4 py-2 text-sm text-gray-500">
                      No results found.
                    </div>
                  ) : (
                    filtered.map((opt) => (
                      <Combobox.Option
                        key={opt.value}
                        value={opt}
                        className={({ active }) =>
                          `relative cursor-pointer select-none py-2 pl-8 pr-3 transition-colors duration-150 ${
                            active ? "text-slate-900" : "text-gray-900 hover:bg-gray-50"
                          }`
                        }
                      >
                        {({ selected, active }) => (
                          <>
                            <span
                              className="absolute inset-0"
                              style={{ backgroundColor: active ? `${PRIMARY_COLOR}18` : undefined }}
                            />
                            <span className={`relative block truncate ${selected ? "font-semibold" : "font-normal"}`}>
                              {opt.label}
                            </span>
                            {selected && (
                              <span
                                className="absolute inset-y-0 left-0 flex items-center pl-2.5"
                                style={{ color: PRIMARY_COLOR }}
                              >
                                <CheckIcon className="h-4 w-4" />
                              </span>
                            )}
                          </>
                        )}
                      </Combobox.Option>
                    ))
                  )}
                </Combobox.Options>
              </div>
            );
          }}
        </Combobox>

        {error && <p className="mt-1 text-sm text-red-500">{error}</p>}
      </div>
    </div>
  );
};

export default TransactionTypeSelect;