import {
    Calendar,
    Download,
    ExternalLink,
    FileText,
    HardDrive,
    Image as ImageIcon,
    Maximize2,
    Minimize2,
} from 'lucide-react';
import { useState } from 'react';
import { toast } from 'sonner';

import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import {
    Dialog,
    DialogContent,
    DialogDescription,
    DialogHeader,
    DialogTitle,
} from '@/components/ui/dialog';
import { formatDate } from '@/lib/utils';
import type { MediaFile } from '@/types/media';

interface MediaDetailDialogProps {
    media: MediaFile | null;
    open: boolean;
    onOpenChange: (open: boolean) => void;
    onDownload?: () => void;
}

export function MediaDetailDialog({
    media,
    open,
    onOpenChange,
    onDownload,
}: MediaDetailDialogProps) {
    if (!media) {
        return null;
    }

    const openUrl = media.url || media.download_url || null;
    const isImage = media.type === 'image';
    const canEmbedDocument = !isImage && Boolean(media.preview_url);

    const handleDownload = () => {
        if (onDownload) {
            onDownload();
        } else {
            toast.success(`Mengunduh file: ${media.name}`);
        }
    };

    const openInNewTab = () => {
        if (openUrl) {
            window.open(openUrl, '_blank', 'noopener,noreferrer');
        }
    };

    return (
        <Dialog open={open} onOpenChange={onOpenChange}>
            <DialogContent className="flex h-[95vh] w-[95vw] max-w-5xl flex-col overflow-hidden rounded-2xl border-none bg-card p-0 shadow-2xl sm:max-w-5xl [&>button:last-child]:hidden">
                {/* Area pratinjau mengisi sisa ruang vertikal; min-h-0 agar anak
                    yang scroll (iframe/gambar) tidak memaksa dialog melebar. */}
                <div className="min-h-0 flex-1">
                    {/* key memaksa remount saat file ganti → zoom otomatis reset. */}
                    <MediaPreview
                        key={media.id}
                        media={media}
                        isImage={isImage}
                        canEmbedDocument={canEmbedDocument}
                        onOpenInNewTab={openInNewTab}
                        canOpen={Boolean(openUrl)}
                    />
                </div>

                {/* Content Details Area */}
                <div className="flex shrink-0 flex-col gap-4 p-6">
                    <DialogHeader className="gap-1">
                        <div className="flex items-start justify-between gap-4">
                            <DialogTitle
                                className="line-clamp-2 text-lg leading-tight font-bold text-foreground"
                                title={media.name}
                            >
                                {media.name}
                            </DialogTitle>
                            <Badge
                                variant="secondary"
                                className="mt-0.5 shrink-0 capitalize"
                            >
                                {media.type}
                            </Badge>
                        </div>
                        <DialogDescription className="text-sm text-muted-foreground">
                            {media.task_code
                                ? `${media.task_code} - ${media.task_name}`
                                : 'Media file properties and related information.'}
                        </DialogDescription>
                    </DialogHeader>

                    {/* Meta Properties Grid */}
                    <div className="grid grid-cols-2 gap-4 border-y py-4 text-sm">
                        <MetaItem
                            icon={<HardDrive size={18} />}
                            label="File Size"
                            value={media.size}
                        />
                        <MetaItem
                            icon={<Calendar size={18} />}
                            label="Updated"
                            value={formatDate(media.updated_at, {
                                month: 'long',
                                withTime: true,
                            })}
                        />
                    </div>

                    {/* Action Footer */}
                    <div className="flex flex-col gap-2 sm:flex-row sm:justify-end">
                        {openUrl && (
                            <Button
                                variant="outline"
                                onClick={openInNewTab}
                                className="h-10 gap-2"
                            >
                                <ExternalLink size={16} /> Open in tab
                            </Button>
                        )}
                        <Button
                            onClick={handleDownload}
                            className="h-10 gap-2 font-semibold shadow-md"
                        >
                            <Download size={16} /> Download File
                        </Button>
                    </div>
                </div>
            </DialogContent>
        </Dialog>
    );
}

/**
 * Area pratinjau file. Gambar dapat di-zoom (muat ↔ ukuran penuh); dokumen Drive
 * di-embed lewat iframe; sisanya menampilkan ikon dengan ajakan buka di tab.
 */
function MediaPreview({
    media,
    isImage,
    canEmbedDocument,
    onOpenInNewTab,
    canOpen,
}: {
    media: MediaFile;
    isImage: boolean;
    canEmbedDocument: boolean;
    onOpenInNewTab: () => void;
    canOpen: boolean;
}) {
    // Zoom hanya untuk gambar: false = muat ke area (object-contain), true =
    // ukuran penuh dengan scroll agar detail bukti bisa diperiksa.
    const [zoomed, setZoomed] = useState(false);
    const onToggleZoom = () => setZoomed((value) => !value);

    if (isImage && media.preview_url) {
        return (
            <div
                className={`relative flex h-full w-full justify-center bg-muted ${
                    zoomed ? 'items-start overflow-auto' : 'items-center p-4'
                }`}
            >
                <img
                    src={media.preview_url}
                    alt={media.name}
                    onClick={onToggleZoom}
                    className={
                        zoomed
                            ? 'max-w-none cursor-zoom-out'
                            : 'max-h-full cursor-zoom-in rounded-lg object-contain shadow-md'
                    }
                />
                <Button
                    type="button"
                    variant="secondary"
                    size="icon"
                    onClick={onToggleZoom}
                    aria-label={zoomed ? 'Zoom out' : 'Zoom in'}
                    className="absolute top-3 right-3 h-9 w-9 rounded-full shadow-md"
                >
                    {zoomed ? <Minimize2 size={16} /> : <Maximize2 size={16} />}
                </Button>
            </div>
        );
    }

    if (canEmbedDocument) {
        return (
            <iframe
                src={media.preview_url ?? undefined}
                title={`Pratinjau ${media.name}`}
                className="h-full w-full border-b bg-muted"
            />
        );
    }

    // Tak bisa di-preview: tampilkan ikon + ajakan buka di tab (jika ada URL).
    return (
        <div className="flex h-full w-full flex-col items-center justify-center gap-4 bg-muted p-8">
            <div className="flex h-20 w-20 items-center justify-center rounded-2xl bg-amber-50 text-amber-500 shadow-md dark:bg-amber-950/30">
                {media.type === 'document' ? (
                    <FileText size={44} />
                ) : (
                    <ImageIcon size={44} />
                )}
            </div>
            <span className="text-xs font-semibold tracking-wider text-muted-foreground uppercase">
                Pratinjau tidak tersedia
            </span>
            {canOpen && (
                <Button
                    variant="outline"
                    onClick={onOpenInNewTab}
                    className="gap-2"
                >
                    <ExternalLink size={16} /> Open in tab
                </Button>
            )}
        </div>
    );
}

/** Satu baris properti meta (ikon + label + nilai). */
function MetaItem({
    icon,
    label,
    value,
}: {
    icon: React.ReactNode;
    label: string;
    value: string;
}) {
    return (
        <div className="flex items-center gap-3">
            <div className="rounded-lg bg-muted p-2 text-muted-foreground">
                {icon}
            </div>
            <div className="flex min-w-0 flex-col">
                <span className="text-xs text-muted-foreground">{label}</span>
                <span className="truncate font-semibold text-foreground">
                    {value}
                </span>
            </div>
        </div>
    );
}
