import { useEffect, useState } from 'react';
import { Button, Modal } from '@heroui/react';
import { api } from '@/lib/api';
import {
    CheckCircleIcon,
    MegaphoneIcon,
    WrenchScrewdriverIcon,
    DocumentTextIcon,
    ChevronLeftIcon,
    ChevronRightIcon,
    BookOpenIcon,
    SparklesIcon,
} from '@heroicons/react/24/solid';
import { formatDate } from '@/lib/formatDate';

interface PopupPanduan {
    id: number;
    title: string;
    slug: string;
    category: 'teknis' | 'sop' | 'pengumuman' | 'lainnya';
    excerpt?: string;
    content: string;
    cover_image?: string;
    priority: number;
    created_at: string;
    updated_at: string;
}

const CATEGORY_MAP = {
    teknis: {
        label: 'Panduan Teknis / Tutorial',
        icon: WrenchScrewdriverIcon,
        badge: 'bg-sky-100 text-sky-700',
    },
    sop: {
        label: 'Standar Operasional (SOP)',
        icon: DocumentTextIcon,
        badge: 'bg-emerald-100 text-emerald-700',
    },
    pengumuman: {
        label: 'Pengumuman Penting',
        icon: MegaphoneIcon,
        badge: 'bg-amber-100 text-amber-700',
    },
    lainnya: {
        label: 'Informasi',
        icon: BookOpenIcon,
        badge: 'bg-gray-100 text-gray-700',
    },
};

export default function LoginPanduanModal() {
    const [popups, setPopups] = useState<PopupPanduan[]>([]);
    const [currentIndex, setCurrentIndex] = useState(0);
    const [isOpen, setIsOpen] = useState(false);
    const [loading, setLoading] = useState(false);

    useEffect(() => {
        let isMounted = true;
        api.get<PopupPanduan[]>('/panduans/popups')
            .then((res) => {
                if (isMounted && Array.isArray(res.data) && res.data.length > 0) {
                    setPopups(res.data);
                    setCurrentIndex(0);
                    setIsOpen(true);
                }
            })
            .catch(() => {
                // Silently fail if popups cannot be fetched
            });

        return () => {
            isMounted = false;
        };
    }, []);

    if (!isOpen || popups.length === 0) {
        return null;
    }

    const currentItem = popups[currentIndex];
    const categoryInfo = CATEGORY_MAP[currentItem?.category] || CATEGORY_MAP.teknis;
    const CategoryIcon = categoryInfo.icon;
    const total = popups.length;

    const handleDismiss = async () => {
        if (!currentItem) return;
        setLoading(true);
        try {
            await api.post(`/panduans/${currentItem.id}/dismiss`);
            const nextList = popups.filter((_, idx) => idx !== currentIndex);
            setPopups(nextList);
            if (nextList.length === 0) {
                setIsOpen(false);
            } else if (currentIndex >= nextList.length) {
                setCurrentIndex(nextList.length - 1);
            }
        } catch {
            setIsOpen(false);
        } finally {
            setLoading(false);
        }
    };

    return (
        <Modal isOpen={isOpen} onOpenChange={setIsOpen}>
            <Modal.Backdrop>
                <Modal.Container>
                    <Modal.Dialog className="max-w-2xl w-full bg-gray-50">
                        <Modal.Header className="flex-row! items-center gap-3 pb-3 mb-2 border-b border-gray-200">
                            <Modal.Icon className="bg-amber-100 text-amber-600">
                                <SparklesIcon className="w-5 h-5" />
                            </Modal.Icon>
                            <div className="flex-1 min-w-0">
                                <div className="flex items-center gap-2">
                                    <span className={`px-2 py-0.5 rounded-full text-[11px] font-semibold ${categoryInfo.badge}`}>
                                        {categoryInfo.label}
                                    </span>
                                    {total > 1 && (
                                        <span className="text-xs font-medium text-gray-500 bg-gray-200/70 px-2 py-0.5 rounded-full">
                                            {currentIndex + 1} dari {total}
                                        </span>
                                    )}
                                </div>
                                <Modal.Heading className="text-lg font-bold text-gray-900 mt-1 truncate">
                                    {currentItem.title}
                                </Modal.Heading>
                            </div>
                        </Modal.Header>
                        <Modal.CloseTrigger />

                        <Modal.Body className="overflow-x-hidden">
                            <div className="max-h-[62vh] overflow-y-auto overflow-x-hidden space-y-4 pr-1 break-words">
                                {currentItem.cover_image && (
                                    <div className="w-full aspect-[16/9] max-h-64 rounded-xl overflow-hidden border border-gray-200 shadow-2xs bg-gray-100">
                                        <img
                                            src={currentItem.cover_image}
                                            alt={currentItem.title}
                                            className="w-full h-full object-cover object-center"
                                        />
                                    </div>
                                )}

                                <div className="text-sm text-gray-500">
                                    Dipublikasikan pada {formatDate(currentItem.created_at)}
                                </div>

                                <div
                                    className="prose prose-sky max-w-none text-gray-800 text-[15px] leading-[1.5] break-words [overflow-wrap:anywhere] [&_p]:leading-[1.5] [&_p]:break-words [&_li]:leading-[1.5] [&_pre]:overflow-x-auto [&_table]:overflow-x-auto prose-headings:font-bold prose-headings:text-gray-900 prose-img:rounded-xl prose-img:shadow-2xs prose-img:max-w-full"
                                    dangerouslySetInnerHTML={{ __html: currentItem.content }}
                                />
                            </div>
                        </Modal.Body>

                        <Modal.Footer className="border-t border-gray-200 pt-3 mt-2 flex flex-wrap items-center justify-between gap-2">
                            <div className="flex items-center gap-1.5 flex-wrap">
                                {total > 1 && (
                                    <>
                                        <button
                                            type="button"
                                            onClick={() => setCurrentIndex((idx) => Math.max(0, idx - 1))}
                                            disabled={currentIndex === 0}
                                            className="p-1.5 border border-gray-300 rounded-lg text-gray-600 hover:bg-white disabled:opacity-30 transition cursor-pointer"
                                            title="Sebelumnya"
                                        >
                                            <ChevronLeftIcon className="w-4 h-4" />
                                        </button>
                                        <button
                                            type="button"
                                            onClick={() => setCurrentIndex((idx) => Math.min(total - 1, idx + 1))}
                                            disabled={currentIndex === total - 1}
                                            className="p-1.5 border border-gray-300 rounded-lg text-gray-600 hover:bg-white disabled:opacity-30 transition cursor-pointer"
                                            title="Selanjutnya"
                                        >
                                            <ChevronRightIcon className="w-4 h-4" />
                                        </button>
                                    </>
                                )}
                                <Button
                                    variant="outline"
                                    onPress={() => {
                                        setIsOpen(false);
                                        window.location.href = `/panduan/${currentItem.id}`;
                                    }}
                                    className="text-sm"
                                >
                                    <BookOpenIcon className="w-4 h-4 text-sky-600" />
                                    <span>Lihat Penuh</span>
                                </Button>
                                <Button
                                    variant="outline"
                                    onPress={() => setIsOpen(false)}
                                    className="text-sm"
                                >
                                    Tutup
                                </Button>
                            </div>

                            <Button
                                variant="primary"
                                onPress={handleDismiss}
                                isDisabled={loading}
                                className="text-sm"
                            >
                                <CheckCircleIcon className="w-4 h-4" />
                                <span>Saya Sudah Membaca & Mengerti</span>
                            </Button>
                        </Modal.Footer>
                    </Modal.Dialog>
                </Modal.Container>
            </Modal.Backdrop>
        </Modal>
    );
}
