import React, { useState, useEffect } from 'react'; import { Link, useNavigate } from 'react-router-dom'; import { DatePicker, Select, Input, message } from 'antd'; import { ArrowLeft, Calendar, Users, DollarSign, Target, FileText, CheckCircle, TrendingUp } from 'feather-icons-react'; import { LoadingButton } from '../../components/Loading'; import dayjs from 'dayjs'; const { Option } = Select; const { TextArea } = Input; const CreateProject = () => { const navigate = useNavigate(); const [loading, setLoading] = useState(false); const [categoriesLoading, setCategoriesLoading] = useState(true); const [usersLoading, setUsersLoading] = useState(true); const [formData, setFormData] = useState({ projectName: '', description: '', clientName: '', categoryId: '', priority: 'medium', status: 'planning', startDate: dayjs(), endDate: dayjs().add(1, 'month'), budget: '', progressPercentage: 0, managers: [], teamMembers: [], tags: [] }); const [errors, setErrors] = useState({}); const [categories, setCategories] = useState([]); const [users, setUsers] = useState([]); // Load categories from API const loadCategories = async () => { try { const apiBaseUrl = process.env.REACT_APP_API_BASE_URL || ''; const response = await fetch(`${apiBaseUrl}ProjectCategories`, { method: 'GET', headers: { 'Content-Type': 'application/json', 'Accept': 'application/json' } }); if (response.ok) { const result = await response.json(); setCategories(result.data || []); } else { console.error('Failed to load categories'); // Fallback to sample data setCategories([ { id: 1, name: 'Web Development', color: 'blue' }, { id: 2, name: 'Mobile App', color: 'green' }, { id: 3, name: 'Design', color: 'purple' }, { id: 4, name: 'Marketing', color: 'orange' } ]); } } catch (error) { console.error('Error loading categories:', error); // Fallback to sample data setCategories([ { id: 1, name: 'Web Development', color: 'blue' }, { id: 2, name: 'Mobile App', color: 'green' }, { id: 3, name: 'Design', color: 'purple' }, { id: 4, name: 'Marketing', color: 'orange' } ]); } finally { setCategoriesLoading(false); } }; // Load users from API const loadUsers = async () => { try { const apiBaseUrl = process.env.REACT_APP_API_BASE_URL || ''; const response = await fetch(`${apiBaseUrl}Users`, { method: 'GET', headers: { 'Content-Type': 'application/json', 'Accept': 'application/json' } }); if (response.ok) { const result = await response.json(); setUsers(result.data || []); } else { console.error('Failed to load users'); // Fallback to sample data setUsers([ { id: 1, fullName: 'John Smith', email: 'john@example.com' }, { id: 2, fullName: 'Sarah Johnson', email: 'sarah@example.com' }, { id: 3, fullName: 'Mike Wilson', email: 'mike@example.com' }, { id: 4, fullName: 'Lisa Chen', email: 'lisa@example.com' } ]); } } catch (error) { console.error('Error loading users:', error); // Fallback to sample data setUsers([ { id: 1, fullName: 'John Smith', email: 'john@example.com' }, { id: 2, fullName: 'Sarah Johnson', email: 'sarah@example.com' }, { id: 3, fullName: 'Mike Wilson', email: 'mike@example.com' }, { id: 4, fullName: 'Lisa Chen', email: 'lisa@example.com' } ]); } finally { setUsersLoading(false); } }; // Load data on component mount useEffect(() => { loadCategories(); loadUsers(); }, []); // Avatar component with initials fallback const UserAvatar = ({ initials, name }) => (
{initials}
); // Generate initials from name const getInitials = (name) => { return name .split(' ') .map(word => word.charAt(0)) .join('') .toUpperCase() .substring(0, 2); }; const handleInputChange = (field, value) => { setFormData(prev => ({ ...prev, [field]: value })); // Clear error when user starts typing if (errors[field]) { setErrors(prev => ({ ...prev, [field]: '' })); } }; const validateForm = () => { const newErrors = {}; if (!formData.projectName.trim()) { newErrors.projectName = 'Project name is required'; } if (!formData.description.trim()) { newErrors.description = 'Project description is required'; } if (!formData.categoryId) { newErrors.categoryId = 'Please select a category'; } if (!formData.clientName.trim()) { newErrors.clientName = 'Client name is required'; } if (!formData.budget.trim()) { newErrors.budget = 'Budget is required'; } else if (isNaN(parseFloat(formData.budget))) { newErrors.budget = 'Budget must be a valid number'; } if (formData.progressPercentage < 0 || formData.progressPercentage > 100) { newErrors.progressPercentage = 'Progress must be between 0 and 100'; } if (dayjs(formData.endDate).isBefore(dayjs(formData.startDate))) { newErrors.endDate = 'End date must be after start date'; } setErrors(newErrors); return Object.keys(newErrors).length === 0; }; const handleSubmit = async (e) => { e.preventDefault(); if (!validateForm()) { return; } setLoading(true); try { const apiBaseUrl = process.env.REACT_APP_API_BASE_URL || ''; // Prepare data for API - Simple format const projectData = { projectName: formData.projectName, description: formData.description, clientName: formData.clientName, categoryId: parseInt(formData.categoryId), priority: formData.priority, status: formData.status, startDate: formData.startDate.format('YYYY-MM-DD'), endDate: formData.endDate.format('YYYY-MM-DD'), budget: parseFloat(formData.budget), progressPercentage: parseInt(formData.progressPercentage) }; console.log('Sending project data:', projectData); const response = await fetch(`${apiBaseUrl}Projects`, { method: 'POST', headers: { 'Content-Type': 'application/json', 'Accept': 'application/json' }, body: JSON.stringify(projectData) }); if (response.ok) { const result = await response.json(); console.log('Project created successfully:', result); message.success('Project created successfully!'); // Redirect to project list setTimeout(() => { navigate('/project-tracker'); }, 1500); } else { const errorData = await response.json(); console.error('API Error:', errorData); message.error(errorData.message || 'Failed to create project. Please try again.'); } } catch (error) { console.error('Error creating project:', error); message.error('Network error. Please check your connection and try again.'); } finally { setLoading(false); } }; return (
{/* Header */}

Create New Project

Add a new project to your workspace
Back to Projects
{/* Form */}
{/* Project Basic Info */}
Project Information
handleInputChange('projectName', e.target.value)} placeholder="Enter project name" /> {errors.projectName &&
{errors.projectName}
}
handleInputChange('clientName', e.target.value)} placeholder="Enter client name" /> {errors.clientName &&
{errors.clientName}
}