import { useState, useEffect } from 'react';
import {
    FileText, Search, Plus, Clock, User, Check, X,
    AlertCircle, Eye, Edit, FolderOpen, Book,
    ClipboardList, FileCheck, History, Download, Loader2,
    LucideIcon
} from 'lucide-react';
import { documentsApi, Document, DocumentType, DocumentStatus, DocumentVersion } from '../lib/documentsApi';
import { PageHeader, EmptyState, CardSkeleton } from '../components/ui/LinearPrimitives';

const TYPE_CONFIG: Record<DocumentType, { icon: LucideIcon; badge: string; label: string }> = {
    SOP: { icon: Book, badge: 'badge-accent', label: 'SOP' },
    POLICY: { icon: FileCheck, badge: 'badge-accent', label: 'Policy' },
    FORM: { icon: ClipboardList, badge: 'badge-accent', label: 'Form' },
    CHECKLIST: { icon: Check, badge: 'badge-success', label: 'Checklist' },
    TRAINING: { icon: Book, badge: 'badge-success', label: 'Training' },
    OTHER: { icon: FileText, badge: 'badge', label: 'Document' }
};


const STATUS_CONFIG: Record<DocumentStatus, { badge: string; label: string }> = {
    DRAFT: { badge: 'badge', label: 'Draft' },
    PENDING_APPROVAL: { badge: 'badge-warning', label: 'Pending' },
    APPROVED: { badge: 'badge-success', label: 'Approved' },
    ARCHIVED: { badge: 'badge-destructive', label: 'Archived' }
};

export default function DocumentsPage() {
    const [documents, setDocuments] = useState<Document[]>([]);
    const [loading, setLoading] = useState(true);
    const [searchTerm, setSearchTerm] = useState('');
    const [filterType, setFilterType] = useState<DocumentType | ''>('');
    const [filterStatus, setFilterStatus] = useState<DocumentStatus | ''>('');
    const [selectedDoc, setSelectedDoc] = useState<Document | null>(null);
    const [versions, setVersions] = useState<DocumentVersion[]>([]);
    const [showVersions, setShowVersions] = useState(false);
    const [pendingAcks, setPendingAcks] = useState<Document[]>([]);

    useEffect(() => {
        loadDocuments();
        loadPendingAcks();
    }, [filterType, filterStatus]);

    async function loadDocuments() {
        setLoading(true);
        try {
            const docs = await documentsApi.getDocuments({
                type: filterType || undefined,
                status: filterStatus || undefined,
                search: searchTerm || undefined
            });
            setDocuments(docs);
        } catch (error) {
            console.error('Failed to load documents:', error);
        } finally {
            setLoading(false);
        }
    }

    async function loadPendingAcks() {
        try {
            const pending = await documentsApi.getPendingAcks();
            setPendingAcks(pending);
        } catch (error) {
            console.error('Failed to load pending acks:', error);
        }
    }

    async function handleViewDocument(doc: Document) {
        setSelectedDoc(doc);
        try {
            const vers = await documentsApi.getVersions(doc.id);
            setVersions(vers);
        } catch (error) {
            console.error('Failed to load versions:', error);
        }
    }

    async function handleAcknowledge(docId: string) {
        try {
            await documentsApi.acknowledgeDocument(docId);
            setPendingAcks(prev => prev.filter(d => d.id !== docId));
            if (selectedDoc?.id === docId) {
                const updated = await documentsApi.getDocument(docId);
                setSelectedDoc(updated);
            }
        } catch (error) {
            console.error('Failed to acknowledge:', error);
        }
    }

    // Filter documents by search term
    const filteredDocs = documents.filter(doc => {
        if (searchTerm && !doc.title.toLowerCase().includes(searchTerm.toLowerCase())) {
            return false;
        }
        return true;
    });

    // Group by type for display
    const groupedDocs = filteredDocs.reduce((acc, doc) => {
        const typeLabel = TYPE_CONFIG[doc.type]?.label || doc.type;
        if (!acc[typeLabel]) acc[typeLabel] = [];
        acc[typeLabel].push(doc);
        return acc;
    }, {} as Record<string, Document[]>);

    return (
        <div className="space-y-6 pb-20 animate-in">
            <PageHeader
                title="SOP Library"
                subtitle="Standard Operating Procedures & Compliance"
                actions={
                    <button className="btn btn-primary">
                        <Plus size={16} />
                        <span className="hidden sm:inline">New Document</span>
                    </button>
                }
            />

            {/* Pending Acknowledgements Banner */}
            {pendingAcks.length > 0 && (
                <div className="card p-4 border-warning/50 bg-warning-muted">
                    <div className="flex items-center gap-3">
                        <AlertCircle className="text-warning flex-shrink-0" size={20} />
                        <div className="flex-1">
                            <p className="font-medium text-primary text-sm">
                                {pendingAcks.length} document{pendingAcks.length > 1 ? 's require' : ' requires'} acknowledgement
                            </p>
                            <p className="text-xs text-secondary">Review to remain compliant</p>
                        </div>
                        <button
                            onClick={() => handleViewDocument(pendingAcks[0])}
                            className="btn btn-primary text-xs h-8"
                        >
                            Review
                        </button>
                    </div>
                </div>
            )}

            {/* Filters */}
            <div className="flex flex-wrap gap-3">
                <div className="relative flex-1 min-w-[200px]">
                    <Search className="absolute left-3 top-1/2 -translate-y-1/2 text-tertiary" size={16} />
                    <input
                        type="text"
                        placeholder="Search documents..."
                        value={searchTerm}
                        onChange={(e) => setSearchTerm(e.target.value)}
                        className="input w-full pl-9"
                    />
                </div>
                <select
                    value={filterType}
                    onChange={(e) => setFilterType(e.target.value as DocumentType | '')}
                    className="input"
                >
                    <option value="">All Types</option>
                    <option value="SOP">SOPs</option>
                    <option value="POLICY">Policies</option>
                    <option value="TRAINING">Training</option>
                    <option value="FORM">Forms</option>
                    <option value="CHECKLIST">Checklists</option>
                    <option value="OTHER">Other</option>
                </select>
                <select
                    value={filterStatus}
                    onChange={(e) => setFilterStatus(e.target.value as DocumentStatus | '')}
                    className="input"
                >
                    <option value="">All Statuses</option>
                    <option value="APPROVED">Approved</option>
                    <option value="PENDING_APPROVAL">Pending</option>
                    <option value="DRAFT">Draft</option>
                    <option value="ARCHIVED">Archived</option>
                </select>
            </div>

            {/* Documents Grid */}
            {loading ? (
                <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-3">
                    {Array.from({ length: 6 }).map((_, i) => <CardSkeleton key={i} />)}
                </div>
            ) : filteredDocs.length === 0 ? (
                <EmptyState
                    icon={FolderOpen}
                    title="No documents found"
                    description="Create your first document or adjust filters."
                />
            ) : (
                <div className="space-y-6">
                    {Object.entries(groupedDocs).map(([category, docs]) => (
                        <div key={category}>
                            <h3 className="text-xs font-medium text-tertiary uppercase tracking-wider mb-3 flex items-center gap-2">
                                <FolderOpen size={12} />
                                {category}
                                <span className="text-tertiary">({docs.length})</span>
                            </h3>
                            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-3">
                                {docs.map(doc => {
                                    const typeConfig = TYPE_CONFIG[doc.type];
                                    const TypeIcon = typeConfig.icon;
                                    const statusConfig = STATUS_CONFIG[doc.status];
                                    const isPending = pendingAcks.some(p => p.id === doc.id);

                                    return (
                                        <div
                                            key={doc.id}
                                            onClick={() => handleViewDocument(doc)}
                                            className={`
                                                card card-interactive p-4 cursor-pointer
                                                ${isPending ? 'ring-1 ring-warning/50' : ''}
                                            `}
                                        >
                                            <div className="flex items-start gap-3">
                                                <div className="w-9 h-9 rounded-md bg-accent-muted flex items-center justify-center flex-shrink-0">
                                                    <TypeIcon size={16} className="text-accent" />
                                                </div>
                                                <div className="flex-1 min-w-0">
                                                    <h4 className="font-medium text-primary text-sm truncate">
                                                        {doc.title}
                                                    </h4>
                                                    <p className="text-xs text-tertiary mt-0.5">
                                                        {typeConfig.label} · v{doc.version}
                                                    </p>
                                                </div>
                                                {isPending && (
                                                    <span className="w-2 h-2 bg-warning rounded-full animate-pulse flex-shrink-0" />
                                                )}
                                            </div>

                                            <div className="flex items-center justify-between mt-3 pt-3 border-t border-subtle">
                                                <span className={`${statusConfig.badge} text-[10px]`}>
                                                    {statusConfig.label}
                                                </span>
                                                <div className="flex items-center gap-1 text-[10px] text-tertiary">
                                                    <Clock size={10} />
                                                    {new Date(doc.updatedAt).toLocaleDateString()}
                                                </div>
                                            </div>
                                        </div>
                                    );
                                })}
                            </div>
                        </div>
                    ))}
                </div>
            )}

            {/* Document Viewer Modal */}
            {selectedDoc && (
                <div className="fixed inset-0 bg-black/50 flex items-center justify-center p-4 z-50 animate-fade-in" onClick={() => setSelectedDoc(null)}>
                    <div
                        className="card max-w-4xl w-full max-h-[90vh] overflow-hidden flex flex-col animate-scale-in"
                        onClick={e => e.stopPropagation()}
                    >
                        {/* Modal Header */}
                        <div className="p-4 border-b border-subtle flex justify-between items-start">
                            <div className="flex items-start gap-3">
                                <div className="w-10 h-10 rounded-md bg-accent-muted flex items-center justify-center">
                                    {(() => {
                                        const Icon = TYPE_CONFIG[selectedDoc.type].icon;
                                        return <Icon size={20} className="text-accent" />;
                                    })()}
                                </div>
                                <div>
                                    <h3 className="text-lg font-semibold text-primary">{selectedDoc.title}</h3>
                                    <p className="text-xs text-tertiary">
                                        {TYPE_CONFIG[selectedDoc.type].label} · Version {selectedDoc.version}
                                    </p>
                                </div>
                            </div>
                            <div className="flex items-center gap-1">
                                <button
                                    onClick={() => setShowVersions(!showVersions)}
                                    className={`btn btn-ghost p-2 ${showVersions ? 'text-accent bg-accent-muted' : ''}`}
                                    title="Version History"
                                >
                                    <History size={16} />
                                </button>
                                <button
                                    onClick={() => setSelectedDoc(null)}
                                    className="btn btn-ghost p-2"
                                >
                                    <X size={16} />
                                </button>
                            </div>
                        </div>

                        {/* Status Bar */}
                        <div className="px-4 py-2 bg-tertiary border-b border-subtle flex items-center justify-between text-xs">
                            <div className="flex items-center gap-3">
                                <span className={`${STATUS_CONFIG[selectedDoc.status].badge} text-[10px]`}>
                                    {STATUS_CONFIG[selectedDoc.status].label}
                                </span>
                                {selectedDoc.effectiveDate && (
                                    <span className="text-tertiary">
                                        Effective: {new Date(selectedDoc.effectiveDate).toLocaleDateString()}
                                    </span>
                                )}
                            </div>
                            {selectedDoc.createdBy && (
                                <span className="flex items-center gap-1 text-tertiary">
                                    <User size={12} />
                                    {selectedDoc.createdBy.name}
                                </span>
                            )}
                        </div>

                        {/* Content */}
                        <div className="flex-1 overflow-hidden flex">
                            <div className={`flex-1 overflow-y-auto p-6 ${showVersions ? 'border-r border-subtle' : ''}`}>
                                <div
                                    className="prose prose-slate dark:prose-invert max-w-none text-sm"
                                    dangerouslySetInnerHTML={{ __html: selectedDoc.content }}
                                />
                            </div>

                            {showVersions && (
                                <div className="w-56 overflow-y-auto p-4 bg-tertiary">
                                    <h4 className="text-xs font-medium text-primary mb-3">Version History</h4>
                                    <div className="space-y-2">
                                        {versions.map(ver => (
                                            <div
                                                key={ver.id}
                                                className={`
                                                    p-2 rounded-md text-xs cursor-pointer
                                                    ${ver.version === selectedDoc.version
                                                        ? 'bg-accent-muted ring-1 ring-accent/30'
                                                        : 'bg-primary hover:bg-secondary'
                                                    }
                                                `}
                                            >
                                                <div className="flex justify-between items-center">
                                                    <span className="font-medium text-primary">v{ver.version}</span>
                                                    <span className="text-tertiary">{new Date(ver.createdAt).toLocaleDateString()}</span>
                                                </div>
                                                {ver.changeNotes && (
                                                    <p className="text-tertiary mt-1 truncate">{ver.changeNotes}</p>
                                                )}
                                            </div>
                                        ))}
                                    </div>
                                </div>
                            )}
                        </div>

                        {/* Footer */}
                        <div className="p-4 border-t border-subtle flex justify-between items-center">
                            {selectedDoc.requiresAck ? (
                                <button
                                    onClick={() => handleAcknowledge(selectedDoc.id)}
                                    className="btn btn-primary"
                                >
                                    <Check size={16} />
                                    Acknowledge
                                </button>
                            ) : <div />}
                            <div className="flex gap-1">
                                <button className="btn btn-ghost p-2">
                                    <Download size={16} />
                                </button>
                                <button className="btn btn-ghost p-2">
                                    <Edit size={16} />
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
            )}
        </div>
    );
}
