//frontend/src/features/dashboard/teacher/TeacherSupportForm.jsx
import { useState, useEffect } from "react";
import {
  Breadcrumbs,
  Link as MuiLink,
  Typography,
  Box,
  TextField,
  Select,
  MenuItem,
  FormControl,
  InputLabel,
  Button,
  Paper,
  Alert,
  CircularProgress,
} from "@mui/material";
import { Link, useLocation, useNavigate } from "react-router-dom";
import TawkMessengerReact from "@tawk.to/tawk-messenger-react";
import StudentSidebar from "../../../components/TeacherSidebar/index";
import StudentHeader from "../../../components/TeacherHeader/index";
import axios from "axios";
import useAuth from "../../../hooks/useAuth";
import { LifeBuoy, Tags, Layers, Mail, MessageSquareText, Send } 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 selectSx = {
  borderRadius: 2,
  bgcolor: "#f8fafc",
  "&:hover": { bgcolor: "#f1f5f9" },
  "&.Mui-focused": { bgcolor: "#fff" },
  "& fieldset": { borderColor: "rgba(15, 23, 42, 0.12)" },
  "&:hover fieldset": { borderColor: "rgba(79, 70, 229, 0.35)" },
  "&.Mui-focused fieldset": { borderColor: "rgb(79 70 229)", borderWidth: "1.5px" },
};

const TeacherSupportForm = () => {
  const { user } = useAuth();
  const navigate = useNavigate();
  const [categories, setCategories] = useState([]);
  const [subcategories, setSubcategories] = useState([]);
  const [categoryId, setCategoryId] = useState("");
  const [subcategoryId, setSubcategoryId] = useState("");
  const [message, setMessage] = useState("");
  const [error, setError] = useState(null);
  const [success, setSuccess] = useState(null);
  const [loading, setLoading] = useState(false);
  const location = useLocation();
  const [isSidebarCollapsed, setIsSidebarCollapsed] = useState(false);
  const [isMobile, setIsMobile] = useState(false);

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

  useEffect(() => {
    const fetchCategories = async () => {
      if (!user?.token) return;
      try {
        const config = { headers: { Authorization: `Bearer ${user.token}` } };
        const { data } = await axios.get(`${API_BASE}/api/auth/support/categories`, config);
        setCategories(data);
      } catch (err) {
        setError(err.response?.data?.message || "Could not load categories.");
      }
    };
    fetchCategories();
  }, [user?.token]);

  useEffect(() => {
    const fetchSubcategories = async () => {
      if (!user?.token || !categoryId) {
        setSubcategories([]);
        setSubcategoryId("");
        return;
      }
      try {
        const config = { headers: { Authorization: `Bearer ${user.token}` } };
        const { data } = await axios.get(`${API_BASE}/api/auth/support/subcategories/${categoryId}`, config);
        setSubcategories(data);
        setSubcategoryId("");
      } catch (err) {
        setError(err.response?.data?.message || "Could not load subcategories.");
      }
    };
    fetchSubcategories();
  }, [categoryId, user?.token]);

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

    try {
      const config = { headers: { Authorization: `Bearer ${user.token}` } };
      const { data } = await axios.post(
        `${API_BASE}/api/auth/support/submit`,
        { categoryId, subcategoryId, message },
        config
      );
      setSuccess(data.message || "Ticket submitted. Redirecting…");
      setCategoryId("");
      setSubcategoryId("");
      setMessage("");
      setTimeout(() => navigate(`/${user.role}/support-ticket`), 2000);
    } catch (err) {
      setError(err.response?.data?.message || "Could not submit your request. Try again.");
    } finally {
      setLoading(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 = "Support - 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-2xl">
              <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" },
                  }}
                >
                  <LifeBuoy size={32} strokeWidth={1.75} className="text-indigo-600" aria-hidden />
                  Submit a support request
                </Typography>
                <Typography sx={{ mt: 0.75, color: "rgb(100 116 139)", fontWeight: 500, fontSize: "0.9375rem" }}>
                  Choose a topic and describe your issue. Our team will respond from your tickets list.
                </Typography>
              </Box>

              {error && (
                <Alert severity="error" onClose={() => setError(null)} sx={{ mb: 2, borderRadius: 2 }}>
                  {error}
                </Alert>
              )}
              {success && (
                <Alert severity="success" 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 }}>
                    <Tags size={20} strokeWidth={1.75} className="text-indigo-600" />
                    <Typography variant="subtitle1" sx={{ fontWeight: 700, color: "rgb(15 23 42)" }}>
                      Category
                    </Typography>
                  </Box>
                  <FormControl fullWidth size="small" sx={{ mb: 2 }}>
                    <InputLabel id="support-category-label">Topic</InputLabel>
                    <Select
                      labelId="support-category-label"
                      value={categoryId}
                      onChange={(e) => setCategoryId(e.target.value)}
                      label="Topic"
                      required
                      sx={selectSx}
                    >
                      <MenuItem value="">
                        <em>Select a category</em>
                      </MenuItem>
                      {categories.map((category) => (
                        <MenuItem key={category._id} value={category._id}>
                          {category.name}
                        </MenuItem>
                      ))}
                    </Select>
                  </FormControl>

                  <Box sx={{ display: "flex", alignItems: "center", gap: 1, mb: 2 }}>
                    <Layers size={20} strokeWidth={1.75} className="text-indigo-600" />
                    <Typography variant="subtitle1" sx={{ fontWeight: 700, color: "rgb(15 23 42)" }}>
                      Subcategory
                    </Typography>
                  </Box>
                  <FormControl fullWidth size="small" sx={{ mb: 0 }} disabled={!categoryId}>
                    <InputLabel id="support-subcategory-label">Detail</InputLabel>
                    <Select
                      labelId="support-subcategory-label"
                      value={subcategoryId}
                      onChange={(e) => setSubcategoryId(e.target.value)}
                      label="Detail"
                      required
                      sx={selectSx}
                    >
                      <MenuItem value="">
                        <em>{categoryId ? "Select a subcategory" : "Choose a category first"}</em>
                      </MenuItem>
                      {subcategories.map((subcategory) => (
                        <MenuItem key={subcategory._id} value={subcategory._id}>
                          {subcategory.name}
                        </MenuItem>
                      ))}
                    </Select>
                  </FormControl>
                </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 }}>
                    <Mail size={20} strokeWidth={1.75} className="text-indigo-600" />
                    <Typography variant="subtitle1" sx={{ fontWeight: 700, color: "rgb(15 23 42)" }}>
                      Contact
                    </Typography>
                  </Box>
                  <TextField
                    fullWidth
                    label="Your email"
                    value={user?.email || ""}
                    size="small"
                    sx={{ ...fieldSx, mb: 0 }}
                    disabled
                    helperText="We’ll use this account email for follow-up"
                  />
                </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 }}>
                    <MessageSquareText size={20} strokeWidth={1.75} className="text-indigo-600" />
                    <Typography variant="subtitle1" sx={{ fontWeight: 700, color: "rgb(15 23 42)" }}>
                      Message
                    </Typography>
                  </Box>
                  <TextField
                    fullWidth
                    label="Describe your issue"
                    value={message}
                    onChange={(e) => setMessage(e.target.value)}
                    multiline
                    minRows={5}
                    required
                    placeholder="Include steps to reproduce, class names, or screenshots if relevant…"
                    sx={fieldSx}
                  />
                </Paper>

                <Button
                  type="submit"
                  variant="contained"
                  disableElevation
                  fullWidth
                  size="large"
                  disabled={loading}
                  startIcon={loading ? <CircularProgress size={20} color="inherit" /> : <Send 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)" },
                  }}
                >
                  {loading ? "Sending…" : "Submit request"}
                </Button>
              </form>

              <Paper
                elevation={0}
                sx={{
                  mt: 4,
                  p: 2.5,
                  borderRadius: 3,
                  border: "1px dashed rgba(148, 163, 184, 0.7)",
                  bgcolor: "rgba(248, 250, 252, 0.8)",
                }}
              >
                <Typography variant="body2" sx={{ color: "rgb(100 116 139)", mb: 1.5, fontWeight: 600 }}>
                  Live chat
                </Typography>
                <Typography variant="caption" sx={{ color: "rgb(148 163 184)", display: "block", mb: 2 }}>
                  Prefer chat? Use the widget below when it’s available.
                </Typography>
                <Box sx={{ minHeight: 56, position: "relative" }}>
                  <TawkMessengerReact propertyId="add your tawk property id" widgetId="add your tawk widget id" />
                </Box>
              </Paper>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};

export default TeacherSupportForm;
