'use client';
import React, {useContext, useEffect, useState} from 'react';
import {Attribute, CharacterAttribute, CharacterElement, CharacterProps} from '@/lib/types/character';
import {SelectBoxProps} from '@/components/form/SelectBox';
import {
    advancedCharacterElements,
    basicCharacterElements,
    characterCategories,
    characterStatus
} from '@/lib/constants/character';
import {SeriesCharacterProps} from '@/lib/types/series';
import Badge from '@/components/ui/Badge';
import Collapse from '@/components/ui/Collapse';
import {
    Book,
    Cake,
    Dna,
    Flag,
    Globe,
    Home,
    MessageCircle,
    Palette,
    Quote,
    Skull,
    SlidersHorizontal,
    StickyNote,
    Tag,
    User,
    Users
} from 'lucide-react';
import {useTranslations} from '@/lib/i18n';
import {SessionContext, SessionContextProps} from '@/context/SessionContext';
import {AlertContext, AlertContextProps} from '@/context/AlertContext';
import {dynamicBg} from '@/lib/utils/dynamicStyles';
import {LangContext, LangContextProps} from '@/context/LangContext';
import {BookContext, BookContextProps} from '@/context/BookContext';
import OfflineContext, {OfflineContextType} from '@/context/OfflineContext';
import {isDesktop} from '@/lib/configs';
import {apiGet} from '@/lib/api/client';
import {getCharacterAttributes} from '@/lib/tauri';

type AttributeResponse = { type: string; values: Attribute[] }[];

interface CharacterSettingsDetailProps {
    character: CharacterProps;
    seriesCharacter?: SeriesCharacterProps | null;
    onLoadAttributes?: (attributes: CharacterAttribute) => void;
}

export default function CharacterSettingsDetail({
                                                    character,
                                                    seriesCharacter,
                                                    onLoadAttributes,
                                                }: CharacterSettingsDetailProps): React.JSX.Element {
    const t = useTranslations();
    const {lang}: LangContextProps = useContext<LangContextProps>(LangContext);
    const {session}: SessionContextProps = useContext<SessionContextProps>(SessionContext);
    const {errorMessage}: AlertContextProps = useContext<AlertContextProps>(AlertContext);
    const {book}: BookContextProps = useContext<BookContextProps>(BookContext);
    const {isCurrentlyOffline} = useContext(OfflineContext);
    const [showAdvanced, setShowAdvanced] = useState<boolean>(false);
    
    useEffect(function (): void {
        if (character?.id !== null) {
            getAttributes().then();
        }
    }, [character?.id]);
    
    async function getAttributes(): Promise<void> {
        try {
            const useLocal: boolean = isDesktop && (isCurrentlyOffline() || !!book?.localBook);
            const response: AttributeResponse = useLocal
                ? await getCharacterAttributes(character.id!) as AttributeResponse
                : await apiGet<AttributeResponse>(
                    'character/attribute',
                    session.accessToken,
                    lang,
                    {characterId: character?.id}
                );
            if (response && onLoadAttributes) {
                const attributes: CharacterAttribute = {};
                response.forEach(function (item: { type: string; values: Attribute[] }): void {
                    attributes[item.type] = item.values;
                });
                onLoadAttributes(attributes);
            }
        } catch (e: unknown) {
            if (e instanceof Error) {
                errorMessage(e.message);
            }
        }
    }
    
    function getCategoryLabel(): string {
        const cat: SelectBoxProps | undefined = characterCategories.find((c: SelectBoxProps): boolean => c.value === character.category);
        return cat ? t(cat.label) : character.category || '—';
    }

    function getStatusLabel(): string {
        const stat: SelectBoxProps | undefined = characterStatus.find((s: SelectBoxProps): boolean => s.value === character.status);
        return stat ? t(stat.label) : character.status || '—';
    }
    
    function renderAttributeSection(element: CharacterElement): React.JSX.Element | null {
        const attributes: Attribute[] = character[element.section] || [];
        if (attributes.length === 0) return null;
        
        return (
            <Collapse variant="card" key={element.section} title={element.title} icon={element.icon}>
                    <div className="flex flex-wrap gap-2">
                        {attributes.map(function (attr: Attribute, index: number): React.JSX.Element {
                            return (
                                <span key={index}
                                      className="px-3 py-1 bg-primary/20 text-primary rounded-full text-sm border border-primary/30">
                                    {attr.name}
                                </span>
                            );
                        })}
                    </div>
            </Collapse>
        );
    }
    
    return (
        <div className="space-y-6 px-2 pb-4">
            {/* Hero Section - Image + Infos principales */}
            <div
                className="flex gap-6 p-6 bg-gradient-to-r from-secondary to-transparent rounded-2xl border border-secondary">
                {/* Image */}
                <div className="shrink-0">
                    {character.image ? (
                        <div className="w-32 h-32 rounded-2xl border-4 border-primary overflow-hidden">
                            <img src={character.image} alt={character.name} className="w-full h-full object-cover"/>
                        </div>
                    ) : (
                        <div
                            className="w-32 h-32 rounded-2xl border-4 border-secondary bg-secondary flex items-center justify-center">
                            <User className="w-12 h-12 text-text-secondary" strokeWidth={1.75}/>
                        </div>
                    )}
                </div>
                
                {/* Infos principales */}
                <div className="flex-1 min-w-0">
                    <h2 className="text-2xl font-bold text-text-primary">
                        {character.name} {character.lastName}
                    </h2>
                    {character.nickname && (
                        <p className="text-primary italic mt-1">« {character.nickname} »</p>
                    )}
                    {character.title && (
                        <p className="text-text-secondary mt-2">{character.title}</p>
                    )}
                    
                    {/* Badges */}
                    <div className="flex flex-wrap gap-2 mt-4">
                        <Badge variant="primary" icon={Tag} shape="rounded">{getCategoryLabel()}</Badge>
                        {character.gender && (
                            <Badge variant="muted" icon={Users} shape="rounded">{character.gender}</Badge>
                        )}
                        {character.age && (
                            <Badge variant="muted" icon={Cake}
                                   shape="rounded">{character.age} {t('characterDetail.yearsOld')}</Badge>
                        )}
                    </div>
                </div>
            </div>
            
            {/* Histoire & Biographie */}
            <Collapse variant="card" title={t('characterDetail.historySection')} icon={Book}>
                    <div className="grid grid-cols-1 lg:grid-cols-2 gap-4">
                    <div className="lg:col-span-2">
                        <h4 className="text-text-secondary text-xs uppercase tracking-wide mb-2">{t('characterDetail.biography')}</h4>
                        <p className={`${character.biography ? 'text-text-primary' : 'text-text-dimmed italic'}`}>
                            {character.biography || '—'}
                        </p>
                    </div>
                    <div>
                        <h4 className="text-text-secondary text-xs uppercase tracking-wide mb-2">{t('characterDetail.history')}</h4>
                        <p className={`${character.history ? 'text-text-primary' : 'text-text-dimmed italic'}`}>
                            {character.history || '—'}
                        </p>
                    </div>
                    <div>
                        <h4 className="text-text-secondary text-xs uppercase tracking-wide mb-2">{t('characterDetail.roleFull')}</h4>
                        <p className={`${character.role ? 'text-text-primary' : 'text-text-dimmed italic'}`}>
                            {character.role || '—'}
                        </p>
                    </div>
                </div>
            </Collapse>

            {/* Attributs de base */}
            {basicCharacterElements.map(renderAttributeSection)}
            
            {/* Toggle Mode Avancé */}
            <div
                className="flex items-center justify-between p-4 bg-secondary rounded-xl border border-secondary">
                <div className="flex items-center gap-3">
                    <SlidersHorizontal className="text-primary w-5 h-5" strokeWidth={1.75}/>
                    <span className="text-text-primary font-medium">{t('characterDetail.advancedMode')}</span>
                </div>
                <button
                    onClick={function (): void {
                        setShowAdvanced(!showAdvanced);
                    }}
                    className={`px-4 py-2 rounded-lg transition-all duration-200 ${
                        showAdvanced
                            ? 'bg-primary text-text-primary'
                            : 'bg-secondary text-text-primary hover:bg-gray-dark'
                    }`}
                >
                    {showAdvanced ? t('characterDetail.hideAdvanced') : t('characterDetail.showAdvanced')}
                </button>
            </div>
            
            {/* Sections avancées */}
            {showAdvanced && (
                <>
                    {/* Identité étendue */}
                    <Collapse variant="card" title={t('characterDetail.identitySection')} icon={Globe}>
                            <div className="grid grid-cols-2 lg:grid-cols-4 gap-4">
                                <div className="p-3 rounded-lg">
                                <div className="flex items-center gap-2 mb-2">
                                    <Dna className="w-3 h-3 text-primary" strokeWidth={1.75}/>
                                    <span
                                        className="text-text-secondary text-xs uppercase">{t('characterDetail.species')}</span>
                                </div>
                                    <p className={character.species ? 'text-text-primary' : 'text-text-dimmed italic'}>
                                    {character.species || '—'}
                                </p>
                            </div>
                                <div className="p-3 rounded-lg">
                                <div className="flex items-center gap-2 mb-2">
                                    <Flag className="w-3 h-3 text-primary" strokeWidth={1.75}/>
                                    <span
                                        className="text-text-secondary text-xs uppercase">{t('characterDetail.nationality')}</span>
                                </div>
                                    <p className={character.nationality ? 'text-text-primary' : 'text-text-dimmed italic'}>
                                    {character.nationality || '—'}
                                </p>
                            </div>
                                <div className="p-3 rounded-lg">
                                <div className="flex items-center gap-2 mb-2">
                                    <Skull className="w-3 h-3 text-primary" strokeWidth={1.75}/>
                                    <span
                                        className="text-text-secondary text-xs uppercase">{t('characterDetail.status')}</span>
                                </div>
                                    <p className={character.status ? 'text-text-primary' : 'text-text-dimmed italic'}>
                                    {getStatusLabel()}
                                </p>
                            </div>
                                <div className="p-3 rounded-lg">
                                <div className="flex items-center gap-2 mb-2">
                                    <Home className="w-3 h-3 text-primary" strokeWidth={1.75}/>
                                    <span
                                        className="text-text-secondary text-xs uppercase">{t('characterDetail.residence')}</span>
                                </div>
                                    <p className={character.residence ? 'text-text-primary' : 'text-text-dimmed italic'}>
                                    {character.residence || '—'}
                                </p>
                            </div>
                        </div>
                    </Collapse>

                    {/* Voix du personnage */}
                    <Collapse variant="card" title={t('characterDetail.voiceSection')} icon={MessageCircle}>
                            <div className="grid grid-cols-1 lg:grid-cols-2 gap-4">
                                <div className="p-4 rounded-lg">
                                <h4 className="text-text-secondary text-xs uppercase tracking-wide mb-2">{t('characterDetail.speechPattern')}</h4>
                                    <p className={`${character.speechPattern ? 'text-text-primary' : 'text-text-dimmed italic'}`}>
                                    {character.speechPattern || '—'}
                                </p>
                            </div>
                                <div className="p-4 rounded-lg relative">
                                <Quote className="absolute top-2 left-2 w-6 h-6 text-primary/20" strokeWidth={1.75}/>
                                <h4 className="text-text-secondary text-xs uppercase tracking-wide mb-2">{t('characterDetail.catchphrase')}</h4>
                                    <p className={`italic ${character.catchphrase ? 'text-text-primary' : 'text-text-dimmed'}`}>
                                    {character.catchphrase ? `« ${character.catchphrase} »` : '—'}
                                </p>
                            </div>
                        </div>
                    </Collapse>

                    {/* Notes de l'auteur */}
                    <Collapse variant="card" title={t('characterDetail.authorSection')} icon={StickyNote}>
                            <div className="grid grid-cols-1 lg:grid-cols-3 gap-4">
                                <div className="lg:col-span-2 p-4 rounded-lg">
                                <div className="flex items-center gap-2 mb-2">
                                    <StickyNote className="w-3 h-3 text-primary" strokeWidth={1.75}/>
                                    <span
                                        className="text-text-secondary text-xs uppercase">{t('characterDetail.notes')}</span>
                                </div>
                                    <p className={`${character.notes ? 'text-text-primary' : 'text-text-dimmed italic'}`}>
                                    {character.notes || '—'}
                                </p>
                            </div>
                                <div className="p-4 rounded-lg">
                                <div className="flex items-center gap-2 mb-2">
                                    <Palette className="w-3 h-3 text-primary" strokeWidth={1.75}/>
                                    <span
                                        className="text-text-secondary text-xs uppercase">{t('characterDetail.colorLabel')}</span>
                                </div>
                                {character.color ? (
                                    <div className="flex items-center gap-3">
                                        <div
                                            className={`w-8 h-8 rounded-lg border-2 border-secondary ${character.color ? dynamicBg(character.color) : ''}`}
                                        />
                                        <span className="text-text-primary font-mono">{character.color}</span>
                                    </div>
                                ) : (
                                    <p className="text-text-dimmed italic">—</p>
                                )}
                            </div>
                        </div>
                    </Collapse>
                    
                    {/* Attributs avancés */}
                    {advancedCharacterElements.map(renderAttributeSection)}
                </>
            )}
        </div>
    );
}
