import { useEffect, useState } from "react";
import { Card } from "primereact/card";
import { Tag } from "primereact/tag";
import { Tooltip } from "primereact/tooltip";
import { Button } from "primereact/button";
import {
    Description,
    GenreProportion,
    NameItem,
    NameType,
    VoteDeleteModel,
    VoteEditModel
} from "../../../api/models/Types.tsx";
import {GetTitleNames, TitleNames} from "../../../components/library/NameComponent.tsx";
import { libraryClient } from "../../../api/axios.tsx";
import useUser from "../../../api/hooks/useUser.tsx";
import {QueryClient, useQuery, useQueryClient } from "@tanstack/react-query";
import {currentUser as currentUserQueryKey} from "../../../common/QueryKeys.tsx";
import { useParams } from "react-router-dom";
import {GetAnimeTitleDetail, UnvoteAnimeTitle, VoteAnimeTitle} from "../../../api/AnimeTitleApi.tsx";
import {DateToString, GetDate, TruncateString} from "../../../common/Helper.tsx";
import RadarChart from "../../../components/RadarChart.tsx";
import {TabPanel, TabView } from "primereact/tabview";
import { DataScroller } from "primereact/datascroller";
import { ScrollPanel } from "primereact/scrollpanel";
import { Badge } from "primereact/badge";
import React from "react";
import ViewComponent from "../../../components/library/ViewComponent.tsx";
import RatingComponent from "../../../components/RatingComponent.tsx";
import LastViewComponent from "../../../components/library/LastViewComponent.tsx";
import { Divider } from "primereact/divider";

const queryKey = 'anime_title_detail';
export default function TitleDetail() {
    const client = libraryClient;
    //useAxiosWithAuth(libraryClient);
    const { getUser } = useUser();
    const queryClient = useQueryClient();
    const { data: user } = useQuery({queryKey: [currentUserQueryKey], queryFn: () => getUser(),
        refetchInterval: 30000}, queryClient);

    const { id } = useParams();
    const { data: animeTitle, isLoading, isError } = useQuery({queryKey: [queryKey],
        queryFn: () => GetAnimeTitleDetail(id ?? '', client)}, queryClient);
    
    const [ isRateEditing, setIsRateEditing ] = useState<boolean>(false);
    // const [ isRateEditing, setIsRateEditing ] = useState<bool>(false);

    const [ titleNames, setTitleNames ] = useState<TitleNames | null>(null);
    const [ originalName, setOriginalName ] = useState<NameItem | null>(null);
    const [ otherNames, setOtherNames ] = useState<Array<NameItem>>([]);
    const [ abbreviations, setAbbreviations ] = useState<Array<NameItem>>([]);
    const [ namesActiveIndex, setNamesActiveIndex ] = useState<number>(0);
    const [ mainDescription, setMainDescription ] = useState<Description | null>(null);
    const [ otherDescriptions, setOtherDescriptions ] = useState<Array<Description>>([]);
    const [ descriptionsActiveIndex, setDescriptionsActiveIndex ] = useState<number>(0);
    const [ selectedOtherDescription, setSelectedOtherDescription ] = useState<Description | null>(null);
    const [ releaseDate, setReleaseDate ] = useState<Date | null>(null);
    const [ expectedReleaseDate, setExpectedReleaseDate ] = useState<Date | null>(null);

    useEffect(() => {        
        if (animeTitle == null) {
            setTitleNames(null);
            setOriginalName(null);
            setOtherNames([]);
            setAbbreviations([]);
            setMainDescription(null);
            setOtherDescriptions([]);
        }
        else {
            const names = GetTitleNames(animeTitle.commonProperties.names, user?.languageId);
            setTitleNames(names);
            setOriginalName(animeTitle.commonProperties.names.find(q => q.type === NameType.Original) ?? null);
            setOtherNames(animeTitle.commonProperties.names
                .filter(q => names.namesUsed?.includes(q) != true && q.type !== NameType.Abbreviation) ?? []);
            setAbbreviations(animeTitle.commonProperties.names
                .filter(q => names.namesUsed?.includes(q) != true && q.type === NameType.Abbreviation) ?? []);
            
            let mainDescription;
            if (user?.languageId == null) {
                mainDescription = animeTitle.commonProperties.descriptions.find((desc) => desc.isOriginal)
            }
            else{
                mainDescription = animeTitle.commonProperties.descriptions.find(
                        (desc) => desc.language.id === user.languageId && desc.isOriginal
                    ) ?? animeTitle.commonProperties.descriptions.find((desc) => desc.language.id === user.languageId)
                    ?? animeTitle.commonProperties.descriptions.find((desc) => desc.isOriginal);
            }
            setMainDescription(mainDescription ?? null);
            const otherDescriptions = animeTitle.commonProperties.descriptions.filter((desc) => desc !== mainDescription);
            setOtherDescriptions(otherDescriptions ?? null);
            setSelectedOtherDescription(selectedOtherDescription == null
                ? otherDescriptions.length > 0 ? otherDescriptions[0] : null
                : otherDescriptions.find((q) => q.value === selectedOtherDescription.value
                    && q.language.id === selectedOtherDescription.language.id) ?? null);
        }
        setReleaseDate(GetDate(animeTitle?.commonProperties.releaseDate));
        setExpectedReleaseDate(GetDate(animeTitle?.commonProperties.expectedReleaseDate));
    }, [animeTitle, user]); //user

    useEffect(() => {
        setNamesActiveIndex(otherNames.length > 0 ? 0 : abbreviations.length > 0 ? 1 : 0);
    }, [otherNames, abbreviations]);
    
    useEffect(() => {
        setDescriptionsActiveIndex(mainDescription != null ? 0 : (otherDescriptions.length > 0 ? 1 : 0));
    }, [mainDescription, otherDescriptions]);
    
    if (animeTitle == null){
        return (<>НЕТУТИ НИЧАГО</>);
    }
    
    if (isLoading){
        return (
            <>Загрузка...</>
        );
    }

    return (
        <div className='grid pt-3'>
            <div className='col'>
                <div className='p-card p-component flex flex-column'>
                    <div className="p-card-header surface-100 px-3 border-round-md border-noround-bottom">
                        <h3 className="py-2 my-0">
                            {titleNames &&
                                titleNames.titleElement
                            }
                            {!titleNames &&
                                <>Без названия</>
                            }
                        </h3>
                    </div>
                    <div className='p-card-body p-2 pt-1 flex-grow-1'>

                        <div className="grid p-2">
                            {/* 📌 Верхняя часть */}
                            <div className="col-12 sm:col-6 lg:col-3">
                                {animeTitle.commonProperties.preview?.url && (
                                    <img src={animeTitle.commonProperties.preview.url} className="w-full border-round"
                                         alt={(originalName ? `[${originalName.value}] ` : '') +  'preview'} />
                                )}

                                {/*{GetInfo(GetDate(animeTitle.commonProperties.releaseDate), GetDate(animeTitle.commonProperties.expectedReleaseDate),*/}
                                {/*    GetDate(animeTitle.commonProperties.firstEpisodeReleaseDate), GetDate(animeTitle.commonProperties.lastEpisodeReleaseDate),*/}
                                {/*    animeTitle.director, animeTitle.studio, animeTitle.country)}*/}
                                {ShowTitleInfo(GetDate(animeTitle.commonProperties.releaseDate), GetDate(animeTitle.commonProperties.expectedReleaseDate),
                                    null, null, null, null, null)}
                                
                            </div>
                            <div className="col-12 sm:col-6 lg:col-8">

                                <div className='grid align-items-center'>
                                    <div className="col-12 md:col-8">
                                        <RatingComponent
                                            rateObjectId={animeTitle.id}
                                            ratePercentage={animeTitle.rate}
                                            userRatePercentage={animeTitle.myRate}
                                            isEditing={isRateEditing}
                                            setIsEditing={(id) => setIsRateEditing(id != null)}
                                            setRate={(value) => {
                                                // console.log(`Set rate (${value == null ? 'null' : value}) of [${rateObjectId}]`);
                                                if (value != null){
                                                    return VoteAnimeTitle({
                                                        animeTitleId: animeTitle.id,
                                                        animeSeasonId: null,
                                                        animeEpisodeId: null,
                                                        ratingPercentage: value
                                                    } as VoteEditModel);
                                                }
                                                else{
                                                    return UnvoteAnimeTitle({
                                                        animeTitleId: animeTitle.id,
                                                        animeSeasonId: null,
                                                        animeEpisodeId: null,
                                                    } as VoteDeleteModel);
                                                }
                                            }}
                                            deleteRate={() => {
                                                // console.log(`Delete rate of [${rateObjectId}]`);
                                                return UnvoteAnimeTitle({
                                                    animeTitleId: animeTitle.id,
                                                    animeSeasonId: null,
                                                    animeEpisodeId: null,
                                                } as VoteDeleteModel);
                                            }}
                                            forceRefresh={() => InvalidateTitle(queryClient)}
                                        />
                                    </div>
                                    <div className="col-12 md:col-4">
                                        <ViewComponent views={animeTitle.views} myViews={animeTitle.myViews} />
                                    </div>
                                </div>

                                {/*<LastViewComponent item={animeTitle}/>*/}
                                
                                <TabView key='name-tabview' className='border-2 border-200 border-round'
                                         activeIndex={namesActiveIndex}
                                >
                                    <TabPanel header='Другие названия' disabled={otherNames.length === 0}>
                                        {otherNames.length > 0 ? (
                                            <DataScroller value={otherNames} rows={5} loader
                                                          itemTemplate={(name) => (
                                                              <div className='my-2 p-2 surface-200 border-round'>
                                                                  <span
                                                                      className='select-all'>{name.value}</span> [{name.language.codeIso3}]
                                                              </div>
                                                          )}/>
                                        ) : (
                                            <div
                                                className="text-200 font-bold p-1 px-2  border-1 border-round border-dashed bg-bluegray-800">Отсутствует</div>
                                        )}
                                    </TabPanel>
                                    <TabPanel header="Аббривеатуры" disabled={abbreviations.length === 0}>
                                        <DataScroller value={abbreviations} rows={5} loader
                                                      itemTemplate={(name) => {
                                                          return <div
                                                              className='my-2 p-2 surface-200 border-round'>{name.value} [{name.language.codeIso3}]</div>
                                                      }}/>
                                    </TabPanel>
                                </TabView>

                                {/*<ScrollPanel style={{ width: '100%', height: '200px' }}>*/}
                                {/*    <p>*/}
                                {/*        Lorem ipsum dolor ...*/}
                                {/*    </p>*/}
                                {/*</ScrollPanel>*/}

                                <TabView key='description-tabview' className='border-2 border-200 border-round mt-2'
                                         activeIndex={descriptionsActiveIndex}
                                >
                                    <TabPanel header='Описание' disabled={mainDescription == null}>
                                        {mainDescription ? (
                                            <div className="relative">
                                                <Badge className="absolute top-0 left-0" severity="info"
                                                       style={{transform: 'translate(-20%, -40%)',}}
                                                       value={mainDescription.language.codeIso3}/>
                                                <ScrollPanel className='border-1 border-round pt-3 pb-2'
                                                             style={{height: '15.3em'}}>
                                                    <p className='mx-2 my-0'>{mainDescription.value}</p>
                                                </ScrollPanel>
                                            </div>
                                        ) : (
                                            <div
                                                className="text-200 font-bold p-1 px-2 border-1 border-round border-dashed bg-bluegray-800">Отсутствует</div>
                                        )}
                                    </TabPanel>
                                    <TabPanel header="Другие описания" disabled={otherDescriptions.length === 0}>
                                        <div className="grid">
                                            <div className="col pb-0">
                                                {selectedOtherDescription ? (
                                                    <div className="relative">
                                                        <Badge className="absolute top-0 left-0" severity='secondary'
                                                               style={{transform: 'translate(-20%, -40%)',}}
                                                               value={selectedOtherDescription.language.codeIso3}/>

                                                        <ScrollPanel className='border-1 border-round pt-3 pb-2'
                                                                     style={{height: '15.3em'}}>
                                                            <p className='mx-2 my-0'>{selectedOtherDescription.value}</p>
                                                        </ScrollPanel>
                                                    </div>
                                                ) : (
                                                    <span className="text-gray-500">Выберите описание</span>
                                                )}
                                            </div>
                                            <div className="col-4 h-full">
                                                <DataScroller value={otherDescriptions} rows={5} loader
                                                              itemTemplate={(desc) => (
                                                                  <div
                                                                      className={'border-round p-1 mb-2 cursor-pointer border-' + (desc == selectedOtherDescription ? '2 bg-primary-400 text-50 border-300' : '1 surface-50')}
                                                                      onClick={() => setSelectedOtherDescription(desc)}>
                                                                      <Badge value={desc.language.codeIso3}
                                                                             severity='secondary'/>
                                                                      <span
                                                                          className='ml-2 vertical-align-middle'>{TruncateString(desc.value, 20)}</span>
                                                                  </div>
                                                              )}
                                                />
                                            </div>
                                        </div>

                                    </TabPanel>
                                </TabView>

                                <div className='d-flex '>
                                    {ShowGenres(animeTitle.commonProperties.genres)}
                                </div>
                            </div>


                            {/*/!* 📌 Список сезонов и серий (заглушка) *!/*/}
                            {/*<div className="col-12">*/}
                            {/*    <Card className="p-3">*/}
                            {/*        <h3>Содержимое</h3>*/}
                            {/*        /!* TODO: Добавить список сезонов и серий *!/*/}
                            {/*        <p>Список сезонов и серий скоро появится!</p>*/}
                            {/*    </Card>*/}
                            {/*</div>*/}

                        </div>
                        
                    </div>
                </div>
            </div>

            {/* 📌 Пользовательские данные (если залогинен) */}
            {user?.isAuthenticated == true && (
                <div className='col-3'>
                    {/* 📌 Пользовательские данные (если залогинен) */}
                    <Card className="p-3">
                        <h3>Заметки и ссылки</h3>
                        {/* TODO: Добавить список заметок */}
                        <Button label="Добавить заметку" icon="pi pi-plus" />
                    </Card>
                </div>
            )}
        </div>
    );
};

function ShowTitleInfo(releaseDate: Date | null, expectedReleaseDate: Date | null, firstEpisodeReleaseDate: Date | null,
     lastEpisodeReleaseDate: Date | null, director: string | null, studio: string | null, country: string | null) {
    return (
        <>
            <div className='p-card mb-2'>
                <div className='p-card-body flex flex-column gap-2'>
                    {/*{announceDate && <Tag severity="info" className="cursor-pointer" data-pr-tooltip={`Анонс: ${announceDate}`}>Анонс: {announceDate}</Tag>}*/}
                    {/*{releaseDate && <Tag severity="success" className="cursor-pointer" data-pr-tooltip={`Выход: ${releaseDate}`}>Выход: {releaseDate.toISOString()}</Tag>}*/}
                    {/*<b className='uppercase'>Дата выхода:</b> <span>{releaseDate?.toISOString() ?? '--'}</span>*/}

                    <div>
                        {ShowKeyValue('Дата выхода', releaseDate != null ? DateToString(releaseDate) : null)}
                    </div>
                    <div>
                        {ShowKeyValue('Ожидаемая дата выхода', expectedReleaseDate != null ? DateToString(expectedReleaseDate) : null)}
                    </div>

                    <Divider type="solid" className="py-0" />

                    <div>
                        {ShowKeyValue('Выход первого эпизода', firstEpisodeReleaseDate != null ? DateToString(firstEpisodeReleaseDate) : null)}
                    </div>
                    <div>
                        {ShowKeyValue('Выход последнего эпизода', lastEpisodeReleaseDate != null ? DateToString(lastEpisodeReleaseDate) : null)}
                    </div>
                </div>
            </div>

            <div className='p-card'>
                <div className='p-card-body flex flex-column gap-2'>
                    {/*{announceDate && <Tag severity="info" className="cursor-pointer" data-pr-tooltip={`Анонс: ${announceDate}`}>Анонс: {announceDate}</Tag>}*/}
                    {/*{releaseDate && <Tag severity="success" className="cursor-pointer" data-pr-tooltip={`Выход: ${releaseDate}`}>Выход: {releaseDate.toISOString()}</Tag>}*/}
                    {/*<b className='uppercase'>Дата выхода:</b> <span>{releaseDate?.toISOString() ?? '--'}</span>*/}

                    <div>
                        {ShowKeyValue('Режиссёр', director)}
                    </div>
                    <div>
                        {ShowKeyValue('Студия', studio)}
                    </div>
                    <div>
                        {ShowKeyValue('Страна', country)}
                    </div>
                </div>
            </div>
        </>
    );
}

function  ShowKeyValue(key: string, value: string | null){
    return (
        <>
            <div className='uppercase text-xs text-400 mb-1'>
                <b>{key}</b>
            </div>
            <div className='text-sm'>
                <span className={`text-${value == null ? '100' : 'blue-500'}`}>{value == null ? '--' : value}</span>
            </div>
        </>
    );
}

function ShowGenres(genres: Array<GenreProportion>) {
    const showRadar = genres.length > 2 && genres.length <= 12;
    return (
        <div className='p-card mt-2 border-2 border-100 border-round'>
            <div className='p-card-header  border-bottom-2 border-100 pt-2 pb-1 px-2'>
                <h3 className='m-0'>Жанры</h3>
            </div>
            <div className={`p-card-body flex${showRadar ? ' justify-content-center' : ''} gap-2`}>
                {showRadar ? (
                    // <RadarChart data={animeTitle.commonProperties.genres.map((g) => ({ label: g.genre.name, value: g.proportion ?? 0 }))} />
                    <RadarChart
                        data={genres.map(g => ({ label: g.genre.name, value: g.proportion }))}
                        title="Популярность жанров"
                        maxWidth="35em"
                        scaleMax={10} // Устанавливаем шкалу от 0 до 10
                        chartBackgroundColor='gray'
                        chartBackgroundOpacity={0.15}
                        gridColor="gray"
                        lineColor="green"
                        lineOpacity={0.6}
                        dashedGrid
                        fillOpacity={0.4}
                        fillColor='indigo'
                        ticksColor="white"
                        ticksFontSize={20}
                        labelColor='white'
                        labelFontSize={16}
                    />
                    // можно использовать CSS
                ) : (
                    <div className="flex flex-row flex-wrap gap-2">
                        {
                            React.Children.toArray(
                                (genres).map((item) => {
                                    return (
                                        <Tag key={item.genre.id} className='col-auto' severity="info"
                                             value={item.genre.name}></Tag>
                                    );
                                })
                            )
                        }
                    </div>
                )}
            </div>
        </div>
    );
}

function InvalidateTitle(queryClient: QueryClient) { queryClient.invalidateQueries({ queryKey: [queryKey] }); }