'use client';

import { useState, useEffect } from 'react';
import { motion } from 'framer-motion';
import {
  FileText, Plus, Download, Eye, Trash2,
  Loader2, Search, Filter, Folder, Calendar, Tag
} from 'lucide-react';
import { ERPModal } from '@/components/erp/erp-modal';

interface Document {
  id: string;
  title: string;
  description?: string;
  type: string;
  category?: string;
  fileName?: string;
  fileSize?: number;
  status: string;
  tags?: string[];
  createdAt: string;
  updatedAt: string;
}

export default function AllDocumentsPage() {
  const [documents, setDocuments] = useState<Document[]>([]);
  const [loading, setLoading] = useState(true);
  const [showModal, setShowModal] = useState(false);
  const [showViewModal, setShowViewModal] = useState(false);
  const [selectedDoc, setSelectedDoc] = useState<Document | null>(null);
  const [submitting, setSubmitting] = useState(false);
  const [searchTerm, setSearchTerm] = useState('');
  const [filterType, setFilterType] = useState<string>('all');
  const [formData, setFormData] = useState({
    title: '',
    description: '',
    type: 'policy',
    category: '',
    tags: '',
  });

  const fetchDocuments = async () => {
    setLoading(true);
    try {
      const res = await fetch('/api/erp/documents?type=documents');
      const data = await res.json();
      setDocuments(data.documents || []);
    } catch (error) {
      console.error('Failed to fetch documents:', error);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchDocuments();
  }, []);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!formData.title) return;

    setSubmitting(true);
    try {
      const res = await fetch('/api/erp/documents', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          entity: 'document',
          data: {
            title: formData.title,
            description: formData.description || null,
            type: formData.type,
            category: formData.category || null,
            tags: formData.tags ? formData.tags.split(',').map(t => t.trim()) : [],
            status: 'active',
            fileSize: Math.floor(Math.random() * 5000000), // Mock file size
          },
        }),
      });
      if (res.ok) {
        setShowModal(false);
        setFormData({
          title: '',
          description: '',
          type: 'policy',
          category: '',
          tags: '',
        });
        fetchDocuments();
      }
    } catch (error) {
      console.error('Failed to create document:', error);
    } finally {
      setSubmitting(false);
    }
  };

  const handleView = (doc: Document) => {
    setSelectedDoc(doc);
    setShowViewModal(true);
  };

  const handleDelete = async (docId: string) => {
    if (!confirm('Are you sure you want to delete this document?')) return;
    
    try {
      const res = await fetch(`/api/erp/documents?id=${docId}&entity=document`, {
        method: 'DELETE',
      });
      if (res.ok) {
        fetchDocuments();
      }
    } catch (error) {
      console.error('Failed to delete document:', error);
    }
  };

  const formatDate = (dateStr: string) => {
    if (!dateStr) return 'N/A';
    return new Date(dateStr).toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' });
  };

  const formatFileSize = (bytes?: number) => {
    if (!bytes) return 'N/A';
    if (bytes < 1024) return `${bytes} B`;
    if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
    return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
  };

  const getTypeIcon = (type: string) => {
    switch (type) {
      case 'policy': return 'bg-blue-500/10 text-blue-400';
      case 'report': return 'bg-green-500/10 text-green-400';
      case 'procedure': return 'bg-brand-secondary/10 text-brand-secondary-light';
      case 'template': return 'bg-yellow-500/10 text-yellow-400';
      case 'manual': return 'bg-brand-deep/10 text-brand';
      default: return 'bg-gray-500/10 text-gray-400';
    }
  };

  const documentTypes = ['all', 'policy', 'report', 'procedure', 'template', 'manual', 'other'];

  const filteredDocuments = documents.filter(doc => {
    const matchesSearch = (doc.title?.toLowerCase() || '').includes(searchTerm.toLowerCase()) ||
                          (doc.description?.toLowerCase() || '').includes(searchTerm.toLowerCase());
    const matchesFilter = filterType === 'all' || doc.type === filterType;
    return matchesSearch && matchesFilter;
  });

  const totalSize = documents.reduce((sum, d) => sum + (d.fileSize || 0), 0);

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold text-white flex items-center gap-3">
            <FileText className="w-7 h-7 text-brand" />
            All Documents
          </h1>
          <p className="text-gray-400 mt-1">Manage your company documents</p>
        </div>
        <button
          onClick={() => setShowModal(true)}
          className="flex items-center gap-2 px-4 py-2 bg-brand-deep hover:bg-brand-deep text-white rounded-lg transition-colors"
        >
          <Plus className="w-4 h-4" />
          Add Document
        </button>
      </div>

      {/* Summary Cards */}
      <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
        <div className="p-4 bg-white/5 border border-white/10 rounded-lg">
          <p className="text-sm text-gray-400">Total Documents</p>
          <p className="text-xl font-bold text-white">{documents.length}</p>
        </div>
        <div className="p-4 bg-white/5 border border-white/10 rounded-lg">
          <p className="text-sm text-gray-400">Active</p>
          <p className="text-xl font-bold text-green-400">
            {documents.filter(d => d.status === 'active').length}
          </p>
        </div>
        <div className="p-4 bg-white/5 border border-white/10 rounded-lg">
          <p className="text-sm text-gray-400">Archived</p>
          <p className="text-xl font-bold text-gray-400">
            {documents.filter(d => d.status === 'archived').length}
          </p>
        </div>
        <div className="p-4 bg-white/5 border border-white/10 rounded-lg">
          <p className="text-sm text-gray-400">Total Size</p>
          <p className="text-xl font-bold text-brand">{formatFileSize(totalSize)}</p>
        </div>
      </div>

      {/* Filters */}
      <div className="flex flex-col sm:flex-row gap-4">
        <div className="relative flex-1">
          <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-500" />
          <input
            type="text"
            placeholder="Search documents..."
            value={searchTerm}
            onChange={(e) => setSearchTerm(e.target.value)}
            className="w-full pl-10 pr-4 py-2 bg-white/5 border border-white/10 rounded-lg text-white placeholder-gray-500 focus:border-brand-deep focus:outline-none"
          />
        </div>
        <div className="flex gap-2 overflow-x-auto pb-2">
          {documentTypes.map((type) => (
            <button
              key={type}
              onClick={() => setFilterType(type)}
              className={`px-3 py-2 rounded-lg text-sm capitalize whitespace-nowrap transition-colors ${
                filterType === type
                  ? 'bg-brand-deep text-white'
                  : 'bg-white/5 text-gray-400 hover:bg-white/10'
              }`}
            >
              {type}
            </button>
          ))}
        </div>
      </div>

      {/* Documents List */}
      {loading ? (
        <div className="flex items-center justify-center py-12">
          <Loader2 className="w-8 h-8 text-brand animate-spin" />
        </div>
      ) : (
        <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-3">
          {filteredDocuments.length === 0 ? (
            <div className="col-span-full text-center py-12 text-gray-500 bg-white/5 border border-white/10 rounded-lg">
              No documents found
            </div>
          ) : (
            filteredDocuments.map((doc, index) => (
              <motion.div
                key={doc.id}
                initial={{ opacity: 0, y: 20 }}
                animate={{ opacity: 1, y: 0 }}
                transition={{ delay: index * 0.03 }}
                className="p-4 bg-white/5 border border-white/10 rounded-lg hover:border-brand-deep/30 transition-colors"
              >
                <div className="flex items-start justify-between mb-3">
                  <div className="flex items-center gap-3">
                    <div className={`p-2 rounded-lg ${getTypeIcon(doc.type)}`}>
                      <FileText className="w-5 h-5" />
                    </div>
                    <div className="min-w-0">
                      <h3 className="font-semibold text-white truncate">{doc.title}</h3>
                      <span className={`text-xs px-2 py-0.5 rounded capitalize ${getTypeIcon(doc.type)}`}>
                        {doc.type}
                      </span>
                    </div>
                  </div>
                </div>
                {doc.description && (
                  <p className="text-sm text-gray-400 mb-3 line-clamp-2">{doc.description}</p>
                )}
                <div className="flex items-center justify-between text-xs text-gray-500">
                  <div className="flex items-center gap-3">
                    <span className="flex items-center gap-1">
                      <Calendar className="w-3 h-3" />
                      {formatDate(doc.createdAt)}
                    </span>
                    <span>{formatFileSize(doc.fileSize)}</span>
                  </div>
                  <div className="flex gap-1">
                    <button
                      onClick={() => handleView(doc)}
                      className="p-1.5 hover:bg-white/10 rounded transition-colors"
                      title="View"
                    >
                      <Eye className="w-4 h-4 text-brand" />
                    </button>
                    <button
                      onClick={() => handleDelete(doc.id)}
                      className="p-1.5 hover:bg-white/10 rounded transition-colors"
                      title="Delete"
                    >
                      <Trash2 className="w-4 h-4 text-red-400" />
                    </button>
                  </div>
                </div>
                {doc.tags && doc.tags.length > 0 && (
                  <div className="flex flex-wrap gap-1 mt-2">
                    {(doc.tags as string[]).slice(0, 3).map((tag, i) => (
                      <span key={i} className="text-xs px-2 py-0.5 bg-white/5 text-gray-400 rounded">
                        {tag}
                      </span>
                    ))}
                  </div>
                )}
              </motion.div>
            ))
          )}
        </div>
      )}

      {/* Add Document Modal */}
      <ERPModal
        isOpen={showModal}
        onClose={() => setShowModal(false)}
        title="Add New Document"
      >
        <form onSubmit={handleSubmit} className="space-y-4">
          <div>
            <label className="block text-sm text-gray-400 mb-1">Document Title</label>
            <input
              type="text"
              value={formData.title}
              onChange={(e) => setFormData({ ...formData, title: e.target.value })}
              className="w-full px-3 py-2 bg-white/5 border border-white/10 rounded-lg text-white focus:border-brand-deep focus:outline-none"
              required
            />
          </div>
          <div className="grid grid-cols-2 gap-4">
            <div>
              <label className="block text-sm text-gray-400 mb-1">Type</label>
              <select
                value={formData.type}
                onChange={(e) => setFormData({ ...formData, type: e.target.value })}
                className="w-full px-3 py-2 bg-white/5 border border-white/10 rounded-lg text-white focus:border-brand-deep focus:outline-none"
              >
                <option value="policy">Policy</option>
                <option value="report">Report</option>
                <option value="procedure">Procedure</option>
                <option value="template">Template</option>
                <option value="manual">Manual</option>
                <option value="other">Other</option>
              </select>
            </div>
            <div>
              <label className="block text-sm text-gray-400 mb-1">Category</label>
              <input
                type="text"
                value={formData.category}
                onChange={(e) => setFormData({ ...formData, category: e.target.value })}
                className="w-full px-3 py-2 bg-white/5 border border-white/10 rounded-lg text-white focus:border-brand-deep focus:outline-none"
                placeholder="e.g., HR, Finance"
              />
            </div>
          </div>
          <div>
            <label className="block text-sm text-gray-400 mb-1">Description</label>
            <textarea
              value={formData.description}
              onChange={(e) => setFormData({ ...formData, description: e.target.value })}
              className="w-full px-3 py-2 bg-white/5 border border-white/10 rounded-lg text-white focus:border-brand-deep focus:outline-none resize-none"
              rows={3}
            />
          </div>
          <div>
            <label className="block text-sm text-gray-400 mb-1">Tags (comma-separated)</label>
            <input
              type="text"
              value={formData.tags}
              onChange={(e) => setFormData({ ...formData, tags: e.target.value })}
              className="w-full px-3 py-2 bg-white/5 border border-white/10 rounded-lg text-white focus:border-brand-deep focus:outline-none"
              placeholder="e.g., important, 2024, compliance"
            />
          </div>
          <div className="flex justify-end gap-3 pt-4">
            <button
              type="button"
              onClick={() => setShowModal(false)}
              className="px-4 py-2 text-gray-400 hover:text-white transition-colors"
            >
              Cancel
            </button>
            <button
              type="submit"
              disabled={submitting || !formData.title}
              className="px-4 py-2 bg-brand-deep hover:bg-brand-deep disabled:opacity-50 disabled:cursor-not-allowed text-white rounded-lg transition-colors flex items-center gap-2"
            >
              {submitting && <Loader2 className="w-4 h-4 animate-spin" />}
              Add Document
            </button>
          </div>
        </form>
      </ERPModal>

      {/* View Document Modal */}
      <ERPModal
        isOpen={showViewModal}
        onClose={() => setShowViewModal(false)}
        title={selectedDoc?.title || 'Document Details'}
      >
        {selectedDoc && (
          <div className="space-y-4">
            <div className="grid grid-cols-2 gap-4">
              <div>
                <p className="text-sm text-gray-400">Type</p>
                <p className="text-white capitalize">{selectedDoc.type}</p>
              </div>
              <div>
                <p className="text-sm text-gray-400">Status</p>
                <p className="text-white capitalize">{selectedDoc.status}</p>
              </div>
              <div>
                <p className="text-sm text-gray-400">Created</p>
                <p className="text-white">{formatDate(selectedDoc.createdAt)}</p>
              </div>
              <div>
                <p className="text-sm text-gray-400">File Size</p>
                <p className="text-white">{formatFileSize(selectedDoc.fileSize)}</p>
              </div>
            </div>
            {selectedDoc.description && (
              <div>
                <p className="text-sm text-gray-400">Description</p>
                <p className="text-white">{selectedDoc.description}</p>
              </div>
            )}
            {selectedDoc.tags && (selectedDoc.tags as string[]).length > 0 && (
              <div>
                <p className="text-sm text-gray-400 mb-2">Tags</p>
                <div className="flex flex-wrap gap-2">
                  {(selectedDoc.tags as string[]).map((tag, i) => (
                    <span key={i} className="text-xs px-2 py-1 bg-brand-deep/10 text-brand rounded">
                      {tag}
                    </span>
                  ))}
                </div>
              </div>
            )}
            <div className="flex justify-end pt-4">
              <button
                onClick={() => setShowViewModal(false)}
                className="px-4 py-2 bg-white/5 hover:bg-white/10 text-white rounded-lg transition-colors"
              >
                Close
              </button>
            </div>
          </div>
        )}
      </ERPModal>
    </div>
  );
}
