import React, { useState, useEffect } from "react";
import {
    Box,
    Typography,
    Table,
    TableBody,
    TableCell,
    TableContainer,
    TableHead,
    TableRow,
    Button,
    Dialog,
    DialogActions,
    DialogContent,
    DialogTitle,
    TextField,
    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 CloudUploadIcon from "@mui/icons-material/CloudUpload";
import GetAppIcon from "@mui/icons-material/GetApp";
import PersonIcon from "@mui/icons-material/Person";

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

const AdminTeachers = () => {
    const [teachers, setTeachers] = useState([]);
    const [loading, setLoading] = useState(true);
    const [openDialog, setOpenDialog] = useState(false);

    const [formData, setFormData] = useState({
        id: null,
        first_name: "",
        last_name: "",
        email: "",
        phone: "",
    });

    const [editMode, setEditMode] = useState(false);
    const [error, setError] = useState(null);

    const theme = useTheme();

    // Fetch teachers from the backend
    const fetchTeachers = async () => {
        setLoading(true);
        setError(null);

        try {
            const response = await api.get(endpoints.teachers.list);
            const data = await response.json();

            setTeachers(data);
        } catch (error) {
            console.error("Error fetching teachers:", error);
            setError("Error loading teachers");
        } finally {
            setLoading(false);
        }
    };

    // Load teachers when the component mounts
    useEffect(() => {
        fetchTeachers();
    }, []);

    // Open the dialog for adding or editing a teacher
    const handleOpenDialog = (teacher = null) => {
        if (teacher) {
            setFormData({
                id: teacher.id,
                first_name: teacher.first_name || "",
                last_name: teacher.last_name || "",
                email: teacher.email || "",
                phone: teacher.phone || "",
            });

            setEditMode(true);
        } else {
            setFormData({
                id: null,
                first_name: "",
                last_name: "",
                email: "",
                phone: "",
            });

            setEditMode(false);
        }

        setOpenDialog(true);
    };

    // Close the dialog
    const handleCloseDialog = () => {
        setOpenDialog(false);
    };

    // Handle form input changes
    const handleInputChange = (event) => {
        const { name, value } = event.target;

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

    // Create or update a teacher
    const handleSubmit = async () => {
        if (
            !formData.first_name.trim() ||
            !formData.last_name.trim() ||
            !formData.email.trim() ||
            !formData.phone.trim()
        ) {
            setError("Please complete all required fields");
            return;
        }

        try {
            const data = {
                first_name: formData.first_name.trim(),
                last_name: formData.last_name.trim(),
                email: formData.email.trim(),
                phone: formData.phone.trim(),
            };

            let response;

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

            if (!response.ok) {
                throw new Error("Request failed");
            }

            await fetchTeachers();
            setOpenDialog(false);
        } catch (error) {
            console.error("Error saving teacher:", error);
            setError("An error occurred while saving the teacher");
        }
    };

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

        if (!confirmed) {
            return;
        }

        try {
            const response = await api.delete(endpoints.teachers.delete(id));
            const data = await response.json();

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

            await fetchTeachers();
        } catch (error) {
            console.error("Error deleting teacher:", error);
            setError(error.message || "Error deleting the teacher");
        }
    };

    // Upload a CSV file
    const handleFileUpload = async (event) => {
        const file = event.target.files?.[0];

        if (!file) {
            return;
        }

        const uploadData = new FormData();
        uploadData.append("file", file);

        try {
            const response = await api.post(
                endpoints.teachers.import,
                uploadData,
                true
            );

            if (!response.ok) {
                const errorData = await response.json();

                throw new Error(
                    errorData.error || "Error importing the CSV file"
                );
            }

            await fetchTeachers();
        } catch (error) {
            console.error("Error importing CSV file:", error);
            setError(error.message || "An unexpected error occurred");
        } finally {
            event.target.value = "";
        }
    };

    // Download the CSV template
    const downloadTemplate = () => {
        const headers = [
            "Last Name",
            "First Name",
            "Email",
            "Phone Number",
        ];

        let csvContent = `${headers.join(",")}\n`;

        if (teachers.length > 0) {
            teachers.forEach((teacher) => {
                const row = [
                    teacher.last_name || "",
                    teacher.first_name || "",
                    teacher.email || "",
                    teacher.phone || "",
                ];

                csvContent += `${row.join(",")}\n`;
            });
        }

        const blob = new Blob([csvContent], {
            type: "text/csv;charset=utf-8;",
        });

        const url = URL.createObjectURL(blob);
        const link = document.createElement("a");

        link.href = url;
        link.download = "teachers_template.csv";

        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);

        URL.revokeObjectURL(url);
    };

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

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

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

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

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

            {/* Statistics cards */}
            <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 Teachers
                                </Typography>

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

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

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

            {/* Action buttons */}
            <Box
                sx={{
                    display: "flex",
                    justifyContent: "flex-end",
                    flexWrap: "wrap",
                    gap: 2,
                    mb: 3,
                }}
            >
                <Button
                    variant="contained"
                    startIcon={<GetAppIcon />}
                    onClick={downloadTemplate}
                >
                    Download Template
                </Button>

                <Button
                    variant="contained"
                    component="label"
                    startIcon={<CloudUploadIcon />}
                >
                    Import CSV

                    <input
                        type="file"
                        hidden
                        accept=".csv,text/csv"
                        onChange={handleFileUpload}
                    />
                </Button>

                <Button
                    variant="contained"
                    startIcon={<AddIcon />}
                    onClick={() => handleOpenDialog()}
                >
                    New Teacher
                </Button>
            </Box>

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

                                    <TableCell
                                        align="center"
                                        sx={{ fontWeight: "bold" }}
                                    >
                                        First Name
                                    </TableCell>

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

                                    <TableCell
                                        align="center"
                                        sx={{ fontWeight: "bold" }}
                                    >
                                        Phone Number
                                    </TableCell>

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

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

                                            <TableCell align="center">
                                                {teacher.first_name}
                                            </TableCell>

                                            <TableCell align="center">
                                                {teacher.email}
                                            </TableCell>

                                            <TableCell align="center">
                                                {teacher.phone}
                                            </TableCell>

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

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

            {/* Add or edit teacher dialog */}
            <Dialog
                open={openDialog}
                onClose={handleCloseDialog}
                maxWidth="md"
                fullWidth
            >
                <DialogTitle>
                    {editMode ? "Edit Teacher" : "Create New Teacher"}
                </DialogTitle>

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

                        <Grid item xs={12} sm={6}>
                            <TextField
                                name="first_name"
                                label="First Name"
                                fullWidth
                                value={formData.first_name}
                                onChange={handleInputChange}
                                required
                            />
                        </Grid>

                        <Grid item xs={12} sm={6}>
                            <TextField
                                name="email"
                                label="Email"
                                type="email"
                                fullWidth
                                value={formData.email}
                                onChange={handleInputChange}
                                required
                            />
                        </Grid>

                        <Grid item xs={12} sm={6}>
                            <TextField
                                name="phone"
                                label="Phone Number"
                                fullWidth
                                value={formData.phone}
                                onChange={handleInputChange}
                                required
                            />
                        </Grid>
                    </Grid>
                </DialogContent>

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

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

export default AdminTeachers;