import { useState, useEffect } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import PageHeader from '../../components/PageHeader';
import { Card } from '../../components/ui/card';
import { Button } from '../../components/ui/button';
import { Input } from '../../components/ui/input';
import { Label } from '../../components/ui/label';
import { Textarea } from '../../components/ui/textarea';
import { Switch } from '../../components/ui/switch';
import { Separator } from '../../components/ui/separator';
import {
HiOutlineArrowLeft,
HiOutlineBookOpen,
HiOutlineChevronRight,
} from 'react-icons/hi2';
import courseService from '@/services/courseService';
function CourseFormPage() {
const { courseId } = useParams();
const navigate = useNavigate();
const isEditing = Boolean(courseId);
const [form, setForm] = useState({
courseCode: '',
title: '',
slug: '',
description: '',
image: '',
isPublished: false,
});
const [loading, setLoading] = useState(isEditing);
const [saving, setSaving] = useState(false);
const [error, setError] = useState(null);
useEffect(() => {
if (!isEditing) return;
const fetchCourse = async () => {
try {
const data = await courseService.getById(courseId);
setForm({
courseCode: data.courseCode || '',
title: data.title || '',
slug: data.slug || '',
description: data.description || '',
image: data.image || '',
isPublished: data.isPublished || false,
});
} catch (err) {
setError(err.message || 'Failed to load course');
} finally {
setLoading(false);
}
};
fetchCourse();
}, [courseId, isEditing]);
const handleChange = (field, value) => {
setForm((prev) => ({ ...prev, [field]: value }));
};
const generateSlug = () => {
const slug = form.title
.toLowerCase()
.normalize('NFD')
.replace(/[\u0300-\u036f]/g, '')
.replace(/đ/g, 'd')
.replace(/[^a-z0-9\s-]/g, '')
.replace(/\s+/g, '-')
.replace(/-+/g, '-')
.trim();
handleChange('slug', slug);
};
const handleSave = async (publish) => {
if (!form.courseCode.trim() || !form.title.trim()) {
setError('Course code and title are required');
return;
}
setSaving(true);
setError(null);
try {
const payload = { ...form, isPublished: publish };
if (isEditing) {
await courseService.update(courseId, payload);
} else {
const created = await courseService.create(payload);
navigate(`/courses/${created.id}`);
return;
}
navigate(`/courses/${courseId}`);
} catch (err) {
setError(err.message || 'Failed to save course');
} finally {
setSaving(false);
}
};
if (loading) {
return (
<>