/**
 * Sector Selector Component
 * Displays a dropdown to select sectors for the active site
 * Used in the header area of pages that need sector filtering
 */
import { useState, useEffect, useRef } from 'react';
import { Dropdown } from '../ui/dropdown/Dropdown';
import { DropdownItem } from '../ui/dropdown/DropdownItem';
import { useSectorStore } from '../../store/sectorStore';
import { useSiteStore } from '../../store/siteStore';

export default function SectorSelector() {
  const { activeSite } = useSiteStore();
  const { activeSector, sectors, setActiveSector, loading } = useSectorStore();
  const [isOpen, setIsOpen] = useState(false);
  const buttonRef = useRef<HTMLButtonElement>(null);

  // Don't render if no active site
  if (!activeSite) {
    return null;
  }

  // Don't render if no sectors available
  if (!loading && sectors.length === 0) {
    return (
      <div className="flex items-center gap-2 px-3 py-2 text-sm text-gray-500 dark:text-gray-400">
        <span>No sectors available</span>
      </div>
    );
  }

  const handleSectorSelect = (sectorId: number | null) => {
    if (sectorId === null) {
      // "All Sectors" option
      setActiveSector(null);
      setIsOpen(false);
    } else {
      const sector = sectors.find(s => s.id === sectorId);
      if (sector) {
        setActiveSector(sector);
        setIsOpen(false);
      }
    }
  };

  return (
    <div className="relative inline-block">
      <button
        ref={buttonRef}
        onClick={() => setIsOpen(!isOpen)}
        className="flex items-center gap-2 px-3 py-2 text-sm font-medium text-gray-700 bg-white border border-gray-300 rounded-lg hover:bg-gray-50 dark:bg-gray-800 dark:text-gray-300 dark:border-gray-700 dark:hover:bg-gray-700 dropdown-toggle"
        aria-label="Select sector"
        disabled={loading || sectors.length === 0}
      >
        <span className="flex items-center gap-2">
          <svg
            className="w-4 h-4"
            fill="none"
            stroke="currentColor"
            viewBox="0 0 24 24"
          >
            <path
              strokeLinecap="round"
              strokeLinejoin="round"
              strokeWidth={2}
              d="M9 19v-6a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2a2 2 0 002-2zm0 0V9a2 2 0 012-2h2a2 2 0 012 2v10m-6 0a2 2 0 002 2h2a2 2 0 002-2m0 0V5a2 2 0 012-2h2a2 2 0 012 2v14a2 2 0 01-2 2h-2a2 2 0 01-2-2z"
            />
          </svg>
          <span className="max-w-[150px] truncate">
            {loading ? 'Loading...' : activeSector?.name || 'All Sectors'}
          </span>
        </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
        isOpen={isOpen}
        onClose={() => setIsOpen(false)}
        anchorRef={buttonRef}
        placement="bottom-right"
        className="w-64 p-2 overflow-y-auto max-h-[300px]"
      >
        {/* "All Sectors" option */}
        <DropdownItem
          onItemClick={() => handleSectorSelect(null)}
          className={`flex items-center gap-3 px-3 py-2 font-medium rounded-lg text-sm text-left ${
            !activeSector
              ? "bg-brand-50 text-brand-700 dark:bg-brand-500/20 dark:text-brand-300"
              : "text-gray-700 hover:bg-gray-100 hover:text-gray-700 dark:text-gray-400 dark:hover:bg-white/5 dark:hover:text-gray-300"
          }`}
        >
          <span className="flex-1">All Sectors</span>
          {!activeSector && (
            <svg
              className="w-4 h-4 text-brand-600 dark:text-brand-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>
          )}
        </DropdownItem>
        {sectors.map((sector) => (
          <DropdownItem
            key={sector.id}
            onItemClick={() => handleSectorSelect(sector.id)}
            className={`flex items-center gap-3 px-3 py-2 font-medium rounded-lg text-sm text-left ${
              activeSector?.id === sector.id
                ? "bg-brand-50 text-brand-700 dark:bg-brand-500/20 dark:text-brand-300"
                : "text-gray-700 hover:bg-gray-100 hover:text-gray-700 dark:text-gray-400 dark:hover:bg-white/5 dark:hover:text-gray-300"
            }`}
          >
            <span className="flex-1">{sector.name}</span>
            {activeSector?.id === sector.id && (
              <svg
                className="w-4 h-4 text-brand-600 dark:text-brand-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>
            )}
          </DropdownItem>
        ))}
      </Dropdown>
    </div>
  );
}

