import React, { useState, useEffect } from "react";
import {
    Box,
    Typography,
    Table,
    TableBody,
    TableCell,
    TableContainer,
    TableHead,
    TableRow,
    Button,
    Dialog,
    DialogActions,
    DialogContent,
    DialogTitle,
    TextField,
    FormControl,
    InputLabel,
    Select,
    MenuItem,
    IconButton,
    Grid,
    Card,
    CardContent,
    Alert,
    Snackbar,
    Divider,
    CircularProgress,
    useTheme,
} from "@mui/material";

import AddIcon from "@mui/icons-material/Add";
import EditIcon from "@mui/icons-material/Edit";
import DeleteIcon from "@mui/icons-material/Delete";
import SchoolIcon from "@mui/icons-material/School";

import { api, endpoints } from "../../services/api";

const AdminClasses = () => {
    const [classes, setClasses] = useState([]);
    const [loading, setLoading] = useState(true);
    const [openDialog, setOpenDialog] = useState(false);
    const [formData, setFormData] = useState({
        id: null,
        nom: "",
        enseignant_responsable: null,
    });
    const [editMode, setEditMode] = useState(false);
    const [teachers, setTeachers] = useState([]);
    const [error, setError] = useState(null);
    const theme = useTheme();

    const fetchData = async () => {
        setLoading(true);
        setError(null);

        try {
            const [classesResponse, teachersResponse] = await Promise.all([
                api.get(endpoints.classes.list),
                api.get(endpoints.teachers.list),
            ]);

            if (!classesResponse.ok || !teachersResponse.ok) {
                throw new Error("Failed to load data");
            }

            const classesData = await classesResponse.json();
            const teachersData = await teachersResponse.json();

            setClasses(Array.isArray(classesData) ? classesData : []);
            setTeachers(Array.isArray(teachersData) ? teachersData : []);
        } catch (error) {
            console.error("Error fetching data:", error);
            setError("Error loading data");
        } finally {
            setLoading(false);
        }
    };

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

    const handleOpenDialog = (classItem = null) => {
        if (classItem) {
            setFormData({
                id: classItem.id,
                nom: classItem.nom || "",
                enseignant_responsable:
                    classItem.enseignant_responsable?.id || null,
            });
            setEditMode(true);
        } else {
            setFormData({
                id: null,
                nom: "",
                enseignant_responsable: null,
            });
            setEditMode(false);
        }

        setOpenDialog(true);
    };

    const handleCloseDialog = () => {
        setOpenDialog(false);
    };

    const handleInputChange = (event) => {
        const { name, value } = event.target;

        setFormData((previousData) => ({
            ...previousData,
            [name]: value,
        }));
    };

    const handleSubmit = async () => {
        if (!formData.nom.trim()) {
            setError("Please enter the class name");
            return;
        }

        try {
            const data = {
                nom: formData.nom.trim(),
                enseignant_responsable_id:
                    formData.enseignant_responsable || null,
            };

            let response;

            if (editMode) {
                response = await api.put(
                    endpoints.classes.update(formData.id),
                    data
                );
            } else {
                response = await api.post(endpoints.classes.create, data);
            }

            if (!response.ok) {
                let message = "Request failed";

                try {
                    const errorData = await response.json();
                    message = errorData.error || errorData.message || message;
                } catch {
                    // Keep the default error message.
                }

                throw new Error(message);
            }

            await fetchData();
            setOpenDialog(false);
        } catch (error) {
            console.error("Error saving class:", error);
            setError(error.message || "An error occurred while saving");
        }
    };

    const handleDelete = async (id) => {
        const confirmed = window.confirm(
            "Are you sure you want to delete this class?"
        );

        if (!confirmed) {
            return;
        }

        try {
            const response = await api.delete(endpoints.classes.delete(id));

            let data = {};

            try {
                data = await response.json();
            } catch {
                // Some successful delete endpoints return an empty response.
            }

            if (!response.ok || data.success === false) {
                throw new Error(data.error || "Unable to delete the class");
            }

            await fetchData();
        } catch (error) {
            console.error("Error deleting class:", error);
            setError(error.message || "Error deleting class");
        }
    };

    return (
        <Box>
            <Box sx={{ mb: 4 }}>
                <Typography
                    variant="h4"
                    color="primary.main"
                    fontWeight="bold"
                    gutterBottom
                >
                    Class Management
                </Typography>

                <Typography
                    variant="subtitle1"
                    color="text.secondary"
                    gutterBottom
                >
                    Manage your classes and their information
                </Typography>

                <Divider sx={{ mt: 1, mb: 3 }} />
            </Box>

            {loading && (
                <Box
                    sx={{
                        display: "flex",
                        justifyContent: "center",
                        my: 4,
                    }}
                >
                    <CircularProgress />
                </Box>
            )}

            <Snackbar
                open={Boolean(error)}
                autoHideDuration={6000}
                onClose={() => setError(null)}
            >
                <Alert
                    onClose={() => setError(null)}
                    severity="error"
                    sx={{ width: "100%" }}
                >
                    {error}
                </Alert>
            </Snackbar>

            <Grid container spacing={3} sx={{ mb: 4 }}>
                <Grid item xs={12} sm={6} md={3}>
                    <Card
                        elevation={2}
                        sx={{
                            height: 140,
                            borderLeft: `4px solid ${theme.palette.primary.main}`,
                            transition: "transform 0.3s, box-shadow 0.3s",
                            "&:hover": {
                                transform: "translateY(-5px)",
                                boxShadow: theme.shadows[4],
                            },
                        }}
                    >
                        <CardContent
                            sx={{
                                height: "100%",
                                display: "flex",
                                flexDirection: "column",
                                justifyContent: "space-between",
                            }}
                        >
                            <Box
                                sx={{
                                    display: "flex",
                                    justifyContent: "space-between",
                                    alignItems: "center",
                                }}
                            >
                                <Typography
                                    variant="subtitle2"
                                    color="text.secondary"
                                >
                                    Total Classes
                                </Typography>

                                <SchoolIcon
                                    fontSize="medium"
                                    sx={{ color: theme.palette.primary.main }}
                                />
                            </Box>

                            <Box>
                                <Typography
                                    variant="h3"
                                    sx={{
                                        fontWeight: "bold",
                                        color: theme.palette.primary.main,
                                    }}
                                >
                                    {classes.length}
                                </Typography>

                                <Typography variant="body2" color="text.secondary">
                                    Existing classes
                                </Typography>
                            </Box>
                        </CardContent>
                    </Card>
                </Grid>
            </Grid>

            <Box
                sx={{
                    display: "flex",
                    justifyContent: "flex-end",
                    mb: 3,
                }}
            >
                <Button
                    variant="contained"
                    startIcon={<AddIcon />}
                    onClick={() => handleOpenDialog()}
                >
                    New Class
                </Button>
            </Box>

            <Card elevation={2}>
                <CardContent sx={{ p: 0 }}>
                    <TableContainer>
                        <Table>
                            <TableHead>
                                <TableRow>
                                    <TableCell sx={{ fontWeight: "bold" }}>
                                        Class Name
                                    </TableCell>

                                    <TableCell
                                        align="center"
                                        sx={{ fontWeight: "bold" }}
                                    >
                                        Assigned Teacher
                                    </TableCell>

                                    <TableCell
                                        align="center"
                                        sx={{ fontWeight: "bold" }}
                                    >
                                        Actions
                                    </TableCell>
                                </TableRow>
                            </TableHead>

                            <TableBody>
                                {classes.length > 0 ? (
                                    classes.map((classItem) => (
                                        <TableRow
                                            key={classItem.id}
                                            hover
                                            sx={{
                                                "&:last-child td, &:last-child th": {
                                                    border: 0,
                                                },
                                                transition: "background-color 0.2s",
                                            }}
                                        >
                                            <TableCell>{classItem.nom}</TableCell>

                                            <TableCell align="center">
                                                {classItem.enseignant_responsable
                                                    ? `${classItem.enseignant_responsable.first_name} ${classItem.enseignant_responsable.last_name}`
                                                    : "Unknown"}
                                            </TableCell>

                                            <TableCell align="center">
                                                <IconButton
                                                    color="primary"
                                                    onClick={() => handleOpenDialog(classItem)}
                                                    size="small"
                                                    aria-label="Edit class"
                                                >
                                                    <EditIcon fontSize="small" />
                                                </IconButton>

                                                <IconButton
                                                    color="error"
                                                    onClick={() => handleDelete(classItem.id)}
                                                    size="small"
                                                    aria-label="Delete class"
                                                >
                                                    <DeleteIcon fontSize="small" />
                                                </IconButton>
                                            </TableCell>
                                        </TableRow>
                                    ))
                                ) : (
                                    !loading && (
                                        <TableRow>
                                            <TableCell colSpan={3} align="center">
                                                No classes available
                                            </TableCell>
                                        </TableRow>
                                    )
                                )}
                            </TableBody>
                        </Table>
                    </TableContainer>
                </CardContent>
            </Card>

            <Dialog
                open={openDialog}
                onClose={handleCloseDialog}
                maxWidth="md"
                fullWidth
            >
                <DialogTitle>
                    {editMode ? "Edit Class" : "Create New Class"}
                </DialogTitle>

                <DialogContent>
                    <Grid container spacing={2} sx={{ mt: 1 }}>
                        <Grid item xs={12} sm={6}>
                            <TextField
                                name="nom"
                                label="Class Name"
                                fullWidth
                                value={formData.nom}
                                onChange={handleInputChange}
                                required
                            />
                        </Grid>

                        <Grid item xs={12} sm={6}>
                            <FormControl fullWidth>
                                <InputLabel id="teacher-label">
                                    Assigned Teacher
                                </InputLabel>

                                <Select
                                    labelId="teacher-label"
                                    label="Assigned Teacher"
                                    name="enseignant_responsable"
                                    value={formData.enseignant_responsable || ""}
                                    onChange={handleInputChange}
                                >
                                    <MenuItem value="">
                                        <em>No teacher assigned</em>
                                    </MenuItem>

                                    {teachers.map((teacher) => (
                                        <MenuItem key={teacher.id} value={teacher.id}>
                                            {teacher.first_name} {teacher.last_name}
                                        </MenuItem>
                                    ))}
                                </Select>
                            </FormControl>
                        </Grid>
                    </Grid>
                </DialogContent>

                <DialogActions>
                    <Button onClick={handleCloseDialog}>Cancel</Button>

                    <Button onClick={handleSubmit} variant="contained">
                        {editMode ? "Update" : "Create"}
                    </Button>
                </DialogActions>
            </Dialog>
        </Box>
    );
};

export default AdminClasses;
