'use client';

import { useEffect, useRef, useState } from 'react';
import { useNavigate } from 'react-router';
import QRCode from 'qrcode';
import { pb } from '~/lib/pocketbase';
import { ImageOff, LogOut, FileCode } from 'lucide-react';
import { FileOrUrlField, type InputMode } from '~/components/FileOrUrlField';

export default function Dashboard() {
    const navigate = useNavigate();
    const [authCheckComplete, setAuthCheckComplete] = useState(false);
    const [name, setName] = useState('');

    // GLB
    const [glbMode, setGlbMode] = useState<InputMode>('file');
    const [glbUrl, setGlbUrl] = useState('');
    const [glbFile, setGlbFile] = useState<File | null>(null);
    const glbInputRef = useRef<HTMLInputElement>(null);

    // USDZ
    const [usdzMode, setUsdzMode] = useState<InputMode>('file');
    const [usdzUrl, setUsdzUrl] = useState('');
    const [usdzFile, setUsdzFile] = useState<File | null>(null);
    const usdzInputRef = useRef<HTMLInputElement>(null);

    const [assets, setAssets] = useState<any[]>([]);
    const [loading, setLoading] = useState(false);

    const fetchAssets = async () => {
        try {
            const records = await pb.collection('ar_assets').getFullList({
                sort: '-created',
            });
            setAssets(records);
        } catch (err) {
            console.error('Failed to fetch assets:', err);
            setAssets([]);
        }
    };

    useEffect(() => {
        if (!pb.authStore.isValid) {
            navigate('/login', { replace: true });
        } else {
            setAuthCheckComplete(true);
            fetchAssets();
        }
    }, [navigate]);

    const handleLogout = () => {
        pb.authStore.clear();
        navigate('/login', { replace: true });
    };

    const createAsset = async () => {
        const hasGlb = glbMode === 'file' ? !!glbFile : !!glbUrl.trim();
        if (!name.trim() || !hasGlb) {
            alert('Please provide a name and a GLB file or URL');
            return;
        }

        setLoading(true);

        try {
            const formData = new FormData();
            formData.append('name', name.trim());

            if (glbMode === 'file' && glbFile) {
                formData.append('glb_file', glbFile);
            } else {
                formData.append('glb_url', glbUrl.trim());
            }

            if (usdzMode === 'file' && usdzFile) {
                formData.append('usdz_file', usdzFile);
            } else if (usdzMode === 'url' && usdzUrl.trim()) {
                formData.append('usdz_url', usdzUrl.trim());
            }

            const record = await pb.collection('ar_assets').create(formData);

            const qrUrl = `${import.meta.env.VITE_FRONTEND_URL}/ar/${record.id}`;

            const qrImage = await QRCode.toDataURL(qrUrl, {
                width: 512,
                margin: 2,
            });

            const qrBlob = await (await fetch(qrImage)).blob();

            const qrFormData = new FormData();
            qrFormData.append('qr_url', qrUrl);
            qrFormData.append('qr_image', new File([qrBlob], `${record.id}.png`, { type: 'image/png' }));

            await pb.collection('ar_assets').update(record.id, qrFormData);

            // Reset all fields
            setName('');
            setGlbUrl('');
            setGlbFile(null);
            setUsdzUrl('');
            setUsdzFile(null);
            if (glbInputRef.current) glbInputRef.current.value = '';
            if (usdzInputRef.current) usdzInputRef.current.value = '';

            fetchAssets();
        } catch (err: any) {
            alert(err?.message || 'Failed to create asset');
        } finally {
            setLoading(false);
        }
    };

    if (!authCheckComplete) {
        return (
            <div className="fixed inset-0 bg-[#0D0D0D] flex flex-col items-center justify-center">
                <div className="w-10 h-10 rounded-full border-2 border-orange-500/20 border-t-orange-500 animate-spin mb-4" />
                <p className="text-white/40 text-xs tracking-widest uppercase">Checking authorization…</p>
            </div>
        );
    }

    return (
        <div className='min-h-screen bg-[#0D0D0D] text-white px-6 py-10 font-sans selection:bg-orange-500/20'>
            <div className='mx-auto max-w-5xl space-y-10'>
                {/* Header */}
                <div className='flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4 border-b border-neutral-900 pb-6'>
                    <div className='flex items-center gap-4'>
                        <div className="w-10 h-10 bg-black border border-neutral-800 rounded-xl flex items-center justify-center shrink-0">
                            <span className="text-orange-500 font-extrabold text-2xl pl-0.5 select-none">t.</span>
                        </div>
                        <div>
                            <h1 className='text-2xl font-bold tracking-tight text-white'>
                                AR Asset Dashboard
                            </h1>
                            <p className='text-xs text-neutral-500 mt-0.5 uppercase tracking-wider'>
                                Manage 3D assets and generate AR QR codes
                            </p>
                        </div>
                    </div>
                    <div className='flex items-center gap-3'>
                        {pb.authStore.model?.email && (
                            <span className='text-xs text-orange-500 border border-orange-500/20 bg-orange-500/5 px-3 py-1.5 rounded-full font-semibold select-none'>
                                {pb.authStore.model.email}
                            </span>
                        )}
                        <button
                            onClick={handleLogout}
                            className='inline-flex items-center gap-2 rounded-xl bg-[#121212] border border-neutral-800 px-4 py-2 text-sm font-medium text-neutral-400 hover:text-white hover:border-orange-500/50 hover:bg-neutral-900 shadow-sm transition-all duration-200 cursor-pointer'
                        >
                            <LogOut size={15} />
                            <span>Sign Out</span>
                        </button>
                    </div>
                </div>

                {/* Form Card */}
                <div className='rounded-2xl bg-[#121212] border border-neutral-900 p-6 shadow-2xl'>
                    <h2 className='mb-5 text-base font-bold text-white uppercase tracking-wider text-orange-500'>
                        Create New Asset
                    </h2>

                    <div className='space-y-5'>
                        {/* Asset Name */}
                        <div className='space-y-1.5'>
                            <label className='text-xs font-bold text-neutral-400 uppercase tracking-wider ml-1'>
                                Asset Name
                            </label>
                            <input
                                className='w-full bg-[#181818] border border-neutral-800 rounded-xl px-4 py-3 text-sm text-white placeholder-neutral-600 focus:border-orange-500 focus:outline-none transition-colors duration-200'
                                placeholder='Enter asset name'
                                value={name}
                                onChange={(e) => setName(e.target.value)}
                            />
                        </div>

                        {/* GLB — Android / Web */}
                        <FileOrUrlField
                            label='GLB File (Android / Web)'
                            required
                            mode={glbMode}
                            onModeChange={setGlbMode}
                            accept='.glb'
                            file={glbFile}
                            onFileChange={setGlbFile}
                            inputRef={glbInputRef}
                            url={glbUrl}
                            onUrlChange={setGlbUrl}
                            urlPlaceholder='https://example.com/model.glb'
                        />

                        {/* USDZ — iOS */}
                        <FileOrUrlField
                            label='USDZ File (iOS) — Optional'
                            mode={usdzMode}
                            onModeChange={setUsdzMode}
                            accept='.usdz,.reality'
                            file={usdzFile}
                            onFileChange={setUsdzFile}
                            inputRef={usdzInputRef}
                            url={usdzUrl}
                            onUrlChange={setUsdzUrl}
                            urlPlaceholder='https://example.com/model.usdz'
                        />
                    </div>

                    <button
                        onClick={createAsset}
                        disabled={loading}
                        className='mt-6 w-full sm:w-auto inline-flex items-center justify-center gap-2 rounded-xl bg-orange-500 px-6 py-3 text-sm font-bold text-black hover:bg-orange-400 shadow-[0_0_24px_rgba(249,115,22,0.2)] hover:shadow-[0_0_32px_rgba(249,115,22,0.35)] transition-all duration-200 active:scale-[0.98] disabled:cursor-not-allowed disabled:opacity-60 disabled:shadow-none'
                    >
                        {loading ? (
                            <>
                                <div className='w-3.5 h-3.5 rounded-full border-2 border-black/30 border-t-black animate-spin' />
                                Creating Asset…
                            </>
                        ) : 'Create Asset'}
                    </button>
                </div>

                {/* Grid Header */}
                <div>
                    <h2 className='mb-5 text-base font-bold text-neutral-400 uppercase tracking-wider ml-1'>
                        Generated Assets
                    </h2>

                    {assets.length === 0 ? (
                        <div className="text-center py-12 rounded-2xl bg-[#121212]/50 border border-dashed border-neutral-800">
                            <FileCode size={36} className="mx-auto text-neutral-600 mb-3" />
                            <p className='text-sm text-neutral-500'>
                                No assets created yet. Upload a model above to get started.
                            </p>
                        </div>
                    ) : (
                        <div className='grid grid-cols-1 gap-6 sm:grid-cols-2 md:grid-cols-3'>
                            {assets.map((asset) => (
                                <div
                                    key={asset.id}
                                    className='group rounded-2xl bg-gradient-to-b from-[#141414] to-[#0D0D0D] border border-neutral-900 p-5 hover:border-orange-500/30 transition-all duration-300 shadow-lg'
                                >
                                    <h3 className='mb-4 text-sm font-bold text-white group-hover:text-orange-500 transition-colors truncate'>
                                        {asset?.name}
                                    </h3>

                                    <div className="bg-white p-3.5 rounded-xl flex items-center justify-center max-w-[190px] mx-auto shadow-md">
                                        {asset?.qr_image ? (
                                            <img
                                                src={pb.files.getURL(asset, asset.qr_image)}
                                                alt={asset?.name}
                                                className='w-full aspect-square rounded-lg object-contain'
                                            />
                                        ) : (
                                            asset?.qr_file ? (
                                                <img
                                                    src={pb.files.getURL(asset, asset.qr_file)}
                                                    alt={asset?.name}
                                                    className='w-full aspect-square rounded-lg object-contain'
                                                />
                                            ) : (
                                                <div className='flex aspect-square w-full flex-col items-center justify-center space-y-2 text-neutral-400 bg-neutral-100 rounded-lg p-4'>
                                                    <ImageOff size={28} strokeWidth={1.5} className="text-neutral-400" />
                                                    <span className='text-[10px] font-semibold uppercase tracking-wider text-neutral-500'>No QR Image</span>
                                                </div>
                                            )
                                        )}
                                    </div>
                                </div>
                            ))}
                        </div>
                    )}
                </div>
            </div>
        </div>
    );
}

