'use client';

import { useState, useEffect } from 'react';
import { ChevronDown, Check, Scale } from 'lucide-react';
import { cn } from '../lib/cn';

interface RegimenOption {
  clave: string;
  descripcion: string;
}

interface RegimenSelectorProps {
  regimenes: RegimenOption[];
  selected: string | null;
  onChange: (clave: string | null) => void;
  isLoading?: boolean;
}

export function RegimenSelector({ regimenes, selected, onChange, isLoading }: RegimenSelectorProps) {
  const [open, setOpen] = useState(false);

  useEffect(() => {
    const handleClickOutside = (e: MouseEvent) => {
      const target = e.target as HTMLElement;
      if (!target.closest('.regimen-selector')) {
        setOpen(false);
      }
    };
    document.addEventListener('click', handleClickOutside);
    return () => document.removeEventListener('click', handleClickOutside);
  }, []);

  if (isLoading || regimenes.length === 0) return null;

  const selectedRegimen = selected ? regimenes.find(r => r.clave === selected) : null;
  const displayText = selectedRegimen
    ? `${selectedRegimen.clave} - ${selectedRegimen.descripcion}`
    : 'Todos los regimenes';

  return (
    <div className="regimen-selector relative">
      <button
        onClick={() => setOpen(!open)}
        className={cn(
          'flex items-center gap-2 rounded-lg px-3 py-2 text-sm font-medium transition-colors',
          selected
            ? 'bg-primary/10 text-primary border border-primary/30'
            : 'hover:bg-accent'
        )}
      >
        <Scale className="h-4 w-4" />
        <span className="max-w-[200px] truncate">{displayText}</span>
        <ChevronDown className={cn('h-4 w-4 transition-transform', open && 'rotate-180')} />
      </button>

      {open && (
        <div className="absolute top-full left-0 mt-2 w-80 rounded-lg border bg-card shadow-lg z-50">
          <div className="p-2 border-b">
            <p className="text-xs text-muted-foreground px-2">Regimen fiscal</p>
          </div>
          <div className="max-h-64 overflow-y-auto p-1">
            <button
              onClick={() => {
                onChange(null);
                setOpen(false);
              }}
              className={cn(
                'flex w-full items-center gap-3 rounded-md px-3 py-2 text-sm hover:bg-accent transition-colors',
                !selected && 'bg-primary/10'
              )}
            >
              <span className="flex-1 text-left font-medium">Todos los regimenes</span>
              {!selected && <Check className="h-4 w-4 text-primary" />}
            </button>

            <div className="my-1 border-t" />

            {regimenes.map((regimen) => (
              <button
                key={regimen.clave}
                onClick={() => {
                  onChange(regimen.clave);
                  setOpen(false);
                }}
                className={cn(
                  'flex w-full items-center gap-3 rounded-md px-3 py-2 text-sm hover:bg-accent transition-colors',
                  selected === regimen.clave && 'bg-primary/10'
                )}
              >
                <div className="h-7 w-7 rounded bg-muted flex items-center justify-center text-xs font-mono font-bold">
                  {regimen.clave}
                </div>
                <span className="flex-1 text-left truncate">{regimen.descripcion}</span>
                {selected === regimen.clave && <Check className="h-4 w-4 text-primary" />}
              </button>
            ))}
          </div>
        </div>
      )}
    </div>
  );
}
