// frontend/src/features/dashboard/teacher/UploadStudyPack.jsx
import { useState, useEffect } from "react";
import {
  Breadcrumbs,
  Link as MuiLink,
  Typography,
  Box,
  TextField,
  Button,
  Alert,
  Select,
  MenuItem,
  IconButton,
  FormControl,
  InputLabel,
  Paper,
  CircularProgress,
  InputAdornment,
} from "@mui/material";
import { Link, useLocation } from "react-router-dom";
import StudentSidebar from "../../../components/TeacherSidebar/index";
import StudentHeader from "../../../components/TeacherHeader/index";
import axios from "axios";
import {
  BookMarked,
  ImagePlus,
  Plus,
  Trash2,
  Upload,
  DollarSign,
  BookOpen,
  Link as LinkIcon,
  FileText,
  Film,
} from "lucide-react";

const API_BASE = import.meta.env.VITE_API_BASE_URL || "http://localhost:5000";

const fieldSx = {
  "& .MuiOutlinedInput-root": {
    borderRadius: 2,
    bgcolor: "#f8fafc",
    transition: "background-color 0.2s ease",
    "&:hover": { bgcolor: "#f1f5f9" },
    "&:hover fieldset": { borderColor: "rgba(79, 70, 229, 0.35)" },
    "&.Mui-focused": { bgcolor: "#fff" },
    "&.Mui-focused fieldset": { borderColor: "rgb(79 70 229)", borderWidth: "1.5px" },
  },
  "& .MuiInputLabel-root": {
    color: "rgb(100 116 139)",
    "&.Mui-focused": { color: "rgb(79 70 229)" },
  },
};

const UploadStudyPack = () => {
  const [formData, setFormData] = useState({ title: "", subject: "", price: "" });
  const [coverPhoto, setCoverPhoto] = useState(null);
  const [coverPreview, setCoverPreview] = useState(null);
  const [filesData, setFilesData] = useState([{ lessonName: "", type: "pdf", content: null }]);
  const [error, setError] = useState(null);
  const [success, setSuccess] = useState(null);
  const [submitting, setSubmitting] = useState(false);
  const location = useLocation();
  const [isSidebarCollapsed, setIsSidebarCollapsed] = useState(false);
  const [isMobile, setIsMobile] = useState(false);

  const toggleSidebar = () => setIsSidebarCollapsed(!isSidebarCollapsed);

  const handleChange = (e) => {
    setFormData({ ...formData, [e.target.name]: e.target.value });
  };

  const handleFileDataChange = (index, field, value) => {
    const updated = [...filesData];
    updated[index][field] = value;
    if (field === "type" && value === "url") {
      updated[index].content = "";
    }
    if (field === "type" && value !== "url") {
      updated[index].content = null;
    }
    setFilesData(updated);
  };

  const handleFileChange = (index, e) => {
    const updated = [...filesData];
    updated[index].content = e.target.files?.[0] ?? null;
    setFilesData(updated);
  };

  const handleCoverChange = (e) => {
    const file = e.target.files?.[0];
    setCoverPhoto(file || null);
    if (coverPreview) URL.revokeObjectURL(coverPreview);
    setCoverPreview(file ? URL.createObjectURL(file) : null);
  };

  useEffect(() => {
    return () => {
      if (coverPreview) URL.revokeObjectURL(coverPreview);
    };
  }, [coverPreview]);

  const addFileField = () => {
    setFilesData([...filesData, { lessonName: "", type: "pdf", content: null }]);
  };

  const removeFileField = (index) => {
    if (filesData.length <= 1) return;
    setFilesData(filesData.filter((_, i) => i !== index));
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    setError(null);
    setSuccess(null);
    setSubmitting(true);

    const data = new FormData();
    data.append("title", formData.title);
    data.append("subject", formData.subject);
    data.append("price", formData.price);
    data.append("coverPhoto", coverPhoto);
    data.append(
      "filesData",
      JSON.stringify(filesData.filter((file) => file.lessonName && (file.type === "url" ? file.content : true)))
    );

    filesData.forEach((fileData) => {
      if (fileData.type !== "url" && fileData.content) {
        data.append("files", fileData.content);
      }
    });

    try {
      const userInfo = JSON.parse(localStorage.getItem("userInfo"));
      const config = {
        headers: { Authorization: `Bearer ${userInfo.token}`, "Content-Type": "multipart/form-data" },
      };
      await axios.post(`${API_BASE}/api/studypacks/upload`, data, config);
      setSuccess("Study pack uploaded successfully.");
      setFormData({ title: "", subject: "", price: "" });
      setCoverPhoto(null);
      if (coverPreview) URL.revokeObjectURL(coverPreview);
      setCoverPreview(null);
      setFilesData([{ lessonName: "", type: "pdf", content: null }]);
    } catch (err) {
      setError(err.response?.data?.message || "Upload failed. Please try again.");
    } finally {
      setSubmitting(false);
    }
  };

  useEffect(() => {
    const handleResize = () => {
      const mobileView = window.innerWidth <= 768;
      setIsMobile(mobileView);
      setIsSidebarCollapsed(mobileView);
    };
    handleResize();
    window.addEventListener("resize", handleResize);
    return () => window.removeEventListener("resize", handleResize);
  }, []);

  const pathnames = location.pathname.split("/").filter((x) => x);
  const formatSegment = (s) =>
    s
      .split("-")
      .map((w) => w.charAt(0).toUpperCase() + w.slice(1))
      .join(" ");

  const breadcrumbItems = pathnames.map((value, index) => {
    const last = index === pathnames.length - 1;
    const to = `/${pathnames.slice(0, index + 1).join("/")}`;
    const displayName = formatSegment(value);

    return last ? (
      <Typography key={to} sx={{ color: "rgb(15 23 42)", fontWeight: 600, fontSize: "0.875rem" }}>
        {displayName}
      </Typography>
    ) : (
      <MuiLink
        key={to}
        component={Link}
        to={to}
        underline="hover"
        sx={{ color: "rgb(79 70 229)", fontWeight: 500, fontSize: "0.875rem" }}
      >
        {displayName}
      </MuiLink>
    );
  });

  const barOffset = isSidebarCollapsed
    ? "ml-[60px] w-[calc(100%-60px)]"
    : "ml-[18%] w-[calc(100%-18%)] md:ml-[250px] md:w-[calc(100%-250px)]";

  useEffect(() => {
    document.title = "Upload study pack - Teacher - EduConnect";
  }, []);

  return (
    <div className="min-h-screen bg-slate-50">
      <StudentHeader
        isSidebarCollapsed={isSidebarCollapsed}
        toggleSidebar={toggleSidebar}
        isMobile={isMobile}
      />

      <div className="flex min-h-screen">
        <div
          className={`fixed left-0 top-0 z-50 h-full transition-all duration-300 ${
            isSidebarCollapsed ? "w-[60px]" : "w-[18%] md:w-[250px]"
          }`}
        >
          <StudentSidebar isCollapsed={isSidebarCollapsed} toggleSidebar={toggleSidebar} />
        </div>

        <div
          className={`flex-1 transition-all duration-300 ${
            isSidebarCollapsed ? "ml-[60px]" : "ml-[18%] md:ml-[250px]"
          }`}
        >
          <div
            className={`fixed left-0 top-0 z-30 mt-[50px] border-b border-slate-200/80 bg-white/95 px-4 py-3 shadow-sm backdrop-blur-sm transition-all duration-300 md:px-6 ${barOffset}`}
          >
            <Breadcrumbs aria-label="breadcrumb" separator="›" sx={{ "& .MuiBreadcrumbs-separator": { color: "rgb(148 163 184)" } }}>
              <MuiLink component={Link} to="/teacher/dashboard" underline="hover" sx={{ color: "rgb(79 70 229)", fontWeight: 500, fontSize: "0.875rem" }}>
                Dashboard
              </MuiLink>
              {breadcrumbItems}
            </Breadcrumbs>
          </div>

          <div className="mt-[104px] h-[calc(100vh-104px)] overflow-y-auto px-4 py-6 md:px-8">
            <div className="mx-auto max-w-3xl">
              <Box sx={{ mb: 4 }}>
                <Typography
                  variant="h4"
                  sx={{
                    fontWeight: 700,
                    letterSpacing: "-0.02em",
                    color: "rgb(15 23 42)",
                    display: "flex",
                    alignItems: "center",
                    gap: 1.5,
                    fontSize: { xs: "1.5rem", md: "1.875rem" },
                  }}
                >
                  <BookMarked size={32} strokeWidth={1.75} className="text-indigo-600" aria-hidden />
                  Upload study pack
                </Typography>
                <Typography sx={{ mt: 0.75, color: "rgb(100 116 139)", fontWeight: 500, fontSize: "0.9375rem" }}>
                  Add details, cover image, and lesson files or links for students to purchase
                </Typography>
              </Box>

              {error && (
                <Alert severity="error" onClose={() => setError(null)} sx={{ mb: 2, borderRadius: 2 }}>
                  {error}
                </Alert>
              )}
              {success && (
                <Alert severity="success" onClose={() => setSuccess(null)} sx={{ mb: 2, borderRadius: 2 }}>
                  {success}
                </Alert>
              )}

              <form onSubmit={handleSubmit}>
                <Paper
                  elevation={0}
                  sx={{
                    p: { xs: 2, md: 3 },
                    mb: 2.5,
                    borderRadius: 3,
                    border: "1px solid rgba(15, 23, 42, 0.08)",
                    boxShadow: "0 1px 3px rgba(15, 23, 42, 0.06)",
                  }}
                >
                  <Box sx={{ display: "flex", alignItems: "center", gap: 1, mb: 2 }}>
                    <BookOpen size={20} strokeWidth={1.75} className="text-indigo-600" />
                    <Typography variant="subtitle1" sx={{ fontWeight: 700, color: "rgb(15 23 42)" }}>
                      Study pack details
                    </Typography>
                  </Box>
                  <TextField
                    fullWidth
                    label="Title"
                    name="title"
                    value={formData.title}
                    onChange={handleChange}
                    margin="normal"
                    required
                    size="small"
                    sx={{ ...fieldSx, mt: 0 }}
                  />
                  <TextField
                    fullWidth
                    label="Subject"
                    name="subject"
                    value={formData.subject}
                    onChange={handleChange}
                    margin="normal"
                    required
                    size="small"
                    sx={fieldSx}
                  />
                  <TextField
                    fullWidth
                    label="Price (USD)"
                    name="price"
                    type="number"
                    inputProps={{ min: 0, step: "0.01" }}
                    value={formData.price}
                    onChange={handleChange}
                    margin="normal"
                    required
                    size="small"
                    InputProps={{
                      startAdornment: (
                        <InputAdornment position="start">
                          <DollarSign size={18} strokeWidth={1.75} className="text-slate-400" aria-hidden />
                        </InputAdornment>
                      ),
                    }}
                    sx={fieldSx}
                  />
                </Paper>

                <Paper
                  elevation={0}
                  sx={{
                    p: { xs: 2, md: 3 },
                    mb: 2.5,
                    borderRadius: 3,
                    border: "1px solid rgba(15, 23, 42, 0.08)",
                    boxShadow: "0 1px 3px rgba(15, 23, 42, 0.06)",
                  }}
                >
                  <Box sx={{ display: "flex", alignItems: "center", gap: 1, mb: 2 }}>
                    <ImagePlus size={20} strokeWidth={1.75} className="text-indigo-600" />
                    <Typography variant="subtitle1" sx={{ fontWeight: 700, color: "rgb(15 23 42)" }}>
                      Cover image
                    </Typography>
                  </Box>
                  <Typography variant="body2" sx={{ color: "rgb(100 116 139)", mb: 2 }}>
                    JPG or PNG recommended. This appears on the study pack card in the store.
                  </Typography>
                  <input type="file" id="cover-upload" accept="image/*" className="hidden" onChange={handleCoverChange} required />
                  <Box sx={{ display: "flex", flexWrap: "wrap", alignItems: "center", gap: 2 }}>
                    <label htmlFor="cover-upload">
                      <Button
                        component="span"
                        variant="outlined"
                        startIcon={<ImagePlus size={18} strokeWidth={1.75} />}
                        sx={{
                          textTransform: "none",
                          fontWeight: 600,
                          borderRadius: 2,
                          borderWidth: 1.5,
                          borderColor: "rgba(15, 23, 42, 0.12)",
                          color: "rgb(51 65 85)",
                          "&:hover": { borderWidth: 1.5, bgcolor: "rgba(15, 23, 42, 0.04)" },
                        }}
                      >
                        Choose image
                      </Button>
                    </label>
                    {coverPhoto && (
                      <Typography variant="body2" sx={{ color: "rgb(71 85 105)", fontWeight: 500 }}>
                        {coverPhoto.name}
                      </Typography>
                    )}
                  </Box>
                  {coverPreview && (
                    <Box
                      sx={{
                        mt: 2,
                        borderRadius: 2,
                        overflow: "hidden",
                        border: "1px solid rgba(15, 23, 42, 0.08)",
                        maxWidth: 280,
                      }}
                    >
                      <img src={coverPreview} alt="Cover preview" style={{ width: "100%", display: "block", maxHeight: 160, objectFit: "cover" }} />
                    </Box>
                  )}
                </Paper>

                <Paper
                  elevation={0}
                  sx={{
                    p: { xs: 2, md: 3 },
                    mb: 2.5,
                    borderRadius: 3,
                    border: "1px solid rgba(15, 23, 42, 0.08)",
                    boxShadow: "0 1px 3px rgba(15, 23, 42, 0.06)",
                  }}
                >
                  <Box sx={{ display: "flex", alignItems: "center", gap: 1, mb: 1 }}>
                    <Upload size={20} strokeWidth={1.75} className="text-indigo-600" />
                    <Typography variant="subtitle1" sx={{ fontWeight: 700, color: "rgb(15 23 42)" }}>
                      Lessons & resources
                    </Typography>
                  </Box>
                  <Typography variant="body2" sx={{ color: "rgb(100 116 139)", mb: 2 }}>
                    Each row is one lesson. Add PDFs, videos, or an external URL per lesson.
                  </Typography>

                  <Box sx={{ display: "flex", flexDirection: "column", gap: 2 }}>
                    {filesData.map((fileData, index) => (
                      <Paper
                        key={index}
                        elevation={0}
                        sx={{
                          p: 2,
                          borderRadius: 2,
                          bgcolor: "rgb(248 250 252)",
                          border: "1px solid rgba(15, 23, 42, 0.06)",
                        }}
                      >
                        <Box
                          sx={{
                            display: "flex",
                            flexWrap: "wrap",
                            gap: 2,
                            alignItems: { xs: "stretch", sm: "flex-start" },
                          }}
                        >
                          <TextField
                            label="Lesson name"
                            value={fileData.lessonName}
                            onChange={(e) => handleFileDataChange(index, "lessonName", e.target.value)}
                            sx={{ ...fieldSx, flex: "1 1 200px", minWidth: 160 }}
                            required
                            size="small"
                          />
                          <FormControl size="small" sx={{ minWidth: 140, flex: "0 0 auto" }}>
                            <InputLabel>Type</InputLabel>
                            <Select
                              value={fileData.type}
                              onChange={(e) => handleFileDataChange(index, "type", e.target.value)}
                              label="Type"
                              sx={{ borderRadius: 2, bgcolor: "#f8fafc" }}
                            >
                              <MenuItem value="pdf">
                                <Box sx={{ display: "flex", alignItems: "center", gap: 1 }}>
                                  <FileText size={16} strokeWidth={1.75} />
                                  PDF
                                </Box>
                              </MenuItem>
                              <MenuItem value="video">
                                <Box sx={{ display: "flex", alignItems: "center", gap: 1 }}>
                                  <Film size={16} strokeWidth={1.75} />
                                  Video
                                </Box>
                              </MenuItem>
                              <MenuItem value="url">
                                <Box sx={{ display: "flex", alignItems: "center", gap: 1 }}>
                                  <LinkIcon size={16} strokeWidth={1.75} />
                                  URL
                                </Box>
                              </MenuItem>
                            </Select>
                          </FormControl>

                          {fileData.type === "url" ? (
                            <TextField
                              label="Resource URL"
                              value={fileData.content || ""}
                              onChange={(e) => handleFileDataChange(index, "content", e.target.value)}
                              sx={{ ...fieldSx, flex: "1 1 240px", minWidth: 200 }}
                              required
                              size="small"
                              placeholder="https://"
                            />
                          ) : (
                            <Box sx={{ flex: "1 1 200px", minWidth: 180 }}>
                              <input
                                id={`file-${index}`}
                                type="file"
                                accept={fileData.type === "pdf" ? ".pdf" : "video/*"}
                                className="hidden"
                                onChange={(e) => handleFileChange(index, e)}
                                required={!fileData.content}
                              />
                              <label htmlFor={`file-${index}`}>
                                <Button
                                  component="span"
                                  variant="outlined"
                                  fullWidth
                                  sx={{
                                    textTransform: "none",
                                    fontWeight: 600,
                                    borderRadius: 2,
                                    py: 1,
                                    borderWidth: 1.5,
                                    borderColor: "rgba(15, 23, 42, 0.12)",
                                    color: "rgb(51 65 85)",
                                  }}
                                >
                                  {fileData.content ? fileData.content.name : `Select ${fileData.type === "pdf" ? "PDF" : "video"}`}
                                </Button>
                              </label>
                            </Box>
                          )}

                          <IconButton
                            onClick={() => removeFileField(index)}
                            disabled={filesData.length <= 1}
                            aria-label="Remove lesson"
                            sx={{
                              color: "rgb(239 68 68)",
                              bgcolor: "rgba(239, 68, 68, 0.08)",
                              "&:hover": { bgcolor: "rgba(239, 68, 68, 0.15)" },
                              "&.Mui-disabled": { opacity: 0.4 },
                            }}
                          >
                            <Trash2 size={20} strokeWidth={1.75} />
                          </IconButton>
                        </Box>
                      </Paper>
                    ))}
                  </Box>

                  <Button
                    type="button"
                    startIcon={<Plus size={18} strokeWidth={1.75} />}
                    onClick={addFileField}
                    sx={{
                      mt: 2,
                      textTransform: "none",
                      fontWeight: 600,
                      color: "rgb(79 70 229)",
                      "&:hover": { bgcolor: "rgba(79, 70, 229, 0.08)" },
                    }}
                  >
                    Add another lesson
                  </Button>
                </Paper>

                <Button
                  type="submit"
                  variant="contained"
                  disableElevation
                  disabled={submitting}
                  fullWidth
                  size="large"
                  startIcon={submitting ? <CircularProgress size={20} color="inherit" /> : <Upload size={20} strokeWidth={1.75} />}
                  sx={{
                    py: 1.5,
                    borderRadius: 2,
                    textTransform: "none",
                    fontWeight: 700,
                    fontSize: "1rem",
                    bgcolor: "rgb(79 70 229)",
                    boxShadow: "none",
                    "&:hover": { bgcolor: "rgb(67 56 202)", boxShadow: "0 4px 14px rgba(79, 70, 229, 0.35)" },
                  }}
                >
                  {submitting ? "Uploading…" : "Publish study pack"}
                </Button>
              </form>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};

export default UploadStudyPack;
