"use client"

import { useState, useRef, useEffect, ReactNode } from "react"
import { ChevronDown } from "lucide-react"

interface Option {
  value: string
  label: string
}

interface CustomSelectProps {
  name: string
  value: string
  onChange: (e: { target: { name: string; value: string } }) => void
  options: Option[]
  placeholder: string
  required?: boolean
  className?: string
  /** Ana sitedeki form için "default", admin panel için "admin" */
  variant?: "default" | "admin"
  /** Sol tarafta ikon göstermek için */
  icon?: ReactNode
}

export default function CustomSelect({
  name,
  value,
  onChange,
  options,
  placeholder,
  required = false,
  className = "",
  variant = "default",
  icon,
}: CustomSelectProps) {
  const [isOpen, setIsOpen] = useState(false)
  const selectRef = useRef<HTMLDivElement>(null)

  // Dışarı tıklandığında kapat
  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (selectRef.current && !selectRef.current.contains(event.target as Node)) {
        setIsOpen(false)
      }
    }
    document.addEventListener("mousedown", handleClickOutside)
    return () => document.removeEventListener("mousedown", handleClickOutside)
  }, [])

  const selectedOption = options.find((opt) => opt.value === value)

  const handleSelect = (optionValue: string) => {
    onChange({ target: { name, value: optionValue } })
    setIsOpen(false)
  }

  // Variant'a göre stiller
  const buttonStyles = variant === "admin"
    ? `w-full px-3 py-2.5 ${icon ? 'pl-10' : 'px-3'} pr-10 bg-white border border-gray-200 rounded-xl text-gray-800 focus:outline-none focus:ring-2 focus:ring-blue-500/20 cursor-pointer text-left text-sm`
    : `h-11 sm:h-12 w-full rounded-lg border border-[#0F2A44]/20 bg-white ${icon ? 'pl-10' : 'pl-4'} pr-10 text-left text-sm focus:outline-none focus:border-[#0F2A44] focus:ring-2 focus:ring-[#0F2A44]/20 cursor-pointer`

  const dropdownStyles = variant === "admin"
    ? "absolute z-50 top-full left-0 right-0 mt-1 bg-white border border-gray-200 rounded-xl shadow-lg overflow-hidden max-h-60 overflow-y-auto"
    : "absolute z-50 top-full left-0 right-0 mt-1 bg-white border border-[#0F2A44]/20 rounded-lg shadow-lg overflow-hidden max-h-60 overflow-y-auto"

  const optionStyles = (isSelected: boolean) => variant === "admin"
    ? `px-4 py-2.5 text-sm cursor-pointer transition-colors ${isSelected ? "bg-blue-50 text-blue-600 font-medium" : "text-gray-700 hover:bg-gray-50"}`
    : `px-4 py-3 text-sm cursor-pointer transition-colors ${isSelected ? "bg-[#0F2A44]/10 text-[#0F2A44] font-medium" : "text-[#2E2E2E] hover:bg-[#0F2A44]/5"}`

  const textStyles = variant === "admin"
    ? { selected: "text-gray-800", placeholder: "text-gray-400" }
    : { selected: "text-[#2E2E2E]", placeholder: "text-[#2E2E2E]/50" }

  const chevronStyles = variant === "admin"
    ? "text-gray-400"
    : "text-[#2E2E2E]/40"

  return (
    <div ref={selectRef} className={`relative ${className}`}>
      {/* Hidden input for form validation */}
      <input
        type="text"
        name={name}
        value={value}
        required={required}
        onChange={() => {}}
        className="sr-only"
        tabIndex={-1}
        aria-hidden="true"
      />

      {/* Icon */}
      {icon && (
        <div className="absolute left-3 top-1/2 -translate-y-1/2 pointer-events-none z-10">
          {icon}
        </div>
      )}
      
      {/* Select Button */}
      <button
        type="button"
        onClick={() => setIsOpen(!isOpen)}
        className={buttonStyles}
      >
        <span className={selectedOption ? textStyles.selected : textStyles.placeholder}>
          {selectedOption ? selectedOption.label : placeholder}
        </span>
      </button>

      {/* Chevron Icon */}
      <ChevronDown 
        className={`absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 ${chevronStyles} pointer-events-none transition-transform duration-200 ${isOpen ? "rotate-180" : ""}`} 
      />

      {/* Dropdown */}
      {isOpen && (
        <div className={dropdownStyles}>
          {options.map((option) => (
            <div
              key={option.value}
              onClick={() => handleSelect(option.value)}
              className={optionStyles(value === option.value)}
            >
              {option.label}
            </div>
          ))}
        </div>
      )}
    </div>
  )
}
