import React, { memo } from 'react';
import { Users, Zap, Flame, Gauge } from 'lucide-react';
import ClientSearchInput from './ClientSearchInput';
import { DashboardCupsType, DashboardSearchMode } from '../types';

interface DashboardSearchBarProps {
    mode: DashboardSearchMode;
    cupsType: DashboardCupsType;
    isLoading: boolean;
    onModeChange: (mode: DashboardSearchMode) => void;
    onCupsTypeChange: (type: DashboardCupsType) => void;
    onSearch: (term: string) => void;
}

interface SegmentOption<T extends string> {
    value: T;
    label: string;
    icon: React.ReactNode;
    tone?: 'electric' | 'gas';
}

const MODE_OPTIONS: SegmentOption<DashboardSearchMode>[] = [
    { value: 'cliente', label: 'Cliente', icon: <Users size={15} /> },
    { value: 'cups', label: 'CUPS', icon: <Gauge size={15} /> },
];

const CUPS_TYPE_OPTIONS: SegmentOption<DashboardCupsType>[] = [
    { value: 'electrico', label: 'Electricidad', icon: <Zap size={14} />, tone: 'electric' },
    { value: 'gas', label: 'Gas', icon: <Flame size={14} />, tone: 'gas' },
];

function Segmented<T extends string>({
    id, label, options, value, onChange, size = 'md',
}: {
    id: string;
    label: string;
    options: SegmentOption<T>[];
    value: T;
    onChange: (v: T) => void;
    size?: 'md' | 'sm';
}) {
    const activeIndex = Math.max(0, options.findIndex((o) => o.value === value));

    const handleKeyDown = (e: React.KeyboardEvent<HTMLDivElement>) => {
        if (e.key !== 'ArrowRight' && e.key !== 'ArrowLeft') return;
        e.preventDefault();
        const delta = e.key === 'ArrowRight' ? 1 : -1;
        const next = options[(activeIndex + delta + options.length) % options.length];
        onChange(next.value);
        document.getElementById(`${id}-${next.value}`)?.focus();
    };

    return (
        <div
            id={id}
            role="radiogroup"
            aria-label={label}
            className={`dash-segmented dash-segmented-${size}`}
            style={{ ['--seg-count' as any]: options.length, ['--seg-index' as any]: activeIndex }}
            onKeyDown={handleKeyDown}
        >
            <span className={`dash-segmented-thumb ${options[activeIndex]?.tone ? `tone-${options[activeIndex].tone}` : ''}`} aria-hidden="true" />
            {options.map((opt) => {
                const active = opt.value === value;
                return (
                    <button
                        key={opt.value}
                        id={`${id}-${opt.value}`}
                        type="button"
                        role="radio"
                        aria-checked={active}
                        tabIndex={active ? 0 : -1}
                        className={`dash-segmented-option ${active ? 'is-active' : ''} ${opt.tone ? `tone-${opt.tone}` : ''}`}
                        onClick={() => onChange(opt.value)}
                    >
                        {opt.icon}
                        <span>{opt.label}</span>
                    </button>
                );
            })}
        </div>
    );
}

const DashboardSearchBar: React.FC<DashboardSearchBarProps> = ({
    mode, cupsType, isLoading, onModeChange, onCupsTypeChange, onSearch,
}) => {
    const isCups = mode === 'cups';
    const isGas = cupsType === 'gas';

    const placeholder = isCups
        ? `Introduce el CUPS de ${isGas ? 'gas' : 'electricidad'} (completo o parcial). Ej: ES0021…`
        : 'Buscar cliente por Razón Social o CIF/NIF…';

    const hint = isCups
        ? `Buscamos el CUPS en ${isGas ? 'suministros de gas' : 'suministros eléctricos'} y te mostramos su titular actual.`
        : 'Escribe al menos 3 caracteres de la razón social o del CIF/NIF.';

    return (
        <div className="dash-search-bar">
            <div className="dash-search-controls">
                <div className="dash-search-control-group">
                    <span className="dash-search-label" id="dash-search-mode-label">Buscar por</span>
                    <Segmented
                        id="dash-search-mode"
                        label="Buscar por cliente o por CUPS"
                        options={MODE_OPTIONS}
                        value={mode}
                        onChange={onModeChange}
                    />
                </div>

                <div className={`dash-search-control-group dash-cups-type ${isCups ? 'is-visible' : ''}`} aria-hidden={!isCups}>
                    <span className="dash-search-label">Tipo de suministro</span>
                    {isCups && (
                        <Segmented
                            id="dash-cups-type"
                            label="Tipo de CUPS"
                            options={CUPS_TYPE_OPTIONS}
                            value={cupsType}
                            onChange={onCupsTypeChange}
                            size="sm"
                        />
                    )}
                </div>
            </div>

            <ClientSearchInput
                key={`${mode}-${cupsType}`}
                inputId="dash-search-input"
                onSearch={onSearch}
                isLoading={isLoading}
                placeholder={placeholder}
                ariaLabel={isCups ? `Buscar CUPS de ${isGas ? 'gas' : 'electricidad'}` : 'Buscar cliente'}
                uppercase={isCups}
                autoFocus
                icon={isCups ? (isGas ? <Flame size={18} color="#ea580c" /> : <Zap size={18} color="#d97706" />) : undefined}
            />

            <p className="dash-search-hint" aria-live="polite">{hint}</p>
        </div>
    );
};

export default memo(DashboardSearchBar);
