import { useState } from "react";
import AddDocumentModal from "./AddDocumentModal";
import ChecklistHeader from "./ChecklistHeader";
import DocumentModal from "./DocumentModal";
import DocumentTable from "./DocumentTable";
import FilterBar from "./FilterBar";
import ImportModal from "./ImportModal";
import OveralSidebar from "./OveralSidebar";

const ITProjectManager = () => {
  // Sample data structure based on the JSON
  const [projectData, setProjectData] = useState({
    "Document": {
      "0": "Project Request",
      "1": "PPAC Request",
      "2": "Project Committee Charter",
      "3": "Business Case",
      "4": "Feasibility Study/Assessment",
      "5": "Business Requirement Document",
      "6": "Request For Proposal (RFP)/ Invitations-To-Tender (ITT)",
      "7": "Project Plans",
      "8": "Initial cost/budget approved",
      "9": "Final Cost Incurred",
      "10": "Initial Architecture/ Technical Feasibility and Estimates"
    },
    "Definition": {
      "0": null,
      "1": null,
      "2": null,
      "3": null,
      "4": "A feasibility study should be performed to identify the expected costs and benefits of developing a system.",
      "5": null,
      "6": "RFP is a document that a BSFI sends to a vendor inviting the vendor to submit a bid.",
      "7": "Project Plans should address business requirements for resumption and recovery alternatives.",
      "8": null,
      "9": null,
      "10": null
    },
    "MORB": {
      "0": "X",
      "1": null,
      "2": "X",
      "3": null,
      "4": "X",
      "5": null,
      "6": "X",
      "7": "X",
      "8": null,
      "9": null,
      "10": null
    },
    "Internal Policies": {
      "0": null,
      "1": "X",
      "2": "X",
      "3": "X",
      "4": null,
      "5": null,
      "6": null,
      "7": null,
      "8": null,
      "9": null,
      "10": "X"
    },
    "PIC": {
      "0": "Business Sponsor",
      "1": "Business Sponsor",
      "2": "Tech PM",
      "3": "Business Sponsor",
      "4": "Business Sponsor",
      "5": "Business Sponsor",
      "6": "Business Sponsor",
      "7": "Tech PM",
      "8": "Business Sponsor",
      "9": "Tech PM",
      "10": "Tech PM"
    },
    "Document Status": {},
    "Documentation Link": {},
    "Reviewed By": {},
    "Review Remarks": {},
    "Last Update": {
      "0": "2024-11-15",
      "1": "2024-12-03", 
      "2": "2024-10-28",
      "3": "2024-12-18",
      "4": "2024-09-14",
      "5": "2024-11-22",
      "6": "2024-12-01",
      "7": "2024-10-05",
      "8": "2024-11-30",
      "9": "2024-12-10",
      "10": "2024-12-20"
    },
    "Status/Phase": {}
  });



  const [searchTerm, setSearchTerm] = useState('');
  const [filterStatus, setFilterStatus] = useState('all');
  const [filterRequirement, setFilterRequirement] = useState('all');
  const [selectedDocument, setSelectedDocument] = useState(null);
  const [editMode, setEditMode] = useState(false);
  const [editData, setEditData] = useState({});
  const [showAddModal, setShowAddModal] = useState(false);
  const [newDocumentData, setNewDocumentData] = useState({
    name: '',
    definition: '',
    morb: false,
    internalPolicies: false,
    pic: '',
    status: 'Not Started',
    phase: ''
  });
  const [showImportModal, setShowImportModal] = useState(false);
  const [importError, setImportError] = useState('');
  const [importSuccess, setImportSuccess] = useState(false);

  // Get document count
  const documentCount = Object.keys(projectData.Document).length;

  // Get unique PIC roles
  const getUniqueRoles = () => {
    const roles = new Set();
    Object.values(projectData.PIC).forEach(pic => {
      if (pic) roles.add(pic);
    });
    return Array.from(roles).sort();
  };

  const availableRoles = getUniqueRoles();

  // Handle PIC change directly in table
  const handlePICChange = (documentId, newPIC) => {
    setProjectData(prev => ({
      ...prev,
      "PIC": { ...prev.PIC, [documentId]: newPIC },
      "Last Update": { ...prev["Last Update"], [documentId]: new Date().toISOString().split('T')[0] }
    }));
  };

  // Filter documents based on search and filters
  const getFilteredDocuments = () => {
    const documents = [];
    for (let i = 0; i < documentCount; i++) {
      const id = i.toString();
      const doc = {
        id,
        name: projectData.Document[id],
        definition: projectData.Definition[id],
        morb: projectData.MORB[id],
        internalPolicies: projectData["Internal Policies"][id],
        pic: projectData.PIC[id],
        status: projectData["Document Status"][id] || 'Not Started',
        link: projectData["Documentation Link"][id],
        reviewedBy: projectData["Reviewed By"][id],
        reviewRemarks: projectData["Review Remarks"][id],
        lastUpdate: projectData["Last Update"][id],
        phase: projectData["Status/Phase"][id]
      };

      // Apply search filter
      if (searchTerm && !doc.name?.toLowerCase().includes(searchTerm.toLowerCase()) && 
          !doc.definition?.toLowerCase().includes(searchTerm.toLowerCase())) {
        continue;
      }

      // Apply status filter
      if (filterStatus !== 'all' && doc.status !== filterStatus) {
        continue;
      }

      // Apply requirement filter
      if (filterRequirement === 'morb' && !doc.morb) continue;
      if (filterRequirement === 'internal' && !doc.internalPolicies) continue;

      documents.push(doc);
    }
    return documents;
  };

  const filteredDocuments = getFilteredDocuments();

  // Status color mapping
  const getStatusColor = (status) => {
    switch (status) {
      case 'Completed': return 'text-green-600 bg-green-100';
      case 'In Progress': return 'text-blue-600 bg-blue-100';
      case 'Under Review': return 'text-yellow-600 bg-yellow-100';
      case 'Not Started': return 'text-gray-600 bg-gray-100';
      default: return 'text-gray-600 bg-gray-100';
    }
  };

  // Handle document update
  const handleSave = () => {
    setProjectData(prev => ({
      ...prev,
      "Document Status": { ...prev["Document Status"], [selectedDocument.id]: editData.status },
      "Documentation Link": { ...prev["Documentation Link"], [selectedDocument.id]: editData.link },
      "Reviewed By": { ...prev["Reviewed By"], [selectedDocument.id]: editData.reviewedBy },
      "Review Remarks": { ...prev["Review Remarks"], [selectedDocument.id]: editData.reviewRemarks },
      "Last Update": { ...prev["Last Update"], [selectedDocument.id]: editData.lastUpdate },
      "Status/Phase": { ...prev["Status/Phase"], [selectedDocument.id]: editData.phase },
      "PIC": { ...prev.PIC, [selectedDocument.id]: editData.pic }
    }));
    setEditMode(false);
    setSelectedDocument(null);
  };

  const openEditModal = (doc) => {
    setSelectedDocument(doc);
    setEditData({
      status: doc.status,
      link: doc.link || '',
      reviewedBy: doc.reviewedBy || '',
      reviewRemarks: doc.reviewRemarks || '',
      phase: doc.phase || '',
      pic: doc.pic || '',
      lastUpdate: doc.lastUpdate || ''
    });
    setEditMode(true);
  };

  const openViewModal = (doc) => {
    setSelectedDocument(doc);
    setEditMode(false);
  };

  // Add new document
  const handleAddDocument = () => {
    const existingIds = Object.keys(projectData.Document).map(Number);
    const newId = Math.max(...existingIds) + 1;
    const newIdStr = newId.toString();

    setProjectData(prev => ({
      ...prev,
      "Document": { ...prev.Document, [newIdStr]: newDocumentData.name },
      "Definition": { ...prev.Definition, [newIdStr]: newDocumentData.definition || null },
      "MORB": { ...prev.MORB, [newIdStr]: newDocumentData.morb ? 'X' : null },
      "Internal Policies": { ...prev["Internal Policies"], [newIdStr]: newDocumentData.internalPolicies ? 'X' : null },
      "PIC": { ...prev.PIC, [newIdStr]: newDocumentData.pic || null },
      "Document Status": { ...prev["Document Status"], [newIdStr]: newDocumentData.status },
      "Status/Phase": { ...prev["Status/Phase"], [newIdStr]: newDocumentData.phase || null },
      "Documentation Link": { ...prev["Documentation Link"], [newIdStr]: null },
      "Reviewed By": { ...prev["Reviewed By"], [newIdStr]: null },
      "Review Remarks": { ...prev["Review Remarks"], [newIdStr]: null },
      "Last Update": { ...prev["Last Update"], [newIdStr]: new Date().toISOString().split('T')[0] }
    }));

    // Reset form and close modal
    setNewDocumentData({
      name: '',
      definition: '',
      morb: false,
      internalPolicies: false,
      pic: '',
      status: 'Not Started',
      phase: ''
    });
    setShowAddModal(false);
  };

  // Delete document
  const handleDeleteDocument = (documentId) => {
    if (window.confirm('Are you sure you want to delete this document? This action cannot be undone.')) {
      const updatedProjectData = { ...projectData };
      
      // Remove from all sections
      Object.keys(updatedProjectData).forEach(section => {
        if (updatedProjectData[section] && updatedProjectData[section][documentId] !== undefined) {
          const newSection = { ...updatedProjectData[section] };
          delete newSection[documentId];
          updatedProjectData[section] = newSection;
        }
      });

      setProjectData(updatedProjectData);
      
      // Close modal if the deleted document was selected
      if (selectedDocument && selectedDocument.id === documentId) {
        setSelectedDocument(null);
        setEditMode(false);
      }
    }
  };

  // Handle JSON file import
  const handleFileImport = (event) => {
    const file = event.target.files[0];
    if (!file) return;

    if (!file.name.endsWith('.json')) {
      setImportError('Please select a valid JSON file.');
      return;
    }

    const reader = new FileReader();
    reader.onload = (e) => {
      try {
        const importedData = JSON.parse(e.target.result);
        
        // Validate the imported data structure
        const requiredSections = ['Document', 'Definition', 'MORB', 'Internal Policies', 'PIC'];
        const hasRequiredSections = requiredSections.every(section => 
          importedData.hasOwnProperty(section)
        );

        if (!hasRequiredSections) {
          setImportError('Invalid JSON structure. Missing required sections.');
          return;
        }

        // Add missing sections if they don't exist
        const completeData = {
          ...importedData,
          "Document Status": importedData["Document Status"] || {},
          "Documentation Link": importedData["Documentation Link"] || {},
          "Reviewed By": importedData["Reviewed By"] || {},
          "Review Remarks": importedData["Review Remarks"] || {},
          "Last Update": importedData["Last Update"] || {},
          "Status/Phase": importedData["Status/Phase"] || {}
        };

        setProjectData(completeData);
        setImportSuccess(true);
        setImportError('');
        
        // Auto-close success message after 3 seconds
        setTimeout(() => {
          setImportSuccess(false);
          setShowImportModal(false);
        }, 3000);

      } catch (error) {
        setImportError('Error parsing JSON file. Please check the file format.');
      }
    };

    reader.readAsText(file);
    // Reset the input
    event.target.value = '';
  };

  // Export JSON data
  const handleExport = () => {
    const dataStr = JSON.stringify(projectData, null, 2);
    const dataUri = 'data:application/json;charset=utf-8,'+ encodeURIComponent(dataStr);
    
    const exportFileDefaultName = `project_data_${new Date().toISOString().split('T')[0]}.json`;
    
    const linkElement = document.createElement('a');
    linkElement.setAttribute('href', dataUri);
    linkElement.setAttribute('download', exportFileDefaultName);
    linkElement.click();
  };

  // Modal handlers
  const handleCloseModal = () => {
    setSelectedDocument(null);
    setEditMode(false);
  };

  const handleCloseAddModal = () => {
    setShowAddModal(false);
    setNewDocumentData({
      name: '',
      definition: '',
      morb: false,
      internalPolicies: false,
      pic: '',
      status: 'Not Started',
      phase: ''
    });
  };

  const handleCloseImportModal = () => {
    setShowImportModal(false);
    setImportError('');
    setImportSuccess(false);
  };

  return (
    <div className="h-full bg-gray-50">
      {/* Header */}
      <ChecklistHeader 
        onAddDocument={() => setShowAddModal(true)}
        onImportClick={() => setShowImportModal(true)}
        onExport={handleExport}
      />

      {/* Filter Bar */}
      <FilterBar 
        searchTerm={searchTerm}
        setSearchTerm={setSearchTerm}
        filterStatus={filterStatus}
        setFilterStatus={setFilterStatus}
        filterRequirement={filterRequirement}
        setFilterRequirement={setFilterRequirement}
        filteredCount={filteredDocuments.length}
        totalCount={documentCount}
        morbCount={Object.values(projectData.MORB).filter(x => x === 'X').length}
        internalCount={Object.values(projectData["Internal Policies"]).filter(x => x === 'X').length}
      />

      {/* Main Content */}
      <div className="p-6 flex gap-6">
        <div className="flex-1">
          <DocumentTable 
            documents={filteredDocuments}
            availableRoles={availableRoles}
            onPICChange={handlePICChange}
            onViewDocument={openViewModal}
            onEditDocument={openEditModal}
            onDeleteDocument={handleDeleteDocument}
            getStatusColor={getStatusColor}
          />
        </div>

        {/* Right side: sidebar fixed width */}
        <div className="w-80">
          <OveralSidebar 
            documentCount={documentCount} 
            filteredDocuments={filteredDocuments} 
            projectData={projectData}
          />
        </div>
      </div>

      {/* Document Details Modal */}
      <DocumentModal 
        document={selectedDocument}
        editMode={editMode}
        editData={editData}
        setEditData={setEditData}
        availableRoles={availableRoles}
        onSave={handleSave}
        onCancel={handleCloseModal}
        getStatusColor={getStatusColor}
      />

      {/* Add Document Modal */}
      <AddDocumentModal 
        show={showAddModal}
        newDocumentData={newDocumentData}
        setNewDocumentData={setNewDocumentData}
        availableRoles={availableRoles}
        onSave={handleAddDocument}
        onCancel={handleCloseAddModal}
      />

      {/* Import JSON Modal */}
      <ImportModal 
        show={showImportModal}
        importError={importError}
        importSuccess={importSuccess}
        onFileImport={handleFileImport}
        onClose={handleCloseImportModal}
      />
    </div>
  );
};

export default ITProjectManager;