"use client";

/**
 * CurrencySelector Component
 *
 * A dropdown component for selecting display currency.
 * Supports both Arabic and English layouts (RTL/LTR).
 */

import React, { useState, useRef, useEffect } from "react";
import type { Currency } from "@/lib/types/pricing";
import {
  CURRENCY_CONFIG,
  SUPPORTED_CURRENCIES,
} from "@/lib/config/currencies.config";

interface CurrencySelectorProps {
  value: Currency;
  onChange: (currency: Currency) => void;
  lang?: "en" | "ar";
  className?: string;
  disabled?: boolean;
}

export function CurrencySelector({
  value,
  onChange,
  lang = "en",
  className = "",
  disabled = false,
}: CurrencySelectorProps) {
  const [isOpen, setIsOpen] = useState(false);
  const dropdownRef = useRef<HTMLDivElement>(null);

  // Close dropdown when clicking outside
  useEffect(() => {
    function handleClickOutside(event: MouseEvent) {
      if (
        dropdownRef.current &&
        !dropdownRef.current.contains(event.target as Node)
      ) {
        setIsOpen(false);
      }
    }

    document.addEventListener("mousedown", handleClickOutside);
    return () => {
      document.removeEventListener("mousedown", handleClickOutside);
    };
  }, []);

  const currentConfig = CURRENCY_CONFIG[value];

  return (
    <div
      ref={dropdownRef}
      className={`relative inline-block ${className}`}
      dir={lang === "ar" ? "rtl" : "ltr"}
    >
      {/* Trigger Button */}
      <button
        type="button"
        onClick={() => !disabled && setIsOpen(!isOpen)}
        disabled={disabled}
        className={`
          flex items-center gap-2 px-3 py-2
          border border-gray-300 dark:border-gray-600
          rounded-lg bg-white dark:bg-gray-800
          text-sm text-gray-700 dark:text-gray-200
          hover:bg-gray-50 dark:hover:bg-gray-700
          focus:outline-none focus:ring-2 focus:ring-blue-500
          disabled:opacity-50 disabled:cursor-not-allowed
          transition-colors
        `}
        aria-haspopup="listbox"
        aria-expanded={isOpen}
      >
        <span className="font-medium">{currentConfig.symbol}</span>
        <span>{currentConfig.code}</span>
        <svg
          className={`w-4 h-4 transition-transform ${isOpen ? "rotate-180" : ""}`}
          fill="none"
          stroke="currentColor"
          viewBox="0 0 24 24"
        >
          <path
            strokeLinecap="round"
            strokeLinejoin="round"
            strokeWidth={2}
            d="M19 9l-7 7-7-7"
          />
        </svg>
      </button>

      {/* Dropdown Menu */}
      {isOpen && (
        <div
          className={`
            absolute z-50 mt-1 w-56
            bg-white dark:bg-gray-800
            border border-gray-200 dark:border-gray-700
            rounded-lg shadow-lg
            max-h-60 overflow-auto
            ${lang === "ar" ? "right-0" : "left-0"}
          `}
          role="listbox"
        >
          {SUPPORTED_CURRENCIES.map((currency) => {
            const config = CURRENCY_CONFIG[currency];
            const isSelected = currency === value;

            return (
              <button
                key={currency}
                type="button"
                onClick={() => {
                  onChange(currency);
                  setIsOpen(false);
                }}
                className={`
                  w-full flex items-center gap-3 px-4 py-2.5
                  text-sm text-left
                  ${lang === "ar" ? "text-right" : "text-left"}
                  hover:bg-gray-100 dark:hover:bg-gray-700
                  ${isSelected ? "bg-blue-50 dark:bg-blue-900/30 text-blue-600 dark:text-blue-400" : "text-gray-700 dark:text-gray-200"}
                  transition-colors
                `}
                role="option"
                aria-selected={isSelected}
              >
                <span
                  className={`w-8 text-center font-medium ${config.isRTL ? "font-arabic" : ""}`}
                >
                  {config.symbol}
                </span>
                <span className="flex-1">
                  <span className="font-medium">{config.code}</span>
                  <span className="mx-1.5 text-gray-400">-</span>
                  <span className="text-gray-500 dark:text-gray-400">
                    {lang === "ar" ? config.nameAr : config.name}
                  </span>
                </span>
                {isSelected && (
                  <svg
                    className="w-4 h-4 text-blue-600 dark:text-blue-400"
                    fill="currentColor"
                    viewBox="0 0 20 20"
                  >
                    <path
                      fillRule="evenodd"
                      d="M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z"
                      clipRule="evenodd"
                    />
                  </svg>
                )}
              </button>
            );
          })}
        </div>
      )}
    </div>
  );
}

/**
 * Compact currency selector for inline use
 */
export function CurrencySelectorInline({
  value,
  onChange,
  className = "",
}: {
  value: Currency;
  onChange: (currency: Currency) => void;
  className?: string;
}) {
  return (
    <select
      value={value}
      onChange={(e) => onChange(e.target.value as Currency)}
      aria-label="Select currency"
      className={`
        px-2 py-1 text-sm
        border border-gray-300 dark:border-gray-600
        rounded bg-white dark:bg-gray-800
        text-gray-700 dark:text-gray-200
        focus:outline-none focus:ring-1 focus:ring-blue-500
        ${className}
      `}
    >
      {SUPPORTED_CURRENCIES.map((currency) => {
        const config = CURRENCY_CONFIG[currency];
        return (
          <option key={currency} value={currency}>
            {config.symbol} {config.code}
          </option>
        );
      })}
    </select>
  );
}
