import {useState} from 'react';
import {FontAwesomeIcon} from '@fortawesome/react-fontawesome';
import {faChevronDown, faChevronUp, faPlus, faTrash} from '@fortawesome/free-solid-svg-icons';
import {Incident} from '@/lib/models/Book';
import {ActChapter, ChapterListProps} from '@/lib/models/Chapter';
import ActChapterItem from './ActChapter';
import {useTranslations} from 'next-intl';

interface ActIncidentsProps {
    incidents: Incident[];
    actId: number;
    mainChapters: ChapterListProps[];
    newIncidentTitle: string;
    setNewIncidentTitle: (title: string) => void;
    onAddIncident: (actId: number) => Promise<void>;
    onDeleteIncident: (actId: number, incidentId: string) => Promise<void>;
    onLinkChapter: (actId: number, chapterId: string, incidentId: string) => Promise<void>;
    onUpdateChapterSummary: (chapterId: string, summary: string, incidentId: string) => void;
    onUnlinkChapter: (chapterInfoId: string, chapterId: string, incidentId: string) => Promise<void>;
    sectionKey: string;
    isExpanded: boolean;
    onToggleSection: (sectionKey: string) => void;
}

export default function ActIncidents({
                                         incidents,
                                         actId,
                                         mainChapters,
                                         newIncidentTitle,
                                         setNewIncidentTitle,
                                         onAddIncident,
                                         onDeleteIncident,
                                         onLinkChapter,
                                         onUpdateChapterSummary,
                                         onUnlinkChapter,
                                         sectionKey,
                                         isExpanded,
                                         onToggleSection,
                                     }: ActIncidentsProps) {
    const t = useTranslations('actComponent');
    const [expandedItems, setExpandedItems] = useState<{ [key: string]: boolean }>({});
    const [selectedChapterId, setSelectedChapterId] = useState<string>('');
    
    function toggleItem(itemKey: string): void {
        setExpandedItems(prev => ({
            ...prev,
            [itemKey]: !prev[itemKey],
        }));
    }
    
    return (
        <div className="mb-4">
            <button
                className="flex justify-between items-center w-full bg-secondary/50 p-3 rounded-xl text-left hover:bg-secondary transition-all duration-200 shadow-sm"
                onClick={(): void => onToggleSection(sectionKey)}
            >
                <span className="font-bold text-text-primary">{t('incidentsTitle')}</span>
                <FontAwesomeIcon
                    icon={isExpanded ? faChevronUp : faChevronDown}
                    className="text-text-primary w-3.5 h-3.5"
                />
            </button>
            
            {isExpanded && (
                <div className="p-2">
                    {incidents && incidents.length > 0 ? (
                        <>
                            {incidents.map((item: Incident) => {
                                const itemKey = `incident_${item.incidentId}`;
                                const isItemExpanded: boolean = expandedItems[itemKey];
                                
                                return (
                                    <div
                                        key={`incident-${item.incidentId}`}
                                        className="bg-secondary/30 rounded-xl mb-3 overflow-hidden border border-secondary/40 shadow-sm hover:shadow-md transition-all duration-200"
                                    >
                                        <button
                                            className="flex justify-between items-center w-full p-2 text-left"
                                            onClick={(): void => toggleItem(itemKey)}
                                        >
                                            <span className="font-bold text-text-primary">{item.title}</span>
                                            <div className="flex items-center">
                                                <FontAwesomeIcon
                                                    icon={isItemExpanded ? faChevronUp : faChevronDown}
                                                    className="text-text-primary w-3.5 h-3.5 mr-2"
                                                />
                                                <button
                                                    onClick={async (e) => {
                                                        e.stopPropagation();
                                                        await onDeleteIncident(actId, item.incidentId);
                                                    }}
                                                    className="text-error hover:bg-error/20 p-1.5 rounded-lg transition-all duration-200 hover:scale-110"
                                                >
                                                    <FontAwesomeIcon icon={faTrash} className="w-3.5 h-3.5"/>
                                                </button>
                                            </div>
                                        </button>
                                        
                                        {isItemExpanded && (
                                            <div className="p-3 bg-secondary/20">
                                                {item.chapters && item.chapters.length > 0 ? (
                                                    <>
                                                        {item.chapters.map((chapter: ActChapter) => (
                                                            <ActChapterItem
                                                                key={`inc-chapter-${chapter.chapterId}-${chapter.chapterInfoId}`}
                                                                chapter={chapter}
                                                                onUpdateSummary={(chapterId, summary) =>
                                                                    onUpdateChapterSummary(chapterId, summary, item.incidentId)
                                                                }
                                                                onUnlink={(chapterInfoId, chapterId) =>
                                                                    onUnlinkChapter(chapterInfoId, chapterId, item.incidentId)
                                                                }
                                                            />
                                                        ))}
                                                    </>
                                                ) : (
                                                    <p className="text-text-secondary text-center text-sm p-2">
                                                        {t('noLinkedChapter')}
                                                    </p>
                                                )}
                                                
                                                <div className="flex items-center mt-2">
                                                    <select
                                                        onChange={(e) => setSelectedChapterId(e.target.value)}
                                                        className="flex-1 bg-secondary/50 text-text-primary rounded-xl px-4 py-2.5 mr-2 border border-secondary/50 focus:outline-none focus:ring-4 focus:ring-primary/20 focus:border-primary hover:bg-secondary hover:border-secondary transition-all duration-200"
                                                    >
                                                        <option value="">{t('selectChapterPlaceholder')}</option>
                                                        {mainChapters.map((chapter: ChapterListProps) => (
                                                            <option key={chapter.chapterId} value={chapter.chapterId}>
                                                                {`${chapter.chapterOrder}. ${chapter.title}`}
                                                            </option>
                                                        ))}
                                                    </select>
                                                    <button
                                                        className="bg-primary text-text-primary w-9 h-9 rounded-full flex items-center justify-center disabled:opacity-50 disabled:cursor-not-allowed shadow-md hover:shadow-lg hover:scale-110 hover:bg-primary-dark transition-all duration-200"
                                                        onClick={(): Promise<void> =>
                                                            onLinkChapter(actId, selectedChapterId, item.incidentId)
                                                        }
                                                        disabled={selectedChapterId.length === 0}
                                                    >
                                                        <FontAwesomeIcon icon={faPlus} className="w-3.5 h-3.5"/>
                                                    </button>
                                                </div>
                                            </div>
                                        )}
                                    </div>
                                );
                            })}
                        </>
                    ) : (
                        <p className="text-text-secondary text-center text-sm p-2">
                            {t('noIncidentAdded')}
                        </p>
                    )}
                    
                    <div className="flex items-center mt-2">
                        <input
                            type="text"
                            className="flex-1 bg-secondary/50 text-text-primary rounded-xl px-4 py-2.5 mr-2 border border-secondary/50 focus:outline-none focus:ring-4 focus:ring-primary/20 focus:border-primary hover:bg-secondary hover:border-secondary transition-all duration-200 placeholder:text-muted/60"
                            value={newIncidentTitle}
                            onChange={(e) => setNewIncidentTitle(e.target.value)}
                            placeholder={t('newIncidentPlaceholder')}
                        />
                        <button
                            className="bg-primary text-text-primary w-9 h-9 rounded-full flex items-center justify-center disabled:opacity-50 disabled:cursor-not-allowed shadow-md hover:shadow-lg hover:scale-110 hover:bg-primary-dark transition-all duration-200"
                            onClick={(): Promise<void> => onAddIncident(actId)}
                            disabled={newIncidentTitle.trim() === ''}
                        >
                            <FontAwesomeIcon icon={faPlus} className="w-3.5 h-3.5"/>
                        </button>
                    </div>
                </div>
            )}
        </div>
    );
}
