import React, {useEffect, useState} from 'react';
import {makeGetRequest, makePostRequest} from '@/lib/request';
import FilePondUploader from '@/components/FilePondUploader';
import {notify} from '@/lib/notify';
import AppPageHeader from "@/components/AppPageHeader";
import MainLayout from "@/layouts/MainLayout";
import {usePage} from "@inertiajs/react";
import axios from 'axios';

export default function Documents(): JSX.Element {
    const {auth} = usePage<{ auth: { user: any } }>().props;
    const token = auth?.user?.token ?? auth?.user?.api_token ?? undefined;

    /* ── list state ── */
    const [docs, setDocs] = useState<any[]>([]);
    const [loading, setLoading] = useState(false);
    const [query, setQuery] = useState('');
    const [page, setPage] = useState(1);
    const [meta, setMeta] = useState<any>(null);

    /* ── detail modal state ── */
    const [selected, setSelected] = useState<any | null>(null);
    const [downloading, setDownloading] = useState<number | null>(null);

    /* ── access modal state (independent from detail) ── */
    const [accessDoc, setAccessDoc] = useState<any | null>(null);   // the document whose access we manage
    const [accessUsers, setAccessUsers] = useState<any[]>([]);
    const [accessUserQuery, setAccessUserQuery] = useState('');
    const [accessUserLoading, setAccessUserLoading] = useState(false);
    const [accessSelectedUserId, setAccessSelectedUserId] = useState<number | null>(null);
    const [accessPermission, setAccessPermission] = useState<'view' | 'edit'>('view');
    const [accessSubmitting, setAccessSubmitting] = useState(false);

    /* ── create document modal state ── */
    const [createOpen, setCreateOpen] = useState(false);
    const [creating, setCreating] = useState(false);
    const [title, setTitle] = useState('');
    const [documentType, setDocumentType] = useState('');
    const [clientMatterId, setClientMatterId] = useState<number | null>(null);
    const [isConfidential, setIsConfidential] = useState(false);
    const [matters, setMatters] = useState<any[]>([]);
    const [uploadFile, setUploadFile] = useState<File | null>(null);
    const [errors, setErrors] = useState<Record<string, string[]>>({});

    useEffect(() => { fetchMatters(); }, []);
    useEffect(() => { fetchDocs(); }, [page, query]);

    useEffect(() => {
        const t = setTimeout(() => setPage(1), 300);
        return () => clearTimeout(t);
    }, [query]);

    /* user search inside access modal */
    useEffect(() => {
        if (!accessDoc) return;
        let mounted = true;
        const t = setTimeout(async () => {
            setAccessUserLoading(true);
            try {
                const params = new URLSearchParams({per_page: '50'});
                if (accessUserQuery) params.append('search', accessUserQuery);
                const res = await makeGetRequest(`/api/users?${params}`, {token});
                const payload = res.data?.result ?? res.data ?? {};
                const list = payload?.data ?? payload ?? [];
                if (mounted) setAccessUsers(Array.isArray(list) ? list : []);
            } catch {
                if (mounted) setAccessUsers([]);
            } finally {
                if (mounted) setAccessUserLoading(false);
            }
        }, 300);
        return () => { mounted = false; clearTimeout(t); };
    }, [accessUserQuery, accessDoc, token]);

    /* ── fetch helpers ── */
    async function fetchMatters() {
        try {
            const res = await makeGetRequest(`/api/matters?per_page=200`, {token});
            const payload = res.data?.result ?? res.data ?? {};
            const list = payload?.data ?? payload ?? [];
            setMatters(Array.isArray(list) ? list : []);
        } catch { /* ignore */ }
    }

    async function fetchDocs() {
        setLoading(true);
        try {
            const params = new URLSearchParams({page: String(page)});
            if (query) params.append('search', query);
            const res = await makeGetRequest(`/api/documents?${params}`, {token});
            const payload = res.data?.result ?? res.data ?? {};
            const list = payload?.data ?? payload ?? [];
            setDocs(Array.isArray(list) ? list : []);
            const m = payload?.meta ?? (payload?.data ? {
                current_page: payload.current_page ?? page,
                last_page: payload.last_page ?? 1,
                total: payload.total ?? 0,
            } : null);
            setMeta(m);
        } catch (e) {
            console.warn('Failed to fetch documents', e);
        } finally {
            setLoading(false);
        }
    }

    /** Load full document (with versions) into detail modal */
    const openDetail = async (d: any) => {
        try {
            const res = await makeGetRequest(`/api/documents/${d.id}`, {token});
            const payload = res.data?.result ?? res.data ?? {};
            setSelected(payload);
        } catch (e: any) {
            notify.toastErrorMessage(e?.response?.data?.message || 'Failed to load document');
        }
    };

    const refreshSelected = () => selected && openDetail(selected);
    const closeDetail = () => setSelected(null);
    const gotoPage = (p: number) => {
        if (p < 1 || p > (meta?.last_page ?? p)) return;
        setPage(p);
    };

    /* ── delete ── */
    const deleteDocument = async (d: any) => {
        if (!confirm(`Delete "${d.title}"? This cannot be undone.`)) return;
        try {
            await axios.delete(`/api/documents/${d.id}`, {
                headers: token ? {Authorization: `Bearer ${token}`} : {},
            });
            notify.toastSuccessMessage('Document deleted');
            fetchDocs();
        } catch (e: any) {
            notify.toastErrorMessage(e?.response?.data?.message || 'Failed to delete document');
        }
    };

    /* ── rollback ── */
    const rollback = async (versionId: number) => {
        if (!selected || !confirm('Roll back to this version?')) return;
        try {
            await makePostRequest(`/api/documents/${selected.id}/versions/${versionId}/rollback`, {}, {token});
            notify.toastSuccessMessage('Rolled back successfully');
            refreshSelected();
        } catch (e: any) {
            notify.toastErrorMessage(e?.response?.data?.message || 'Rollback failed');
        }
    };

    /* ── authenticated download ── */
    const download = async (v: any) => {
        if (downloading) return;
        setDownloading(v.id);
        try {
            const res = await axios.get(`/api/documents/${selected.id}/versions/${v.id}`, {
                responseType: 'blob',
                headers: token ? {Authorization: `Bearer ${token}`} : {},
            });
            const url = URL.createObjectURL(new Blob([res.data]));
            const a = document.createElement('a');
            a.href = url;
            a.download = v.file_name ?? `version-${v.version}`;
            document.body.appendChild(a);
            a.click();
            a.remove();
            URL.revokeObjectURL(url);
        } catch {
            notify.toastErrorMessage('Download failed');
        } finally {
            setDownloading(null);
        }
    };

    /* ── access modal — opened directly from row ── */
    const openAccessModal = async (d: any) => {
        setAccessDoc(null);
        setAccessUserQuery('');
        setAccessSelectedUserId(null);
        setAccessPermission('view');
        // load full document (with accesses)
        try {
            const res = await makeGetRequest(`/api/documents/${d.id}`, {token});
            const payload = res.data?.result ?? res.data ?? {};
            setAccessDoc(payload);
        } catch (e: any) {
            notify.toastErrorMessage(e?.response?.data?.message || 'Failed to load document');
        }
    };

    const refreshAccessDoc = () => accessDoc && openAccessModal(accessDoc);
    const closeAccessModal = () => { setAccessDoc(null); setAccessUsers([]); };

    const grantAccess = async () => {
        if (!accessDoc || !accessSelectedUserId) { alert('Select a user'); return; }
        setAccessSubmitting(true);
        try {
            await makePostRequest(
                `/api/documents/${accessDoc.id}/access`,
                {user_id: accessSelectedUserId, permission: accessPermission},
                {token}
            );
            notify.toastSuccessMessage('Access granted');
            setAccessSelectedUserId(null);
            setAccessUserQuery('');
            refreshAccessDoc();
        } catch (e: any) {
            notify.toastErrorMessage(e?.response?.data?.message || 'Failed to grant access');
        } finally {
            setAccessSubmitting(false);
        }
    };

    const revokeAccess = async (userId: number) => {
        if (!accessDoc || !confirm('Revoke this user\'s access?')) return;
        try {
            await axios.delete(`/api/documents/${accessDoc.id}/access`, {
                data: {user_id: userId},
                headers: token ? {Authorization: `Bearer ${token}`} : {},
            });
            notify.toastSuccessMessage('Access revoked');
            refreshAccessDoc();
        } catch (e: any) {
            notify.toastErrorMessage(e?.response?.data?.message || 'Failed to revoke access');
        }
    };

    /* ── create document ── */
    const openCreate = () => {
        setCreateOpen(true);
        setTitle(''); setDocumentType(''); setClientMatterId(null);
        setIsConfidential(false); setUploadFile(null); setErrors({});
    };
    const closeCreate = () => setCreateOpen(false);

    const submitCreate = async () => {
        setErrors({});
        if (!uploadFile) { alert('Select a file'); return; }
        if (!title || !documentType || !clientMatterId) { alert('Please fill title, type and matter'); return; }
        setCreating(true);
        try {
            const form = new FormData();
            form.append('file', uploadFile);
            form.append('title', title);
            form.append('document_type', documentType);
            form.append('client_matter_id', String(clientMatterId));
            form.append('is_confidential', isConfidential ? '1' : '0');
            const {data} = await makePostRequest('/api/documents', form as any, {token});
            notify.toastSuccessMessage('Document uploaded');
            window.dispatchEvent(new CustomEvent('document:created', {detail: data.result ?? data}));
            closeCreate();
            fetchDocs();
        } catch (err: any) {
            const resp = err?.response?.data;
            if (resp?.errors) setErrors(resp.errors);
            else notify.toastErrorMessage(resp?.message || 'Failed to upload document');
        } finally {
            setCreating(false);
        }
    };

    const handleCreateSubmit = (e: React.FormEvent) => { e.preventDefault(); submitCreate(); };

    /* ─────────────────────── RENDER ─────────────────────── */
    return (
        <div className="grid grid-cols-12 gap-6">
            <div className="col-span-12">
                <div className="box">
                    <div className="box-body">

                        {/* toolbar */}
                        <div className="flex justify-between mb-5">
                            <div className="relative sm:max-w-xs max-w-[210px]">
                                <label htmlFor="hs-table-search" className="sr-only">Search</label>
                                <div className="absolute inset-y-0 end-0 flex items-center pointer-events-none pe-4">
                                    <i className="ti ti-search"></i>
                                </div>
                                <input type="text" id="hs-table-search" className="p-2 pe-10 ti-form-input"
                                    placeholder="Search documents" value={query}
                                    onChange={e => setQuery(e.target.value)}/>
                            </div>
                            <button type="button" className="ti-btn ti-btn-primary py-2 px-3 whitespace-nowrap"
                                onClick={openCreate}>
                                <i className="ri ri-upload-cloud-line mr-2"></i> Upload Document
                            </button>
                        </div>

                        {/* table */}
                        <div className="rounded-sm overflow-auto w-full">
                            <table className="ti-custom-table w-full">
                                <thead className="bg-gray-100">
                                <tr>
                                    <th>Title</th>
                                    <th>Matter</th>
                                    <th>Uploaded By</th>
                                    <th>Version</th>
                                    <th className="!text-end">Actions</th>
                                </tr>
                                </thead>
                                <tbody>
                                {loading
                                    ? <tr><td colSpan={5} className="text-center py-8">Loading...</td></tr>
                                    : docs.length === 0
                                        ? <tr><td colSpan={5} className="text-center py-8">No documents found.</td></tr>
                                        : docs.map(d => (
                                            <tr key={d.id}>
                                                <td className="text-indigo-600 font-medium">{d.title}</td>
                                                <td>{d.matter?.reference_number ?? d.matter?.name ?? '-'}</td>
                                                <td>{d.uploader?.name ?? '-'}</td>
                                                <td>{d.current_version ?? '-'}</td>
                                                <td className="text-end space-x-1">
                                                    {/* View / versions */}
                                                    <button onClick={() => openDetail(d)}
                                                        className="hs-tooltip-toggle w-8 h-8 ti-btn rounded-full p-0 transition-none focus:outline-none ti-btn-soft-primary"
                                                        title="View versions">
                                                        <i className="ti ti-eye"></i>
                                                    </button>
                                                    {/* Access management */}
                                                    <button onClick={() => openAccessModal(d)}
                                                        className="hs-tooltip-toggle w-8 h-8 ti-btn rounded-full p-0 transition-none focus:outline-none ti-btn-soft-secondary"
                                                        title="Manage access">
                                                        <i className="ti ti-users"></i>
                                                    </button>
                                                    {/* Delete */}
                                                    <button onClick={() => deleteDocument(d)}
                                                        className="hs-tooltip-toggle w-8 h-8 ti-btn rounded-full p-0 transition-none focus:outline-none ti-btn-soft-danger"
                                                        title="Delete document">
                                                        <i className="ti ti-trash"></i>
                                                    </button>
                                                </td>
                                            </tr>
                                        ))
                                }
                                </tbody>
                            </table>
                        </div>

                        {/* pagination */}
                        <div className="flex items-center justify-between mt-4">
                            <div className="text-sm text-gray-600">showing {docs?.length} of {meta?.total ?? 0} items</div>
                            <div className="flex items-center gap-2">
                                <button onClick={() => gotoPage((meta?.current_page ?? 1) - 1)}
                                    disabled={(meta?.current_page ?? 1) <= 1} className="px-2 py-1 border rounded">Prev</button>
                                {Array.from({length: meta?.last_page ?? 1}).map((_, i) => {
                                    const p = i + 1;
                                    return <button key={p} onClick={() => gotoPage(p)}
                                        className={`px-2 py-1 border rounded ${p === (meta?.current_page ?? page) ? 'bg-indigo-600 text-white' : ''}`}>{p}</button>;
                                })}
                                <button onClick={() => gotoPage((meta?.current_page ?? 1) + 1)}
                                    disabled={(meta?.current_page ?? 1) >= (meta?.last_page ?? 1)} className="px-2 py-1 border rounded">Next</button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            {/* ── Document detail modal (versions only) ── */}
            {selected && (
                <div role="dialog" aria-modal="true"
                    className="fixed inset-0 z-50 flex items-center justify-center bg-black/40 backdrop-blur-sm p-4">
                    <div className="bg-white rounded-xl shadow-xl w-full max-w-2xl max-h-[85vh] flex flex-col">

                        <div className="flex items-center justify-between px-5 py-4 border-b shrink-0">
                            <div>
                                <h3 className="text-base font-semibold">{selected.title}
                                    {selected.is_confidential && <span className="ml-2 text-xs bg-red-100 text-red-700 px-2 py-0.5 rounded">Confidential</span>}
                                </h3>
                                <p className="text-xs text-gray-500 mt-0.5">{selected.matter?.reference_number ?? ''} · {selected.document_type}</p>
                            </div>
                            <button onClick={closeDetail} className="p-1.5 text-gray-400 hover:text-gray-600 hover:bg-gray-100 rounded transition-colors">
                                <i className="ri ri-close-line text-lg"></i>
                            </button>
                        </div>

                        <div className="overflow-auto px-5 py-4 space-y-6">
                            {/* version history */}
                            <div>
                                <h4 className="font-medium mb-2">Version History</h4>
                                <ul className="divide-y border rounded">
                                    {(selected.versions ?? []).length === 0
                                        ? <li className="p-3 text-sm text-gray-500">No versions yet.</li>
                                        : [...(selected.versions ?? [])].reverse().map((v: any) => (
                                            <li key={v.id} className="p-3 flex items-center justify-between gap-4">
                                                <div className="min-w-0">
                                                    <div className="font-medium flex items-center gap-2">
                                                        {v.version}
                                                        {v.is_current && <span className="text-xs bg-green-100 text-green-700 px-1.5 py-0.5 rounded">current</span>}
                                                    </div>
                                                    <div className="text-xs text-gray-500 truncate">
                                                        {new Date(v.created_at).toLocaleString()} · {v.uploader?.name ?? '-'} · {v.file_name}
                                                    </div>
                                                </div>
                                                <div className="flex items-center gap-2 shrink-0">
                                                    <button onClick={() => download(v)} disabled={downloading === v.id}
                                                        className="ti-btn ti-btn-sm ti-btn-soft-primary" title="Download">
                                                        {downloading === v.id
                                                            ? <span className="animate-spin h-3 w-3 border-2 border-current border-t-transparent rounded-full inline-block"></span>
                                                            : <i className="ti ti-download"></i>}
                                                    </button>
                                                    {!v.is_current && (
                                                        <button onClick={() => rollback(v.id)}
                                                            className="ti-btn ti-btn-sm ti-btn-soft-warning" title="Roll back to this version">
                                                            <i className="ti ti-history"></i>
                                                        </button>
                                                    )}
                                                </div>
                                            </li>
                                        ))
                                    }
                                </ul>
                            </div>

                            {/* upload new version */}
                            <div>
                                <h4 className="font-medium mb-2">Upload New Version</h4>
                                <FilePondUploader
                                    url={`/api/documents/${selected.id}/versions`}
                                    onSuccess={() => { notify.toastSuccessMessage('Version uploaded'); refreshSelected(); }}
                                    onError={() => notify.toastErrorMessage('Version upload failed')}
                                />
                            </div>
                        </div>
                    </div>
                </div>
            )}

            {/* ── Access Management modal (opened from row button) ── */}
            {accessDoc && (
                <div role="dialog" aria-modal="true"
                    className="fixed inset-0 z-50 flex items-center justify-center bg-black/40 backdrop-blur-sm p-4">
                    <div className="bg-white rounded-xl shadow-xl w-full max-w-lg max-h-[85vh] flex flex-col">

                        <div className="flex items-center justify-between px-5 py-4 border-b border-gray-200 shrink-0">
                            <div>
                                <h3 className="text-base font-semibold text-gray-800">Document Access</h3>
                                <p className="text-xs text-gray-500 mt-0.5">{accessDoc.title}</p>
                            </div>
                            <button type="button" onClick={closeAccessModal}
                                className="p-1.5 text-gray-400 hover:text-gray-600 hover:bg-gray-100 rounded transition-colors">
                                <i className="ri ri-close-line text-lg"></i>
                            </button>
                        </div>

                        <div className="overflow-auto px-5 py-5 space-y-5">

                            {/* current access list */}
                            <div>
                                <h4 className="text-sm font-semibold text-gray-700 mb-2">Users with access</h4>
                                {(accessDoc.accesses ?? []).length === 0
                                    ? <p className="text-sm text-gray-500">No users have been granted access yet.</p>
                                    : (
                                        <ul className="divide-y border rounded">
                                            {accessDoc.accesses.map((a: any) => (
                                                <li key={a.id} className="p-3 flex items-center justify-between">
                                                    <div>
                                                        <div className="text-sm font-medium">{a.user?.name ?? `User #${a.user_id}`}</div>
                                                        <div className="text-xs text-gray-500 capitalize">{a.permission}</div>
                                                    </div>
                                                    <button onClick={() => revokeAccess(a.user_id)}
                                                        className="ti-btn ti-btn-sm ti-btn-soft-danger" title="Revoke access">
                                                        <i className="ti ti-user-minus"></i>
                                                    </button>
                                                </li>
                                            ))}
                                        </ul>
                                    )
                                }
                            </div>

                            {/* grant access */}
                            <div className="border-t pt-4">
                                <h4 className="text-sm font-semibold text-gray-700 mb-3">Grant access to a user</h4>
                                <div className="space-y-3">
                                    <div>
                                        <label className="block text-sm font-medium text-gray-700 mb-1">Search user</label>
                                        <input type="text"
                                            className="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-indigo-500"
                                            placeholder="Name or email"
                                            value={accessUserQuery}
                                            onChange={e => setAccessUserQuery(e.target.value)}/>
                                        {accessUserLoading && <div className="text-xs text-gray-500 mt-1">Loading...</div>}
                                        {!accessUserLoading && accessUsers.length > 0 && (
                                            <ul className="mt-2 max-h-36 overflow-auto border rounded">
                                                {accessUsers.map(u => (
                                                    <li key={u.id}
                                                        className={`p-2 cursor-pointer hover:bg-gray-50 ${accessSelectedUserId === u.id ? 'bg-indigo-50 border-l-2 border-indigo-500' : ''}`}
                                                        onClick={() => setAccessSelectedUserId(u.id)}>
                                                        <div className="text-sm font-medium">{u.name}</div>
                                                        <div className="text-xs text-gray-500">{u.email}</div>
                                                    </li>
                                                ))}
                                            </ul>
                                        )}
                                    </div>
                                    <div>
                                        <label className="block text-sm font-medium text-gray-700 mb-1">Permission level</label>
                                        <select className="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-indigo-500"
                                            value={accessPermission}
                                            onChange={e => setAccessPermission(e.target.value as 'view' | 'edit')}>
                                            <option value="view">View only</option>
                                            <option value="edit">Edit</option>
                                        </select>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <div className="flex items-center justify-end gap-2 px-5 py-4 border-t border-gray-200 shrink-0">
                            <button onClick={closeAccessModal}
                                className="px-4 py-2 text-sm text-gray-600 border border-gray-300 rounded-lg hover:bg-gray-50 transition-colors">
                                Close
                            </button>
                            <button onClick={grantAccess} disabled={accessSubmitting || !accessSelectedUserId}
                                className="flex items-center gap-1.5 px-4 py-2 text-sm bg-indigo-600 text-white rounded-lg hover:bg-indigo-700 disabled:opacity-60 font-medium">
                                {accessSubmitting
                                    ? <><span className="animate-spin h-3 w-3 border-2 border-white border-t-transparent rounded-full inline-block"></span> Granting…</>
                                    : <><i className="ti ti-user-plus"></i> Grant Access</>}
                            </button>
                        </div>
                    </div>
                </div>
            )}

            {/* ── Create Document modal ── */}
            {createOpen && (
                <div role="dialog" aria-modal="true"
                    className="fixed inset-0 z-50 flex items-center justify-center bg-black/40 backdrop-blur-sm p-4">
                    <div className="bg-white rounded-xl shadow-xl w-full max-w-md">
                        <form className="space-y-3" onSubmit={handleCreateSubmit} noValidate>
                            <div className="flex items-center justify-between px-5 py-4 border-b border-gray-200">
                                <h3 className="text-base font-semibold text-gray-800">Upload Document</h3>
                                <button type="button" onClick={closeCreate}
                                    className="p-1.5 text-gray-400 hover:text-gray-600 hover:bg-gray-100 rounded transition-colors">
                                    <i className="ri ri-close-line text-lg"></i>
                                </button>
                            </div>
                            <div className="px-5 py-5 space-y-4">
                                <div>
                                    <label htmlFor="doc_title" className="block text-sm font-medium text-gray-700 mb-1">Title</label>
                                    <input id="doc_title" type="text" value={title} onChange={e => setTitle(e.target.value)}
                                        className="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-indigo-500"
                                        placeholder="Document title"/>
                                    {errors.title && <p className="text-sm text-red-600 mt-1">{errors.title[0]}</p>}
                                </div>
                                <div>
                                    <label htmlFor="doc_type" className="block text-sm font-medium text-gray-700 mb-1">Document Type</label>
                                    <input id="doc_type" type="text" value={documentType} onChange={e => setDocumentType(e.target.value)}
                                        className="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-indigo-500"
                                        placeholder="e.g. Contract, Pleading"/>
                                    {errors.document_type && <p className="text-sm text-red-600 mt-1">{errors.document_type[0]}</p>}
                                </div>
                                <div>
                                    <label htmlFor="matter" className="block text-sm font-medium text-gray-700 mb-1">Matter</label>
                                    <select id="matter" value={clientMatterId ?? ''}
                                        onChange={e => setClientMatterId(e.target.value ? Number(e.target.value) : null)}
                                        className="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-indigo-500">
                                        <option value="">Select matter</option>
                                        {matters.map(m => <option key={m.id} value={m.id}>{m.reference_number ?? m.name}</option>)}
                                    </select>
                                    {errors.client_matter_id && <p className="text-sm text-red-600 mt-1">{errors.client_matter_id[0]}</p>}
                                </div>
                                <div className="flex items-center gap-3">
                                    <input id="conf" type="checkbox" checked={isConfidential} onChange={e => setIsConfidential(e.target.checked)}/>
                                    <label htmlFor="conf" className="text-sm">Mark as confidential (partner only)</label>
                                </div>
                                <div>
                                    <label className="block text-sm font-medium text-gray-700 mb-1">File</label>
                                    <FilePondUploader instantUpload={false} onAddFile={f => setUploadFile(f)}/>
                                    {errors.file && <p className="text-sm text-red-600 mt-1">{errors.file[0]}</p>}
                                </div>
                            </div>
                            <div className="flex items-center justify-end gap-2 px-5 py-4 border-t border-gray-200">
                                <button type="button" onClick={closeCreate}
                                    className="px-4 py-2 text-sm text-gray-600 border border-gray-300 rounded-lg hover:bg-gray-50 transition-colors">
                                    Cancel
                                </button>
                                <button type="submit" disabled={creating}
                                    className="flex items-center gap-1.5 px-4 py-2 text-sm bg-indigo-600 text-white rounded-lg hover:bg-indigo-700 disabled:opacity-60 font-medium">
                                    {creating
                                        ? <><span className="animate-spin h-3 w-3 border-2 border-white border-t-transparent rounded-full inline-block"></span> Uploading…</>
                                        : 'Upload'}
                                </button>
                            </div>
                        </form>
                    </div>
                </div>
            )}
        </div>
    );
}

