import { FC } from 'react';
import {UserInfo} from "../../api/models/AccountTypes.tsx";
import {AnimeTitleShort} from "../../api/models/Types.tsx";
import RatingComponent from "../../components/RatingComponent.tsx";
import {GetTitleNames} from "../../components/library/NameComponent.tsx";
import {GetDate} from "../../common/Helper.tsx";
import { Tooltip } from 'primereact/tooltip';
import { FaEye, FaUser, FaUsers } from 'react-icons/fa6';
import { Divider } from 'primereact/divider';
import React from 'react';
import { Tag } from 'primereact/tag';
import { useNavigate } from 'react-router-dom';

interface IAnimeCardProps {
    item: AnimeTitleShort;
    user: UserInfo | null | undefined;
    setRate: (value: number | null) => Promise<string | undefined>;
    deleteRate: () => Promise<string | undefined>;
    forceRefresh?: () => void | null | undefined;
    editingRateId: string | null | undefined,
    setEditingRateId: (itemId: string | null) => void,
}

const AnimeItem: FC<IAnimeCardProps> = ({ item, user, setRate, deleteRate, forceRefresh, editingRateId, setEditingRateId }) => {
    const navigate = useNavigate();
    // const name = GetName(item.names, user?.languageId)?.nameInUserLanguage ?? 'Нет названия';
    const name = GetTitleNames(item.names, user?.languageId)?.titleElement;
    
    const viewDetail = () => navigate(`/library/anime/${item.id}`);

    return (
        <>
            <div className='h-full p-card p-component flex flex-column'>
                {/* Заголовок */}
                {/*<div className='p-card-header surface-100 px-3 border-round-md border-noround-bottom overflow-y-scroll'*/}
                {/*     style={{ height: '3.9em' }}*/}
                {/*     onClick={viewDetail}>*/}
                {/*    <h3 className='py-2 my-0'>{name}</h3>*/}
                {/*</div>*/}
                <div className="p-card-header surface-100 px-3 border-round-md border-noround-bottom overflow-y-scroll cursor-pointer"
                     style={{ height: '3.9em' }}
                     onClick={viewDetail}>
                    <h3 className="py-2 my-0 hover:text-indigo-300 hover:underline">
                        {name}
                    </h3>
                </div>


                {/* Основное содержимое (растягивается, чтобы футер оставался внизу) */}
                <div className='p-card-body p-2 pt-1 flex-grow-1'>
                    <RatingComponent
                        rateObjectId={item.id}
                        ratePercentage={item.rate}
                        userRatePercentage={item.myRate}
                        isEditing={editingRateId === item.id}
                        setIsEditing={setEditingRateId}
                        setRate={setRate}
                        deleteRate={deleteRate}
                        forceRefresh={forceRefresh}
                    />
                    <div className='grid px-2'>
                        <div className='col-12 sm:col-6 lg:col-12 xl:col-6'>
                            {item.preview?.url && (
                                <img src={item.preview.url} alt={item.id} className="w-full h-auto border-round anime-image cursor-pointer"
                                     style={{ maxWidth: '20em' }}
                                     onClick={viewDetail}/>
                            )}
                        </div>
                        <div className='col-12 sm:col-6 lg:col-12 xl:col-6'>
                            <h4 className='my-0 px-2 grid gap-2 justify-content-start'><b className='col-auto'>Выходит:</b>{GetReleaseDates(GetDate(item.releaseDate), GetDate(null), item.completed)}</h4>
                            <h4 className='my-2'><strong>Страна:</strong> пока нет</h4>
                            <h4 className='my-2'><strong>Режиссёр:</strong> пока нет</h4>
                            <h4 className='my-2'><strong>Студия:</strong> пока нет</h4>
                            <h4 className='my-2'><strong>Сезоны:</strong> {item.seasonsCount}</h4>
                            <h4 className='my-2'><strong>Эпизоды:</strong> {item.episodesInsideSeasonsCount + (item.episodesCount > 0 ? (' + ' + item.episodesCount) : '')}</h4>
                        </div>
                        <div className='col-12'>
                            {/* Жанры */}
                            <h4 className='my-2'><strong>Жанры:</strong></h4>
                            <div className='flex flex-row flex-wrap gap-2 w-full'>
                                {
                                    React.Children.toArray(
                                        (item.genres).map((item) => {
                                            return (
                                                <Tag key={item.genre.id} className='col-auto' severity="info" value={item.genre.name}></Tag>
                                            );
                                        })
                                    )
                                }

                                {(item.names.find(q => q.value.startsWith('Арифурэта')) != null) && (
                                    <>
                                        {
                                            React.Children.toArray(
                                                (item.genres).map((item) => {
                                                    return (
                                                        <Tag key={`${item.genre.id}1`} className='col-auto' severity="secondary" value={item.genre.name}></Tag>
                                                    );
                                                })
                                            )
                                        }
                                        {
                                            React.Children.toArray(
                                                (item.genres).map((item) => {
                                                    return (
                                                        <Tag key={`${item.genre.id}2`} className='col-auto' severity="secondary" value={item.genre.name}></Tag>
                                                    );
                                                })
                                            )
                                        }
                                        {
                                            React.Children.toArray(
                                                (item.genres).map((item) => {
                                                    return (
                                                        <Tag key={`${item.genre.id}3`} className='col-auto' severity="secondary" value={item.genre.name}></Tag>
                                                    );
                                                })
                                            )
                                        }
                                    </>
                                )}
                            </div>
                        </div>
                    </div>
                </div>

                {/* Футер (фиксированно внизу) */}
                <div className='p-card-footer surface-50 p-0 border-round-md border-noround-top'>
                    <div className='grid justify-content-between gap-2 m-0'>
                        {GetAnimeTitleYear(GetDate(item.releaseDate), GetDate(item.expectedReleaseDate))}
                        <h4 className='py-2 my-0 pl-2 pr-3 col-auto flex align-items-center surface-100
                            border-round-md border-noround-top border-noround-left'>
                            <FaEye className='text-cyan-500' />
                            <Divider layout='vertical' type='solid' className='py-0 mx-2' />
                            <FaUser className='text-300'/> <span className='ml-1'>{item.myViews ?? 0}</span>
                            <Divider layout='vertical' type='dashed' className='py-0 mx-2' />
                            <FaUsers className='text-300'/> <span className='ml-1'>{item.views ?? '–'}</span>
                        </h4>
                    </div>
                </div>
            </div>

            {/*<div className="anime-card p-3 surface-overlay border-round flex flex-column align-items-center">*/}
            {/*    /!* Картинка *!/*/}
            {/*    {item.preview?.url && (*/}
            {/*        <img src={item.preview.url} alt={item.id} className="w-full border-round anime-image" />*/}
            {/*    )}*/}
            
            {/*    /!* Название *!/*/}
            {/*    /!*<h3 className="mt-2">{name}</h3>*!/*/}
            {/*    {name}*/}
            
            {/*    /!* Рейтинг *!/*/}
            {/*    <RatingComponent*/}
            {/*        rateObjectId={item.id}*/}
            {/*        ratePercentage={item.rate}*/}
            {/*        userRatePercentage={item.myRate}*/}
            {/*        isEditing={editingRateId === item.id}*/}
            {/*        setIsEditing={setEditingRateId}*/}
            {/*        setRate={setRate}*/}
            {/*        deleteRate={deleteRate}*/}
            {/*        forceRefresh={forceRefresh}*/}
            {/*    />*/}
            
            {/*    /!* Дата выхода *!/*/}
            {/*    <p><strong>Год выхода:</strong> {releaseYear}</p>*/}
            
            {/*    /!* Жанры *!/*/}
            {/*    <p><strong>Жанры:</strong> {genres}</p>*/}
            
            {/*    <Button label="Подробнее" icon="pi pi-info-circle" className="p-button-rounded p-button-outlined mt-2" />*/}
            {/*</div>*/}
        </>
    );
};

function GetReleaseDates(firstEpisodeReleaseDate: Date | null | undefined, lastEpisodeReleaseDate: Date | null | undefined, isCompleted: boolean) {
    const formatDate = (date: Date) => date.toLocaleDateString("ru-RU", { year: "numeric", month: "2-digit", day: "2-digit" });
    const formatYearMonth = (date: Date) => date.toLocaleDateString("ru-RU", { year: "numeric", month: "2-digit" }).replace("/", ".");

    const firstEpisodeReleaseYearMonth = firstEpisodeReleaseDate ? formatYearMonth(firstEpisodeReleaseDate) : null;
    const lastEpisodeReleaseYearMonth = (lastEpisodeReleaseDate && isCompleted) ? formatYearMonth(lastEpisodeReleaseDate ) : null;
    const firstEpisodeReleaseFormatted = firstEpisodeReleaseDate ? formatDate(firstEpisodeReleaseDate) : null;
    const lastEpisodeReleaseFormatted = (lastEpisodeReleaseDate && isCompleted) ? formatDate(lastEpisodeReleaseDate)
        : ('настоящее время' + (lastEpisodeReleaseDate ? `, последний эпизод: ${formatDate(lastEpisodeReleaseDate)}` : ''));

    return (
        <div className="col-auto grid px-2 my-0 align-items-center justify-content-between gap-2">
            <span className="col-auto font-italic first-episode-release-date"
                  data-pr-tooltip={firstEpisodeReleaseFormatted == null ? '' : (firstEpisodeReleaseFormatted +
                      ((isCompleted && lastEpisodeReleaseDate != null && firstEpisodeReleaseYearMonth === lastEpisodeReleaseYearMonth) ?
                          ` – ${lastEpisodeReleaseFormatted}` : '')
                  )}>
                {firstEpisodeReleaseYearMonth ?? 'нет данных'}
            </span>
            <Tooltip target=".first-episode-release-date" />
            {((firstEpisodeReleaseYearMonth != null && !lastEpisodeReleaseYearMonth != null) &&
                    (firstEpisodeReleaseYearMonth !== lastEpisodeReleaseYearMonth || (!isCompleted && firstEpisodeReleaseYearMonth === lastEpisodeReleaseYearMonth))) &&
                <>
                    <span className="col-auto font-bold">
                        – 
                    </span>
                    <span className="col-auto font-italic last-episode-release-date" data-pr-tooltip={lastEpisodeReleaseFormatted}>
                        {lastEpisodeReleaseYearMonth ?? "..."}
                    </span>
                    <Tooltip target=".last-episode-release-date" />
                </>
            }
        </div>
    );
}

function GetAnimeTitleYear(releaseDate: Date | null | undefined, estimatedReleaseDate: Date | null | undefined){
    const releaseYear = releaseDate?.getFullYear();
    const estimatedReleaseYear = estimatedReleaseDate?.getFullYear();

    // const releaseYear = item.releaseDate ? new Date(item.releaseDate).getFullYear() : '—';
    return (
        <h4 className={'py-2 my-0 mx-3 col-auto text-' + (releaseYear ? 'primary'
            : estimatedReleaseYear ? '300 font-light' : '100')}>{releaseYear ? releaseYear
            : estimatedReleaseYear ? estimatedReleaseYear : '—'}</h4>
    );
}

export default AnimeItem;