'use client';

import { useEffect, useRef, useState } from 'react';
import QRCode from 'qrcode';
import { pb } from '~/lib/pocketbase';
import { ImageOff, Upload, Link, X } from 'lucide-react';

type InputMode = 'url' | 'file';

export default function Dashboard() {
    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(() => {
        fetchAssets();
    }, []);

    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 {
            // Build FormData so we can send files + fields in one request
            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);
        }
    };

    return (
        <div className='min-h-screen bg-gray-50 px-6 py-10'>
            <div className='mx-auto max-w-5xl space-y-10'>
                <div>
                    <h1 className='text-3xl font-bold text-gray-900'>
                        AR Asset Dashboard
                    </h1>
                    <p className='mt-1 text-gray-500'>
                        Manage 3D assets and generate AR QR codes
                    </p>
                </div>

                <div className='rounded-2xl bg-white p-6 shadow-sm'>
                    <h2 className='mb-5 text-lg font-semibold text-gray-800'>
                        Create New Asset
                    </h2>

                    <div className='space-y-5 text-black'>
                        {/* Asset Name */}
                        <div className='space-y-1'>
                            <label className='text-xs font-semibold text-gray-600 ml-1'>Asset Name</label>
                            <input
                                className='w-full rounded-lg border border-gray-300 px-4 py-2 text-sm focus:border-black focus:outline-none'
                                placeholder='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 inline-flex items-center justify-center gap-2 rounded-xl bg-black px-6 py-2.5 text-sm font-medium text-white transition hover:bg-gray-800 disabled:cursor-not-allowed disabled:opacity-60'
                    >
                        {loading ? (
                            <>
                                <div className='w-3.5 h-3.5 rounded-full border-2 border-white/30 border-t-white animate-spin' />
                                Creating…
                            </>
                        ) : 'Create Asset'}
                    </button>
                </div>

                <div>
                    <h2 className='mb-4 text-lg font-semibold text-gray-800'>
                        Generated Assets
                    </h2>

                    {assets.length === 0 ? (
                        <p className='text-sm text-gray-500'>
                            No assets created yet.
                        </p>
                    ) : (
                        <div className='grid grid-cols-1 gap-6 sm:grid-cols-2 md:grid-cols-3'>
                            {assets.map((asset) => (
                                <div
                                    key={asset.id}
                                    className='rounded-2xl bg-white p-5 shadow-sm transition hover:shadow-md bg-radial-[at_0%_0%] to-70% from-black/20 to-transparent '
                                >
                                    <h3 className='mb-3 text-base font-semibold text-gray-900'>
                                        {asset?.name}
                                    </h3>

                                    {asset?.qr_image ? (
                                        <img
                                            src={pb.files.getURL(asset, asset.qr_image)}
                                            alt={asset?.name}
                                            className='mx-auto w-40 rounded-lg'
                                        />
                                    ) : (
                                        asset?.qr_file ? (
                                            <img
                                                src={pb.files.getURL(asset, asset.qr_file)}
                                                alt={asset?.name}
                                                className='mx-auto w-40 rounded-lg'
                                            />
                                        ) : <div className='mx-auto flex h-40 w-40 flex-col items-center justify-center space-y-2 rounded-lg bg-gray-50 text-gray-400'>
                                            <ImageOff size={32} strokeWidth={1.5} />
                                            <span className='text-xs font-medium'>No QR Image</span>
                                        </div>
                                    )}
                                </div>
                            ))}
                        </div>
                    )}
                </div>
            </div>
        </div>
    );
}

// ─── Reusable File-or-URL field ───────────────────────────────────────────────
interface FileOrUrlFieldProps {
    label: string;
    required?: boolean;
    mode: InputMode;
    onModeChange: (m: InputMode) => void;
    accept: string;
    file: File | null;
    onFileChange: (f: File | null) => void;
    inputRef: React.RefObject<HTMLInputElement | null>;
    url: string;
    onUrlChange: (u: string) => void;
    urlPlaceholder: string;
}

function FileOrUrlField({
    label, required, mode, onModeChange,
    accept, file, onFileChange, inputRef,
    url, onUrlChange, urlPlaceholder,
}: FileOrUrlFieldProps) {
    return (
        <div className='space-y-1.5'>
            {/* Label + toggle */}
            <div className='flex items-center justify-between ml-1'>
                <label className='text-xs font-semibold text-gray-600'>
                    {label}{required && <span className='text-red-500 ml-0.5'>*</span>}
                </label>
                <div className='flex items-center gap-1 rounded-lg border border-gray-200 p-0.5 text-xs'>
                    <button
                        type='button'
                        onClick={() => onModeChange('file')}
                        className={`flex items-center gap-1 rounded-md px-2.5 py-1 transition-all font-medium ${
                            mode === 'file'
                                ? 'bg-black text-white'
                                : 'text-gray-500 hover:text-gray-800'
                        }`}
                    >
                        <Upload size={11} />
                        Upload
                    </button>
                    <button
                        type='button'
                        onClick={() => onModeChange('url')}
                        className={`flex items-center gap-1 rounded-md px-2.5 py-1 transition-all font-medium ${
                            mode === 'url'
                                ? 'bg-black text-white'
                                : 'text-gray-500 hover:text-gray-800'
                        }`}
                    >
                        <Link size={11} />
                        URL
                    </button>
                </div>
            </div>

            {mode === 'file' ? (
                <div
                    onClick={() => inputRef.current?.click()}
                    className={`flex cursor-pointer items-center gap-3 rounded-lg border-2 border-dashed px-4 py-3 transition-colors ${
                        file ? 'border-black bg-gray-50' : 'border-gray-200 hover:border-gray-400'
                    }`}
                >
                    <input
                        ref={inputRef}
                        type='file'
                        accept={accept}
                        className='hidden'
                        onChange={(e) => onFileChange(e.target.files?.[0] ?? null)}
                    />
                    {file ? (
                        <>
                            <div className='flex flex-1 items-center gap-2 min-w-0'>
                                <div className='w-7 h-7 rounded bg-black flex items-center justify-center shrink-0'>
                                    <Upload size={13} className='text-white' />
                                </div>
                                <span className='text-sm text-gray-800 font-medium truncate'>{file.name}</span>
                                <span className='text-xs text-gray-400 shrink-0'>
                                    {(file.size / 1024 / 1024).toFixed(1)} MB
                                </span>
                            </div>
                            <button
                                type='button'
                                onClick={(e) => {
                                    e.stopPropagation();
                                    onFileChange(null);
                                    if (inputRef.current) inputRef.current.value = '';
                                }}
                                className='shrink-0 text-gray-400 hover:text-gray-700'
                            >
                                <X size={15} />
                            </button>
                        </>
                    ) : (
                        <div className='flex flex-1 items-center gap-3 text-gray-400'>
                            <Upload size={16} />
                            <span className='text-sm'>Click to choose a file <span className='text-gray-300'>({accept})</span></span>
                        </div>
                    )}
                </div>
            ) : (
                <input
                    type='url'
                    className='w-full rounded-lg border border-gray-300 px-4 py-2 text-sm focus:border-black focus:outline-none'
                    placeholder={urlPlaceholder}
                    value={url}
                    onChange={(e) => onUrlChange(e.target.value)}
                />
            )}
        </div>
    );
}
