import React, { useState, useEffect } from 'react'; import { Folder, Calendar, ArrowRight, Trash2, FileSpreadsheet, LayoutList, CheckCircle2, Clock } from 'lucide-react'; export default function Projects({ token, isArabic, onSelectProject, onNavigate, initialTab }) { const [activeTab, setActiveTab] = useState(initialTab || 'qto'); const [qtoProjects, setQtoProjects] = useState([]); const [progProjects, setProgProjects] = useState([]); const [cfProjects, setCfProjects] = useState([]); const [loading, setLoading] = useState(false); useEffect(() => { setActiveTab(initialTab || 'qto'); }, [initialTab]); useEffect(() => { if (activeTab === 'qto' && qtoProjects.length === 0) fetchQto(); else if (activeTab === 'programme' && progProjects.length === 0) fetchProg(); else if (activeTab === 'cashflow' && cfProjects.length === 0) fetchCf(); }, [activeTab]); const fetchQto = async () => { setLoading(true); try { const res = await fetch("/api/projects", { headers: { 'Authorization': `Bearer ${token}` } }); if (res.ok) setQtoProjects(await res.json()); } catch (err) { console.error(err); } finally { setLoading(false); } }; const fetchProg = async () => { setLoading(true); try { const res = await fetch("/api/modules/programme", { headers: { 'Authorization': `Bearer ${token}` } }); if (res.ok) setProgProjects(await res.json()); } catch (err) { console.error(err); } finally { setLoading(false); } }; const fetchCf = async () => { setLoading(true); try { const res = await fetch("/api/modules/cashflow", { headers: { 'Authorization': `Bearer ${token}` } }); if (res.ok) setCfProjects(await res.json()); } catch (err) { console.error(err); } finally { setLoading(false); } }; const handleDeleteQto = async (id, e) => { e.stopPropagation(); if (!confirm(isArabic ? 'هل أنت متأكد من رغبتك في حذف هذا المشروع نهائياً؟' : 'Are you sure you want to delete this project permanently?')) return; try { const res = await fetch(`/api/projects/${id}`, { method: 'DELETE', headers: { 'Authorization': `Bearer ${token}` } }); if (res.ok) setQtoProjects(prev => prev.filter(p => p.id !== id)); } catch (err) { console.error(err); } }; const handleDeleteModule = async (feature, id, e) => { e.stopPropagation(); if (!confirm(isArabic ? 'هل أنت متأكد؟' : 'Are you sure?')) return; try { const res = await fetch(`/api/modules/${feature}/item/${id}`, { method: 'DELETE', headers: { 'Authorization': `Bearer ${token}` } }); if (res.ok) { if (feature === 'programme') setProgProjects(prev => prev.filter(p => p.id !== id)); else setCfProjects(prev => prev.filter(p => p.id !== id)); } } catch (err) { console.error(err); } }; const handleLoadModule = async (feature, id) => { try { const res = await fetch(`/api/modules/${feature}/item/${id}`, { headers: { Authorization: `Bearer ${token}` } }); if (res.ok) { const data = await res.json(); onNavigate(feature, { loadData: { id: data.id, config: data.config } }); } } catch (err) { console.error(err); } }; const handleExportModuleExcel = async (feature, id, e) => { e.stopPropagation(); // Default configs for fallback const DEFAULT_CFG = { buaPerFloor: 400, complexityFactor: 1.0, hasPool: false, hasDemolition: false, contractValueAed: 1500000, advancePaymentPct: 10, retentionPct: 10, retentionReleaseAtCompletionPct: 50, vatPct: 5, certificationPeriodDays: 30, paymentPeriodDays: 30, defectsLiabilityMonths: 12, contractorCostRatio: 0.85, startISO: new Date().toISOString().split('T')[0] }; try { const res = await fetch(`/api/modules/${feature}/item/${id}`, { headers: { Authorization: `Bearer ${token}` } }); if (res.ok) { const data = await res.json(); const cfg = { ...DEFAULT_CFG, ...data.config }; const { buildActivityList } = await import('../engine/durationEngine'); const { runScheduler } = await import('../engine/scheduler'); const acts = buildActivityList(cfg); const out = runScheduler(cfg, acts); if (feature === 'programme') { const mod = await import('../engine/programmeExcel'); mod.exportProgrammeToExcel(out, cfg.projectName || 'Project'); } else { const { computeCashFlow } = await import('../engine/cashflow'); const resObj = computeCashFlow(cfg, out.monthly); const mod = await import('../engine/cashflowExcel'); mod.exportCashFlowToExcel(cfg, resObj, cfg.projectName || 'Project'); } } } catch (err) { console.error(err); } }; const renderQto = () => ( loading && qtoProjects.length === 0 ? (

{isArabic ? 'جاري جلب المشاريع...' : 'Fetching projects history...'}

) : qtoProjects.length === 0 ? (

{isArabic ? 'لا توجد مشاريع سابقة حالياً.' : 'No previous projects found.'}

) : (
{qtoProjects.map((proj) => { const step = proj.current_step || 8; const isDone = step >= 7; return (
{ onSelectProject(proj); onNavigate('workflow'); }} style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', cursor: isDone ? 'default' : 'pointer' }} >

{proj.name}

{proj.date} • {isArabic ? `الخطوة ${proj.current_step || 8} من 8` : `Step ${proj.current_step || 8} of 8`}
{isDone && ( )} {!isDone && }
); })}
) ); const renderModule = (items, feature) => ( loading && items.length === 0 ? (

{isArabic ? 'جاري جلب المشاريع...' : 'Fetching projects history...'}

) : items.length === 0 ? (

{isArabic ? 'لا توجد مشاريع سابقة حالياً.' : 'No previous projects found.'}

) : (
{items.map((proj) => (
{feature === 'programme' ? : }

{proj.name}

{proj.date}
))}
) ); return (
{/* Tabs */}
{/* History List */}

{activeTab === 'qto' && (isArabic ? 'مشاريع حصر الكميات السابقة' : 'Takeoff History')} {activeTab === 'programme' && (isArabic ? 'تاريخ الجداول الزمنية' : 'Work Programme History')} {activeTab === 'cashflow' && (isArabic ? 'التدفقات النقدية السابقة' : 'Cash Flow History')}

{activeTab === 'qto' && renderQto()} {activeTab === 'programme' && renderModule(progProjects, 'programme')} {activeTab === 'cashflow' && renderModule(cfProjects, 'cashflow')}
); }