"use client";

import React, { useMemo, RefObject } from "react";
import Link from "next/link";
import Select, { SingleValue, StylesConfig } from "react-select";
import {
  propertyTypeOptions,
  locationOptions,
  unitSizeOptions,
  propertyStatusOptions,
} from "./constants";

interface SelectOption {
  value: string;
  label: string;
}

interface SearchSelectProps {
  label: string;
  name: string;
  value: string;
  onChange: (name: string, value: string) => void;
  options: SelectOption[];
  placeholder?: string;
  className?: string;
}

// Custom SearchSelect component with #F5F5F5 background
const SearchSelect = ({
  label,
  name,
  value,
  onChange,
  options,
  placeholder = "All",
  className = "",
}: SearchSelectProps) => {
  const customStyles: StylesConfig<SelectOption, false> = useMemo(
    () => ({
      control: (provided) => ({
        ...provided,
        minHeight: "auto",
        height: "auto",
        border: "none",
        boxShadow: "none",
        backgroundColor: "transparent",
        cursor: "pointer",
        overflow: "visible",
        paddingRight: "0",
        "&:hover": {
          border: "none",
        },
      }),
      valueContainer: (provided) => ({
        ...provided,
        padding: "0",
        paddingRight: "4px",
        fontFamily: "CreatoDisplay, sans-serif",
        fontSize: "16px",
        fontWeight: "normal",
        color: "#28241E",
        lineHeight: "1",
      }),
      input: (provided) => ({
        ...provided,
        margin: "0",
        padding: "0",
        fontFamily: "CreatoDisplay, sans-serif",
        fontSize: "16px",
        fontWeight: "normal",
        color: "#28241E",
      }),
      placeholder: (provided) => ({
        ...provided,
        margin: "0",
        fontFamily: "CreatoDisplay, sans-serif",
        fontSize: "16px",
        fontWeight: "normal",
        color: "#28241E",
      }),
      singleValue: (provided) => ({
        ...provided,
        margin: "0",
        fontFamily: "CreatoDisplay, sans-serif",
        fontSize: "16px",
        fontWeight: "normal",
        color: "#28241E",
      }),
      indicatorSeparator: () => ({
        display: "none",
      }),
      dropdownIndicator: (provided) => ({
        ...provided,
        padding: "0 4px",
        color: "#28241E",
        display: "flex",
        alignItems: "center",
        "&:hover": {
          color: "#28241E",
        },
      }),
      indicatorsContainer: (provided) => ({
        ...provided,
        padding: "0",
        paddingLeft: "0px",
        marginRight: "50px",
        display: "flex",
        alignItems: "center",
        justifyContent: "center",
        minWidth: "28px",
        flexShrink: 0,
      }),
      menu: (provided) => ({
        ...provided,
        backgroundColor: "#F5F5F5",
        border: "none",
        borderRadius: "0",
        boxShadow: "0 4px 6px -1px rgba(0, 0, 0, 0.1)",
        marginTop: "4px",
        zIndex: 9999,
      }),
      menuPortal: (provided) => ({
        ...provided,
        zIndex: 9999,
      }),
      menuList: (provided) => ({
        ...provided,
        padding: "0",
        maxHeight: "200px",
      }),
      option: (provided, state) => ({
        ...provided,
        backgroundColor: state.isSelected
          ? "#E8E8E8"
          : state.isFocused
          ? "#EBEBEB"
          : "#F5F5F5",
        color: "#28241E",
        fontFamily: "CreatoDisplay, sans-serif",
        fontSize: "16px",
        fontWeight: "normal",
        padding: "8px 12px",
        cursor: "pointer",
        "&:hover": {
          backgroundColor: "#EBEBEB",
        },
      }),
    }),
    []
  );

  const selectedOption = useMemo(
    () => options.find((option) => option.value === value) || null,
    [options, value]
  );

  const handleChange = (selected: SingleValue<SelectOption>) => {
    if (selected) {
      onChange(name, selected.value);
    }
  };

  return (
    <div className={`flex flex-col bg-[#F5F5F5] relative w-full ${className}`}>
      <label className="font-creato font-normal text-sm text-[#28241E] tracking-wide leading-none pb-3">
        {label}
      </label>
      <div className="relative w-full overflow-visible min-w-0">
        <Select
          value={selectedOption}
          onChange={handleChange}
          options={options}
          placeholder={placeholder}
          styles={customStyles}
          isSearchable={false}
          className="react-select-container"
          classNamePrefix="react-select"
          instanceId={`search-select-${name}`}
          menuPortalTarget={
            typeof document !== "undefined" ? document.body : null
          }
          menuPosition="absolute"
        />
        <style
          dangerouslySetInnerHTML={{
            __html: `
            .react-select-container .react-select__indicators {
              margin-right: 50px;
            }
            @media (min-width: 1536px) {
              .react-select-container .react-select__indicators {
                margin-right: 0px;
              }
            }
          `,
          }}
        />
      </div>
    </div>
  );
};

interface FilterState {
  type: string;
  location: string;
  size: string;
  status: string;
}

interface DesktopFilterPanelProps {
  filters: FilterState;
  onFilterChange: (name: string, value: string) => void;
  isExpanded: boolean;
  contentHeight: number;
  filterContainerRef: RefObject<HTMLDivElement | null>;
  filterContentRef: RefObject<HTMLDivElement | null>;
}

const DesktopFilterPanel = ({
  filters,
  onFilterChange,
  isExpanded,
  contentHeight,
  filterContainerRef,
  filterContentRef,
}: DesktopFilterPanelProps) => {
  return (
    <div
      ref={filterContainerRef}
      className="hidden xl:block relative w-full overflow-hidden bg-white"
      style={{
        maxHeight: isExpanded ? `${contentHeight}px` : "0px",
        opacity: isExpanded ? 1 : 0,
        transition:
          "max-height 400ms cubic-bezier(0.4, 0, 0.2, 1), opacity 300ms ease-in-out",
        pointerEvents: isExpanded ? "auto" : "none",
        marginTop: "0",
      }}
    >
      {/* Filter Panel Content - Always rendered for measurement */}
      <div
        ref={filterContentRef}
        className="flex flex-col xl:flex-row items-stretch w-full bg-white"
      >
        {/* Property Type */}
        <SearchSelect
          label="Property Type"
          name="type"
          value={filters.type}
          onChange={onFilterChange}
          options={propertyTypeOptions}
          placeholder="All"
          className="py-4 xl:py-7 px-4 xl:pl-3 2xl:pl-5 xl:pr-10 2xl:pr-10 xl:flex-1 xl:min-w-0  border-r border-[#E8E8E8]"
        />

        {/* Location */}
        <SearchSelect
          label="Location"
          name="location"
          value={filters.location}
          onChange={onFilterChange}
          options={locationOptions}
          placeholder="All"
          className="py-4 xl:py-7 px-4 xl:pl-3 2xl:pl-5 xl:pr-10 2xl:pr-10 xl:flex-1 xl:min-w-0  border-r border-[#E8E8E8]"
        />

        {/* Unit Size */}
        <SearchSelect
          label="Unit Size"
          name="size"
          value={filters.size}
          onChange={onFilterChange}
          options={unitSizeOptions}
          placeholder="All"
          className="py-4 xl:py-7 px-4 xl:pl-3 2xl:pl-5 xl:pr-10 2xl:pr-10 xl:flex-1 xl:min-w-0  border-r border-[#E8E8E8]"
        />

        {/* Property Status */}
        <SearchSelect
          label="Property Status"
          name="status"
          value={filters.status}
          onChange={onFilterChange}
          options={propertyStatusOptions}
          placeholder="All"
          className="py-4 xl:py-7 px-4 xl:pl-3 2xl:pl-5 xl:pr-10 2xl:pr-10 xl:flex-1 xl:min-w-0  border-r border-[#E8E8E8]"
        />

        {/* Search Button */}
        <div className="flex items-center justify-center bg-[#F5F5F5] py-4 xl:py-0 px-4 xl:px-6 2xl:px-10 w-full md:w-full xl:flex-shrink-0 xl:w-auto xl:min-w-[180px] 2xl:min-w-[200px]">
          <Link
            href="/search"
            className="bg-[#DD577F] hover:bg-[#333333] text-white font-creato font-medium text-sm xl:text-base py-3 px-8 xl:px-8 2xl:px-10 transition-colors duration-200 cursor-pointer whitespace-nowrap"
          >
            Search Properties
          </Link>
        </div>
      </div>
    </div>
  );
};

export default DesktopFilterPanel;
