'use client';

import { ATAButton } from '@/components/agent-hierarchy/ata-flyout';
import { useState, useEffect } from 'react';
import { motion } from 'framer-motion';
import {
  FileText, ScrollText, Upload, Clock, AlertTriangle,
  FileCheck, Folder, HardDrive, Calendar, Plus, Loader2,
  Eye, Download, X
} from 'lucide-react';
import { ERPModal } from '@/components/erp/erp-modal';

interface DocumentsData {
  summary: {
    totalDocuments: number;
    documentsByType: Record<string, number>;
    totalContracts: number;
    contractsByStatus: Record<string, number>;
    activeContractValue: number;
    expiringContractsCount: number;
    totalStorageUsed: number;
  };
  recentDocuments: Array<{
    id: string;
    title: string;
    type: string;
    createdAt: string;
    fileSize: number;
    filePath?: string;
    fileUrl?: string;
  }>;
  expiringContracts: Array<{
    id: string;
    contractNumber: string;
    title: string;
    partyName: string;
    endDate: string;
    value: number;
  }>;
}

export default function DocumentsDashboard() {
  const [data, setData] = useState<DocumentsData | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [showUploadModal, setShowUploadModal] = useState(false);
  const [showViewModal, setShowViewModal] = useState(false);
  const [selectedDoc, setSelectedDoc] = useState<DocumentsData['recentDocuments'][0] | null>(null);
  const [submitting, setSubmitting] = useState(false);
  const [allDocuments, setAllDocuments] = useState<DocumentsData['recentDocuments']>([]);
  const [formData, setFormData] = useState({
    title: '',
    type: 'misc',
    description: '',
    tags: '',
  });

  const fetchData = () => {
    setLoading(true);
    setError(null);
    fetch('/api/erp/documents')
      .then((r) => {
        if (!r.ok) throw new Error('Failed to fetch documents');
        return r.json();
      })
      .then((d) => {
        if (d.success === false) throw new Error(d.error || 'Failed to fetch documents');
        setData(d);
        setAllDocuments(d.recentDocuments || []);
      })
      .catch((err) => setError(err.message))
      .finally(() => setLoading(false));
  };

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

  const formatCurrency = (value: number) =>
    new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' }).format(value || 0);

  const formatBytes = (bytes: number) => {
    if (!bytes) return '0 B';
    const k = 1024;
    const sizes = ['B', 'KB', 'MB', 'GB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    return `${parseFloat((bytes / Math.pow(k, i)).toFixed(1))} ${sizes[i]}`;
  };

  const handleUpload = 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,
            type: formData.type,
            description: formData.description || null,
            tags: formData.tags ? formData.tags.split(',').map(t => t.trim()) : [],
            fileSize: Math.floor(Math.random() * 500000) + 10000, // Simulated file size
            status: 'active',
          },
        }),
      });
      
      if (res.ok) {
        setShowUploadModal(false);
        setFormData({ title: '', type: 'misc', description: '', tags: '' });
        fetchData();
      }
    } catch (error) {
      console.error('Failed to upload document:', error);
    } finally {
      setSubmitting(false);
    }
  };

  const openViewModal = (doc: DocumentsData['recentDocuments'][0]) => {
    setSelectedDoc(doc);
    setShowViewModal(true);
  };

  if (loading) {
    return (
      <div className="space-y-6">
        <div className="h-8 w-48 bg-white/10 rounded animate-pulse" />
        <div className="grid grid-cols-4 gap-4">
          {[1, 2, 3, 4].map((i) => (
            <div key={i} className="h-32 bg-white/5 rounded-lg animate-pulse" />
          ))}
        </div>
      </div>
    );
  }

  if (error) {
    return (
      <div className="space-y-6">
        <div className="flex items-center justify-between">
          <h1 className="text-2xl font-bold text-white">Document Management</h1>
          <button onClick={fetchData} className="px-4 py-2 bg-brand-deep/20 text-brand rounded-lg">
            Retry
          </button>
        </div>
        <div className="glass-card p-8 border border-red-500/30 text-center">
          <AlertTriangle className="w-12 h-12 text-red-400 mx-auto mb-4" />
          <p className="text-red-400">{error}</p>
          <p className="text-gray-500 text-sm mt-2">Please try refreshing the page or check the database connection.</p>
        </div>
      </div>
    );
  }

  const summary = data?.summary || {} as DocumentsData['summary'];

  const kpiCards = [
    {
      label: 'Total Documents',
      value: summary.totalDocuments || 0,
      icon: <FileText className="w-5 h-5" />,
      color: 'amber',
    },
    {
      label: 'Active Contracts',
      value: summary.totalContracts || 0,
      icon: <ScrollText className="w-5 h-5" />,
      color: 'cyan',
    },
    {
      label: 'Contract Value',
      value: formatCurrency(summary.activeContractValue),
      icon: <FileCheck className="w-5 h-5" />,
      color: 'green',
    },
    {
      label: 'Expiring Soon',
      value: summary.expiringContractsCount || 0,
      icon: <Clock className="w-5 h-5" />,
      color: summary.expiringContractsCount > 0 ? 'red' : 'gray',
    },
  ];

  const colorClasses: Record<string, { bg: string; text: string; border: string }> = {
    cyan: { bg: 'bg-brand-deep/10', text: 'text-brand', border: 'border-brand-deep/30' },
    green: { bg: 'bg-green-500/10', text: 'text-green-400', border: 'border-green-500/30' },
    amber: { bg: 'bg-amber-500/10', text: 'text-amber-400', border: 'border-amber-500/30' },
    red: { bg: 'bg-red-500/10', text: 'text-red-400', border: 'border-red-500/30' },
    gray: { bg: 'bg-gray-500/10', text: 'text-gray-400', border: 'border-gray-500/30' },
  };

  const docTypeIcons: Record<string, React.ReactNode> = {
    contract: <ScrollText className="w-4 h-4" />,
    invoice: <FileCheck className="w-4 h-4" />,
    report: <FileText className="w-4 h-4" />,
    policy: <Folder className="w-4 h-4" />,
    misc: <FileText className="w-4 h-4" />,
  };

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold text-white">Document Management</h1>
          <p className="text-gray-400 text-sm">Contracts, records, and file storage</p>
        </div>
        <div className="flex items-center gap-3">
          <ATAButton agentId="agent-operations" variant="compact" />
          <button 
            onClick={() => setShowUploadModal(true)}
            className="flex items-center gap-2 px-4 py-2 bg-amber-500/20 text-amber-400 rounded-lg hover:bg-amber-500/30 transition-colors border border-amber-500/30"
          >
            <Upload className="w-4 h-4" />
            <span>Upload Document</span>
          </button>
        </div>
      </div>

      {/* KPI Cards */}
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
        {kpiCards.map((card, idx) => (
          <motion.div
            key={card.label}
            initial={{ opacity: 0, y: 20 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ delay: idx * 0.1 }}
            className={`glass-card p-4 border ${colorClasses[card.color].border}`}
          >
            <div className="flex items-center justify-between mb-2">
              <span className="text-gray-400 text-sm">{card.label}</span>
              <div className={`p-1.5 rounded ${colorClasses[card.color].bg}`}>
                <span className={colorClasses[card.color].text}>{card.icon}</span>
              </div>
            </div>
            <span className="text-2xl font-bold text-white">{card.value}</span>
          </motion.div>
        ))}
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        {/* All Documents */}
        <div className="glass-card p-6 border border-white/10">
          <h2 className="text-lg font-semibold text-white flex items-center gap-2 mb-4">
            <Folder className="w-5 h-5 text-amber-400" />
            All Documents
          </h2>
          {allDocuments.length > 0 ? (
            <div className="space-y-3 max-h-80 overflow-y-auto">
              {allDocuments.map((doc) => (
                <div key={doc.id} className="flex items-center justify-between p-3 bg-white/5 rounded-lg hover:bg-white/10 transition-colors">
                  <div className="flex items-center gap-3">
                    <div className="p-2 bg-amber-500/10 rounded text-amber-400">
                      {docTypeIcons[doc.type] || <FileText className="w-4 h-4" />}
                    </div>
                    <div>
                      <p className="text-white text-sm font-medium">{doc.title}</p>
                      <p className="text-gray-500 text-xs capitalize">{doc.type} • {formatBytes(doc.fileSize)}</p>
                    </div>
                  </div>
                  <div className="flex items-center gap-2">
                    <button 
                      onClick={() => openViewModal(doc)}
                      className="p-2 hover:bg-white/10 rounded-lg transition-colors text-gray-400 hover:text-brand"
                      title="View Document"
                    >
                      <Eye className="w-4 h-4" />
                    </button>
                  </div>
                </div>
              ))}
            </div>
          ) : (
            <div className="text-center py-8 text-gray-500">
              <FileText className="w-8 h-8 mx-auto mb-2 opacity-50" />
              <p>No documents yet</p>
              <button 
                onClick={() => setShowUploadModal(true)}
                className="mt-2 text-amber-400 text-sm hover:underline"
              >
                Upload your first document
              </button>
            </div>
          )}
          <div className="mt-4 pt-4 border-t border-white/10 flex items-center gap-2">
            <HardDrive className="w-4 h-4 text-gray-500" />
            <span className="text-gray-500 text-sm">
              Storage used: <span className="text-white">{formatBytes(summary.totalStorageUsed)}</span>
            </span>
          </div>
        </div>

        {/* Expiring Contracts */}
        <div className="glass-card p-6 border border-white/10">
          <h2 className="text-lg font-semibold text-white flex items-center gap-2 mb-4">
            <Calendar className="w-5 h-5 text-red-400" />
            Contracts Expiring Soon
          </h2>
          {data?.expiringContracts?.length ? (
            <div className="space-y-3">
              {data.expiringContracts.map((contract) => {
                const daysUntil = Math.ceil(
                  (new Date(contract.endDate).getTime() - Date.now()) / (1000 * 60 * 60 * 24)
                );
                return (
                  <div key={contract.id} className="p-3 bg-red-500/5 rounded-lg border border-red-500/20">
                    <div className="flex items-center justify-between mb-1">
                      <p className="text-white text-sm font-medium">{contract.title}</p>
                      <span className="text-red-400 text-xs font-medium">
                        {daysUntil} days left
                      </span>
                    </div>
                    <div className="flex items-center justify-between">
                      <p className="text-gray-500 text-xs">{contract.partyName}</p>
                      <p className="text-gray-400 text-xs">{formatCurrency(contract.value || 0)}</p>
                    </div>
                  </div>
                );
              })}
            </div>
          ) : (
            <div className="text-center py-8 text-gray-500">
              <ScrollText className="w-8 h-8 mx-auto mb-2 opacity-50" />
              <p>No contracts expiring soon</p>
            </div>
          )}
        </div>
      </div>

      {/* Contract Status Summary */}
      {Object.keys(summary.contractsByStatus || {}).length > 0 && (
        <div className="grid grid-cols-2 md:grid-cols-5 gap-4">
          {Object.entries(summary.contractsByStatus).map(([status, count]) => (
            <div key={status} className="p-4 bg-white/5 rounded-lg border border-white/10">
              <p className="text-gray-500 text-xs capitalize">{status}</p>
              <p className="text-white font-semibold text-lg">{count}</p>
            </div>
          ))}
        </div>
      )}

      {/* Upload Document Modal */}
      <ERPModal isOpen={showUploadModal} onClose={() => setShowUploadModal(false)} title="Upload Document">
        <form onSubmit={handleUpload} 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-amber-500/50 focus:outline-none"
              placeholder="e.g., Q1 2024 Financial Report"
              required
            />
          </div>
          
          <div>
            <label className="block text-sm text-gray-400 mb-1">Document 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-amber-500/50 focus:outline-none"
            >
              <option value="misc" className="bg-brand-bg">Miscellaneous</option>
              <option value="contract" className="bg-brand-bg">Contract</option>
              <option value="invoice" className="bg-brand-bg">Invoice</option>
              <option value="report" className="bg-brand-bg">Report</option>
              <option value="policy" className="bg-brand-bg">Policy</option>
            </select>
          </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-amber-500/50 focus:outline-none resize-none"
              rows={3}
              placeholder="Brief description of the document..."
            />
          </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-amber-500/50 focus:outline-none"
              placeholder="e.g., finance, quarterly, 2024"
            />
          </div>

          {/* File drop zone placeholder */}
          <div className="border-2 border-dashed border-white/20 rounded-lg p-6 text-center">
            <Upload className="w-8 h-8 text-gray-500 mx-auto mb-2" />
            <p className="text-gray-400 text-sm">File upload simulation</p>
            <p className="text-gray-500 text-xs mt-1">Document will be created as a record in the system</p>
          </div>
          
          <div className="flex gap-3 pt-4">
            <button
              type="button"
              onClick={() => setShowUploadModal(false)}
              className="flex-1 px-4 py-2 bg-white/5 text-gray-400 rounded-lg hover:bg-white/10 transition-colors"
            >
              Cancel
            </button>
            <button
              type="submit"
              disabled={submitting}
              className="flex-1 px-4 py-2 bg-amber-500/20 text-amber-400 rounded-lg hover:bg-amber-500/30 transition-colors border border-amber-500/30 disabled:opacity-50 flex items-center justify-center gap-2"
            >
              {submitting && <Loader2 className="w-4 h-4 animate-spin" />}
              {submitting ? 'Uploading...' : 'Upload Document'}
            </button>
          </div>
        </form>
      </ERPModal>

      {/* View Document Modal */}
      <ERPModal isOpen={showViewModal} onClose={() => setShowViewModal(false)} title="Document Details">
        {selectedDoc && (
          <div className="space-y-4">
            <div className="flex items-center gap-4">
              <div className="p-4 bg-amber-500/10 rounded-lg text-amber-400">
                {docTypeIcons[selectedDoc.type] || <FileText className="w-8 h-8" />}
              </div>
              <div>
                <h3 className="text-lg font-semibold text-white">{selectedDoc.title}</h3>
                <p className="text-gray-500 text-sm capitalize">{selectedDoc.type}</p>
              </div>
            </div>
            
            <div className="grid grid-cols-2 gap-4">
              <div className="p-3 bg-white/5 rounded-lg">
                <p className="text-gray-500 text-xs">File Size</p>
                <p className="text-white font-medium">{formatBytes(selectedDoc.fileSize)}</p>
              </div>
              <div className="p-3 bg-white/5 rounded-lg">
                <p className="text-gray-500 text-xs">Created</p>
                <p className="text-white font-medium">{new Date(selectedDoc.createdAt).toLocaleDateString()}</p>
              </div>
            </div>
            
            <div className="p-4 bg-white/5 rounded-lg border border-white/10">
              <p className="text-gray-400 text-sm">Document ID</p>
              <p className="text-white font-mono text-xs mt-1">{selectedDoc.id}</p>
            </div>
            
            <div className="flex gap-3 pt-4">
              <button
                onClick={() => setShowViewModal(false)}
                className="flex-1 px-4 py-2 bg-white/5 text-gray-400 rounded-lg hover:bg-white/10 transition-colors"
              >
                Close
              </button>
              <button
                className="flex-1 px-4 py-2 bg-brand-deep/20 text-brand rounded-lg hover:bg-brand-deep/30 transition-colors border border-brand-deep/30 flex items-center justify-center gap-2"
                onClick={() => alert('Download feature coming soon!')}
              >
                <Download className="w-4 h-4" />
                Download
              </button>
            </div>
          </div>
        )}
      </ERPModal>
    </div>
  );
}
