'use client';

import { useState } from 'react';
import { Input } from '@/components/ui/input';
import { Button } from '@/components/ui/button';
import { Label } from '@/components/ui/label';
import { X } from 'lucide-react';

import { useLanguage } from '@/lib/language-context';

interface ICD10SelectProps {
    diagnoses: string[];
    setDiagnoses: (diagnoses: string[]) => void;
}

export default function ICD10Select({ diagnoses = [], setDiagnoses }: ICD10SelectProps) {
    const { t } = useLanguage();
    const [inputValue, setInputValue] = useState('');

    const handleAdd = () => {
        if (inputValue.trim() && !diagnoses.includes(inputValue.trim())) {
            setDiagnoses([...diagnoses, inputValue.trim()]);
            setInputValue('');
        }
    };

    const handleRemove = (diagnosis: string) => {
        setDiagnoses(diagnoses.filter((d) => d !== diagnosis));
    };

    return (
        <div className="space-y-4">
            <Label>{t('clinicalRecord.diagnosesICD10')}</Label>
            <div className="flex gap-2">
                <Input
                    value={inputValue}
                    onChange={(e) => setInputValue(e.target.value)}
                    placeholder={t('clinicalRecord.enterDiagnosisPlaceholder')}
                    onKeyDown={(e) => e.key === 'Enter' && (e.preventDefault(), handleAdd())}
                />
                <Button type="button" onClick={handleAdd}>{t('clinicalRecord.addDiagnosis')}</Button>
            </div>

            <div className="flex flex-wrap gap-2 mt-2">
                {diagnoses.map((diagnosis, index) => (
                    <div key={index} className="flex items-center gap-1 bg-slate-100 text-slate-800 px-3 py-1 rounded-full text-sm border border-slate-200">
                        <span>{diagnosis}</span>
                        <button
                            type="button"
                            onClick={() => handleRemove(diagnosis)}
                            className="text-slate-500 hover:text-red-500 focus:outline-none"
                        >
                            <X size={14} />
                        </button>
                    </div>
                ))}
                {diagnoses.length === 0 && (
                    <span className="text-slate-400 text-sm italic">{t('clinicalRecord.noDiagnosesAdded')}</span>
                )}
            </div>
        </div>
    );
}
