import { Head, Link } from '@inertiajs/react';
import { Award, BookOpen, Download, Image as ImageIcon, Loader2 } from 'lucide-react';
import { Button } from '@/components/ui/button';
import AppLayout from '@/layouts/app-layout';
import type { BreadcrumbItem } from '@/types';
import { useState } from 'react';
import html2canvas from 'html2canvas';
import { toast } from 'sonner';

type Course = { id: number; title: string; slug: string; thumbnail: string | null };
type TemplateSettings = {
    background_image: string | null;
    background_image_base64: string | null;
    signature_image: string | null;
    signature_image_base64: string | null;
    border_color: string;
    primary_color: string;
    title: string;
    subtitle: string;
    completion: string;
    signer_name: string;
    signer_title: string;
};
type User = { id: number; name: string };
type Certificate = {
    id: number;
    certificate_number: string;
    issued_at: string;
    issued_at_formatted: string;
    course: Course;
    user: User;
    template_settings: TemplateSettings;
};

type Props = { certificates: Certificate[] };

const breadcrumbs: BreadcrumbItem[] = [{ title: 'Sertifikat', href: '/certificates' }];

function formatDate(date: string): string {
    return new Intl.DateTimeFormat('id-ID', { day: 'numeric', month: 'long', year: 'numeric' }).format(new Date(date));
}

export default function CertificatesIndex({ certificates }: Props) {
    const [downloadingId, setDownloadingId] = useState<number | null>(null);

    const handleDownloadPNG = async (cert: Certificate) => {
        setDownloadingId(cert.id);
        const toastId = toast.loading('Sedang menyiapkan gambar sertifikat...');
        
        try {
            const element = document.getElementById(`cert-download-${cert.id}`);
            if (!element) {
                toast.error('Elemen sertifikat tidak ditemukan', { id: toastId });
                return;
            }

            // Wait for any images (background or signature) to load completely
            const images = element.getElementsByTagName('img');
            const promises = Array.from(images).map((img) => {
                if (img.complete) return Promise.resolve();
                return new Promise((resolve) => {
                    img.onload = resolve;
                    img.onerror = resolve;
                });
            });
            await Promise.all(promises);

            // Capture using html2canvas with 2x scale for high resolution
            const canvas = await html2canvas(element, {
                scale: 2,
                useCORS: true,
                allowTaint: true,
                backgroundColor: null,
                logging: false,
                onclone: (clonedDoc) => {
                    // Remove all stylesheets and style tags to prevent html2canvas from crashing on Tailwind v4's oklch() colors.
                    // This is completely safe since our certificate template uses 100% inline styles.
                    const styleElements = clonedDoc.querySelectorAll('style, link[rel="stylesheet"]');
                    styleElements.forEach(el => el.remove());
                }
            });

            const dataUrl = canvas.toDataURL('image/png');
            const link = document.createElement('a');
            link.download = `Sertifikat_${cert.course.title.replace(/\s+/g, '_')}.png`;
            link.href = dataUrl;
            link.click();
            
            toast.success('Sertifikat berhasil diunduh sebagai gambar!', { id: toastId });
        } catch (error) {
            console.error('Gagal mengunduh gambar sertifikat:', error);
            toast.error('Gagal mengunduh gambar sertifikat. Silakan coba lagi.', { id: toastId });
        } finally {
            setDownloadingId(null);
        }
    };

    return (
        <>
            <Head title="Sertifikat Saya" />

            <div className="mx-auto max-w-6xl flex flex-col gap-6 px-5 py-8">
                <div>
                    <h1 className="text-2xl font-bold">Sertifikat Saya</h1>
                    <p className="text-sm text-muted-foreground">
                        Sertifikat diterbitkan setelah menyelesaikan seluruh lesson
                    </p>
                </div>

                {certificates.length === 0 ? (
                    <div className="rounded-xl border border-dashed p-12 text-center">
                        <Award className="mx-auto mb-3 h-12 w-12 text-muted-foreground/30" />
                        <p className="font-medium">Belum ada sertifikat</p>
                        <p className="mt-1 text-sm text-muted-foreground">
                            Selesaikan semua lesson di kelas untuk mendapatkan sertifikat
                        </p>
                        <Link href="/courses" className="mt-3 inline-block text-sm text-primary hover:underline">
                            Jelajahi kelas
                        </Link>
                    </div>
                ) : (
                    <div className="grid gap-6 sm:grid-cols-2 lg:grid-cols-3">
                        {certificates.map((cert) => (
                            <div
                                key={cert.id}
                                className="flex flex-col rounded-xl border bg-card shadow-sm transition-shadow hover:shadow-md overflow-hidden"
                            >
                                {/* Certificate Live Miniature Preview Header */}
                                <div 
                                    className="w-full aspect-[1.414] relative overflow-hidden bg-white select-none border-b"
                                    style={{
                                        backgroundImage: cert.template_settings.background_image_base64
                                            ? `url(${cert.template_settings.background_image_base64})`
                                            : 'linear-gradient(135deg, #eff6ff 0%, #ffffff 50%, #eff6ff 100%)',
                                        backgroundSize: 'cover',
                                        backgroundPosition: 'center',
                                        backgroundRepeat: 'no-repeat',
                                    }}
                                >
                                    {/* Miniature Corners */}
                                    <div style={{ position: 'absolute', width: '20px', height: '20px', borderColor: cert.template_settings.border_color, borderStyle: 'solid', top: '10px', left: '10px', borderWidth: '1px 0 0 1px' }} />
                                    <div style={{ position: 'absolute', width: '20px', height: '20px', borderColor: cert.template_settings.border_color, borderStyle: 'solid', top: '10px', right: '10px', borderWidth: '1px 1px 0 0' }} />
                                    <div style={{ position: 'absolute', width: '20px', height: '20px', borderColor: cert.template_settings.border_color, borderStyle: 'solid', bottom: '10px', left: '10px', borderWidth: '0 0 1px 1px' }} />
                                    <div style={{ position: 'absolute', width: '20px', height: '20px', borderColor: cert.template_settings.border_color, borderStyle: 'solid', bottom: '10px', right: '10px', borderWidth: '0 1px 1px 0' }} />

                                    {/* Miniature Outer Border */}
                                    <div
                                        className="absolute inset-[5px] flex flex-col justify-between p-3 text-center"
                                        style={{
                                            border: `3px solid ${cert.template_settings.border_color}`,
                                        }}
                                    >
                                        {/* Content */}
                                        <div className="flex flex-col items-center justify-center flex-1">
                                            <p 
                                                className="text-[4px] uppercase tracking-widest font-semibold opacity-85"
                                                style={{ color: cert.template_settings.primary_color }}
                                            >
                                                {cert.template_settings.title}
                                            </p>
                                            <h2 
                                                className="text-[7px] font-bold tracking-tight leading-none mt-0.5"
                                                style={{ color: cert.template_settings.primary_color }}
                                            >
                                                CERTIFICATE OF COMPLETION
                                            </h2>
                                            <div 
                                                className="text-[8px] font-bold border-b-[0.5px] px-2 py-0.5 mt-1 max-w-[80%] truncate"
                                                style={{ 
                                                    color: cert.template_settings.primary_color,
                                                    borderColor: `${cert.template_settings.border_color}60`
                                                }}
                                            >
                                                {cert.user.name}
                                            </div>
                                            <p 
                                                className="text-[6px] font-medium mt-1 truncate max-w-[90%]"
                                                style={{ color: cert.template_settings.primary_color }}
                                            >
                                                {cert.course.title}
                                            </p>
                                        </div>

                                        {/* Footer info */}
                                        <div className="flex justify-between items-end text-[4px] text-muted-foreground opacity-80">
                                            <div className="text-left leading-none scale-[0.9] origin-left">
                                                <div>No: {cert.certificate_number}</div>
                                                <div className="mt-0.5">{cert.issued_at_formatted}</div>
                                            </div>
                                            <div className="text-right leading-none scale-[0.9] origin-right">
                                                <div className="font-semibold">{cert.template_settings.signer_name}</div>
                                                <div className="text-[3px] mt-0.5">{cert.template_settings.signer_title}</div>
                                            </div>
                                        </div>
                                    </div>
                                </div>

                                <div className="flex flex-1 flex-col gap-3 p-4">
                                    <div>
                                        <p className="font-semibold text-sm line-clamp-1">{cert.course.title}</p>
                                        <p className="text-xs text-muted-foreground">
                                            Selesai: {formatDate(cert.issued_at)}
                                        </p>
                                        <p className="mt-1 font-mono text-[10px] text-muted-foreground">
                                            {cert.certificate_number}
                                        </p>
                                    </div>

                                    <div className="mt-auto flex gap-2">
                                        <Link href={`/courses/${cert.course.slug}`} className="flex-1">
                                            <Button variant="outline" size="sm" className="w-full">
                                                <BookOpen className="h-4 w-4" />
                                                Kelas
                                            </Button>
                                        </Link>
                                        <Button
                                            size="sm"
                                            className="flex-1"
                                            onClick={() => handleDownloadPNG(cert)}
                                            disabled={downloadingId === cert.id}
                                        >
                                            {downloadingId === cert.id ? (
                                                <>
                                                    <Loader2 className="h-4 w-4 animate-spin" />
                                                    Memproses...
                                                </>
                                            ) : (
                                                <>
                                                    <Download className="h-4 w-4" />
                                                    Unduh
                                                </>
                                            )}
                                        </Button>
                                    </div>
                                </div>

                                {/* High-resolution off-screen DOM element for html2canvas */}
                                <div
                                    id={`cert-download-${cert.id}`}
                                    style={{
                                        position: 'absolute',
                                        left: '-9999px',
                                        top: '-9999px',
                                        width: '297mm',
                                        height: '210mm',
                                        backgroundColor: '#ffffff',
                                        fontFamily: 'DejaVu Sans, sans-serif',
                                        overflow: 'hidden',
                                        boxSizing: 'border-box',
                                    }}
                                >
                                    <div
                                        style={{
                                            position: 'absolute',
                                            top: 0,
                                            left: 0,
                                            width: '297mm',
                                            height: '210mm',
                                            backgroundImage: cert.template_settings.background_image_base64
                                                ? `url(${cert.template_settings.background_image_base64})`
                                                : 'linear-gradient(135deg, #eff6ff 0%, #ffffff 50%, #eff6ff 100%)',
                                            backgroundSize: 'cover',
                                            backgroundPosition: 'center',
                                            backgroundRepeat: 'no-repeat',
                                        }}
                                    >
                                        {/* Corner Decorations - Inset to match the Blade template exactly */}
                                        <div style={{ position: 'absolute', width: '25mm', height: '25mm', borderColor: cert.template_settings.border_color, borderStyle: 'solid', top: '13mm', left: '13mm', borderWidth: '4px 0 0 4px' }} />
                                        <div style={{ position: 'absolute', width: '25mm', height: '25mm', borderColor: cert.template_settings.border_color, borderStyle: 'solid', top: '13mm', left: '259mm', borderWidth: '4px 4px 0 0' }} />
                                        <div style={{ position: 'absolute', width: '25mm', height: '25mm', borderColor: cert.template_settings.border_color, borderStyle: 'solid', top: '172mm', left: '13mm', borderWidth: '0 0 4px 4px' }} />
                                        <div style={{ position: 'absolute', width: '25mm', height: '25mm', borderColor: cert.template_settings.border_color, borderStyle: 'solid', top: '172mm', left: '259mm', borderWidth: '0 4px 4px 0' }} />

                                        {/* Outer Border Table - Matching the Blade template exactly */}
                                        <table 
                                            style={{
                                                position: 'absolute',
                                                top: '5mm',
                                                left: '5mm',
                                                width: '287mm',
                                                height: '200mm',
                                                border: `12px solid ${cert.template_settings.border_color}`,
                                                borderCollapse: 'collapse',
                                            }}
                                        >
                                            <tbody>
                                                <tr>
                                                    <td style={{ padding: '40px 80px 20px 80px', textAlign: 'center', verticalAlign: 'top' }}>
                                                        <div style={{ marginTop: '15px' }}>
                                                            <h1 style={{ fontSize: '34px', fontWeight: '700', color: cert.template_settings.primary_color, marginBottom: '15px', letterSpacing: '2px', textTransform: 'uppercase' }}>
                                                                {cert.template_settings.title}
                                                            </h1>
                                                            <p style={{ fontSize: '14px', color: '#64748b', marginBottom: '25px' }}>
                                                                {cert.template_settings.subtitle}
                                                            </p>

                                                            <div style={{ fontSize: '32px', fontWeight: '700', color: cert.template_settings.primary_color, borderBottom: `2px solid ${cert.template_settings.border_color}80`, paddingBottom: '8px', display: 'inline-block', minWidth: '400px', marginBottom: '25px' }}>
                                                                {cert.user.name}
                                                            </div>

                                                            <p style={{ fontSize: '14px', color: '#475569', marginBottom: '10px' }}>
                                                                {cert.template_settings.completion}
                                                            </p>
                                                            <p style={{ fontSize: '22px', fontWeight: '700', color: cert.template_settings.primary_color, marginBottom: '20px' }}>
                                                                {cert.course.title}
                                                            </p>
                                                        </div>
                                                    </td>
                                                </tr>
                                                <tr>
                                                    <td style={{ padding: '0 80px 40px 80px', verticalAlign: 'bottom', height: '120px' }}>
                                                        <table style={{ width: '100%', borderCollapse: 'collapse' }}>
                                                            <tbody>
                                                                <tr>
                                                                    <td style={{ width: '50%', textAlign: 'left', verticalAlign: 'bottom' }}>
                                                                        <div style={{ fontSize: '11px', color: '#94a3b8' }}>Nomor Sertifikat</div>
                                                                        <div style={{ fontSize: '12px', color: '#334155', fontWeight: '600', marginBottom: '10px' }}>{cert.certificate_number}</div>
                                                                        <div style={{ fontSize: '11px', color: '#94a3b8' }}>Tanggal Dikeluarkan</div>
                                                                        <div style={{ fontSize: '12px', color: '#334155', fontWeight: '600' }}>{cert.issued_at_formatted}</div>
                                                                    </td>
                                                                    <td style={{ width: '50%', textAlign: 'right', verticalAlign: 'bottom' }}>
                                                                        <div style={{ display: 'inline-block', textAlign: 'center', minWidth: '200px' }}>
                                                                            {cert.template_settings.signature_image_base64 ? (
                                                                                <img src={cert.template_settings.signature_image_base64} style={{ maxHeight: '55px', display: 'block', margin: '0 auto 4px auto' }} alt="Signature" />
                                                                            ) : (
                                                                                <div style={{ height: '55px' }} />
                                                                            )}
                                                                            <div style={{ fontSize: '12px', color: '#334155', fontWeight: '600', borderTop: '1px solid #cbd5e1', paddingTop: '4px', marginTop: '4px', textAlign: 'center' }}>
                                                                                {cert.template_settings.signer_name}
                                                                            </div>
                                                                            <div style={{ fontSize: '11px', color: '#94a3b8', textAlign: 'center' }}>
                                                                                {cert.template_settings.signer_title}
                                                                            </div>
                                                                        </div>
                                                                    </td>
                                                                </tr>
                                                            </tbody>
                                                        </table>
                                                    </td>
                                                </tr>
                                            </tbody>
                                        </table>
                                    </div>
                                </div>
                            </div>
                        ))}
                    </div>
                )}
            </div>
        </>
    );
}

CertificatesIndex.layout = (page: React.ReactNode) => <AppLayout breadcrumbs={breadcrumbs}>{page}</AppLayout>;
