"use client";

import { useEffect, useState } from "react";
import {
  locationOptions,
  propertyStatusOptions,
  propertyTypeOptions,
  unitSizeOptions,
} from "../properties/contents/filter/constants";

interface SearchModalProps {
  isOpen: boolean;
  onClose: () => void;
}

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

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

const DarkSelect = ({ label, name, value, onChange, options }: DarkSelectProps) => {
  const [isOpen, setIsOpen] = useState(false);
  const selectedOption = options.find((opt) => opt.value === value);

  return (
    <div className="relative">
      <label className="block text-[10px] uppercase tracking-[0.2em] text-white/40 mb-2">
        {label}
      </label>
      <button
        type="button"
        onClick={() => setIsOpen(!isOpen)}
        className="w-full flex items-center justify-between text-left text-white/90 text-sm font-light tracking-wide py-2 border-b border-white/10 hover:border-white/30 transition-colors duration-300"
      >
        <span>{selectedOption?.label || "Select..."}</span>
        <svg
          className={`w-4 h-4 text-white/50 transition-transform duration-300 ${isOpen ? "rotate-180" : ""}`}
          fill="none"
          stroke="currentColor"
          viewBox="0 0 24 24"
        >
          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="1.5" d="M19 9l-7 7-7-7" />
        </svg>
      </button>

      {/* Dropdown */}
      {isOpen && (
        <>
          <div className="fixed inset-0 z-40" onClick={() => setIsOpen(false)} />
          <div className="absolute top-full left-0 right-0 mt-2 bg-[#2a2a2a] border border-white/10 rounded shadow-xl z-50 max-h-48 overflow-y-auto">
            {options.map((option) => (
              <button
                key={option.value}
                type="button"
                onClick={() => {
                  onChange(name, option.value);
                  setIsOpen(false);
                }}
                className={`w-full text-left px-4 py-3 text-sm transition-colors duration-200 ${
                  option.value === value
                    ? "bg-white/10 text-white"
                    : "text-white/70 hover:bg-white/5 hover:text-white"
                }`}
              >
                {option.label}
              </button>
            ))}
          </div>
        </>
      )}
    </div>
  );
};

const SearchModal = ({ isOpen, onClose }: SearchModalProps) => {
  const [shouldRender, setShouldRender] = useState(false);
  const [isAnimating, setIsAnimating] = useState(false);
  const [searchQuery, setSearchQuery] = useState("");
  const [filters, setFilters] = useState({
    propertyType: "all",
    location: "all",
    size: "all",
    status: "all",
  });

  const handleFilterChange = (name: string, value: string) => {
    setFilters((prev) => ({ ...prev, [name]: value }));
  };

  const handleSearch = (e: React.FormEvent) => {
    e.preventDefault();
    console.log("Search:", { searchQuery, filters });
    onClose();
  };

  // Handle mount/unmount with animation
  useEffect(() => {
    if (isOpen) {
      setShouldRender(true);
      const timer = setTimeout(() => setIsAnimating(true), 10);
      return () => clearTimeout(timer);
    } else {
      setIsAnimating(false);
      const timer = setTimeout(() => setShouldRender(false), 500);
      return () => clearTimeout(timer);
    }
  }, [isOpen]);

  // Prevent body scroll when modal is open
  useEffect(() => {
    if (isOpen) {
      document.body.style.overflow = "hidden";
    } else {
      document.body.style.overflow = "unset";
    }
    return () => {
      document.body.style.overflow = "unset";
    };
  }, [isOpen]);

  // Close on Escape key
  useEffect(() => {
    const handleEscape = (e: KeyboardEvent) => {
      if (e.key === "Escape" && isOpen) {
        onClose();
      }
    };
    window.addEventListener("keydown", handleEscape);
    return () => window.removeEventListener("keydown", handleEscape);
  }, [isOpen, onClose]);

  if (!shouldRender) return null;

  return (
    <div
      className={`fixed inset-0 z-50 flex items-start justify-center transition-opacity duration-500 ${
        isAnimating ? "opacity-100" : "opacity-0 pointer-events-none"
      }`}
      onClick={onClose}
    >
      {/* Backdrop */}
      <div className="absolute inset-0 bg-black/60 backdrop-blur-md" />

      {/* Modal Panel */}
      <div
        className={`relative w-full max-w-5xl mx-4 mt-16 md:mt-24 bg-[#1a1a1a] rounded-lg shadow-2xl transform transition-all duration-500 ease-out ${
          isAnimating
            ? "translate-y-0 opacity-100"
            : "-translate-y-8 opacity-0 pointer-events-none"
        }`}
        onClick={(e) => e.stopPropagation()}
      >
        {/* Close Button */}
        <button
          onClick={onClose}
          className="absolute -top-12 right-0 p-2 text-white/60 hover:text-white transition-colors duration-300"
          aria-label="Close search modal"
        >
          <svg width="28" height="28" viewBox="0 0 24 24" fill="none">
            <path
              d="M18 6L6 18M6 6L18 18"
              stroke="currentColor"
              strokeWidth="1.5"
              strokeLinecap="round"
              strokeLinejoin="round"
            />
          </svg>
        </button>

        {/* Content */}
        <form onSubmit={handleSearch} className="p-8 md:p-12">
          {/* Search Input */}
          <div className="relative mb-12">
            <div className="absolute left-0 top-1/2 -translate-y-1/2 text-white/30">
              <svg width="20" height="20" viewBox="0 0 24 24" fill="none">
                <circle cx="11" cy="11" r="7" stroke="currentColor" strokeWidth="1.5" />
                <path d="M20 20L16.5 16.5" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" />
              </svg>
            </div>
            <input
              type="text"
              value={searchQuery}
              onChange={(e) => setSearchQuery(e.target.value)}
              placeholder="Search by project name..."
              className="w-full bg-transparent text-white text-lg md:text-xl font-light tracking-wide pl-10 pr-4 py-3 border-b border-white/20 placeholder-white/30 focus:outline-none focus:border-white/40 transition-colors duration-300"
            />
          </div>

          {/* Filters Grid */}
          <div className="grid grid-cols-2 md:grid-cols-4 gap-6 md:gap-8 mb-12">
            <DarkSelect
              label="Property Type"
              name="propertyType"
              value={filters.propertyType}
              onChange={handleFilterChange}
              options={propertyTypeOptions}
            />
            <DarkSelect
              label="Location"
              name="location"
              value={filters.location}
              onChange={handleFilterChange}
              options={locationOptions}
            />
            <DarkSelect
              label="Unit Size"
              name="size"
              value={filters.size}
              onChange={handleFilterChange}
              options={unitSizeOptions}
            />
            <DarkSelect
              label="Status"
              name="status"
              value={filters.status}
              onChange={handleFilterChange}
              options={propertyStatusOptions}
            />
          </div>

          {/* Search Button */}
          <div className="flex justify-center">
            <button
              type="submit"
              className="group relative px-12 py-4 bg-transparent border border-white/30 text-white text-sm uppercase tracking-[0.2em] font-light overflow-hidden transition-all duration-500 hover:border-white/60"
            >
              <span className="relative z-10 transition-colors duration-500 group-hover:text-black">
                Search Properties
              </span>
              <div className="absolute inset-0 bg-white transform translate-y-full transition-transform duration-500 ease-out group-hover:translate-y-0" />
            </button>
          </div>
        </form>

        {/* Decorative accent line */}
        <div className="absolute bottom-0 left-1/2 -translate-x-1/2 w-24 h-[2px] bg-gradient-to-r from-transparent via-[#cd607f] to-transparent" />
      </div>
    </div>
  );
};

export default SearchModal;
