import { useState, useEffect } from "react";
import axios from "axios";
import {
  Box,
  Typography,
  Paper,
  TextField,
  Button,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  Alert,
  FormControl,
  InputLabel,
  Select,
  MenuItem,
  Grid,
  Chip,
  Stack,
  Skeleton,
  Breadcrumbs,
  Link as MuiLink,
} from "@mui/material";
import useAuth from "../../../hooks/useAuth";
import AdminHeader from "../../../components/AdminHeader/index";
import AdminSidebar from "../../../components/AdminSidebar/index";
import { Link, useLocation } from "react-router-dom";
import {
  Tags,
  Layers,
  Plus,
  Trash2,
  LifeBuoy,
  FolderTree,
} 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 paperCardSx = {
  borderRadius: 3,
  border: "1px solid rgba(15, 23, 42, 0.08)",
  boxShadow: "0 1px 3px rgba(15, 23, 42, 0.06)",
  overflow: "hidden",
};

function categoryIdEquals(a, b) {
  if (a == null || b == null) return false;
  const idA = typeof a === "object" && a._id != null ? String(a._id) : String(a);
  const idB = typeof b === "object" && b._id != null ? String(b._id) : String(b);
  return idA === idB;
}

const AdminSupportCategories = () => {
  const { user } = useAuth();
  const location = useLocation();
  const [isSidebarCollapsed, setIsSidebarCollapsed] = useState(false);
  const [isMobile, setIsMobile] = useState(false);
  const [categories, setCategories] = useState([]);
  const [subcategories, setSubcategories] = useState([]);
  const [newCategory, setNewCategory] = useState("");
  const [newSubcategory, setNewSubcategory] = useState("");
  const [selectedCategoryId, setSelectedCategoryId] = useState("");
  const [error, setError] = useState(null);
  const [success, setSuccess] = useState(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    if (!user?.token) return;
    const fetchData = async () => {
      setLoading(true);
      setError(null);
      try {
        const config = { headers: { Authorization: `Bearer ${user.token}` } };
        const { data: catData } = await axios.get(`${API_BASE}/api/auth/support/categories`, config);
        setCategories(catData);
        const { data: subData } = await axios.get(`${API_BASE}/api/auth/support/subcategories/all`, config);
        setSubcategories(subData);
      } catch (err) {
        console.error("Error fetching support data:", err.response || err);
        setError(err.response?.data?.message || "Could not load support categories.");
      } finally {
        setLoading(false);
      }
    };
    fetchData();
  }, [user?.token]);

  const handleAddCategory = async () => {
    setError(null);
    setSuccess(null);
    try {
      const config = { headers: { Authorization: `Bearer ${user.token}` } };
      const { data } = await axios.post(
        `${API_BASE}/api/auth/admin/support/category`,
        { name: newCategory.trim() },
        config
      );
      setCategories([...categories, data.category]);
      setSuccess(data.message);
      setNewCategory("");
    } catch (err) {
      setError(err.response?.data?.message || "Error adding category");
    }
  };

  const handleAddSubcategory = async () => {
    setError(null);
    setSuccess(null);
    try {
      const config = { headers: { Authorization: `Bearer ${user.token}` } };
      const { data } = await axios.post(
        `${API_BASE}/api/auth/admin/support/subcategory`,
        { name: newSubcategory.trim(), categoryId: selectedCategoryId },
        config
      );
      setSubcategories([...subcategories, data.subcategory]);
      setSuccess(data.message);
      setNewSubcategory("");
      setSelectedCategoryId("");
    } catch (err) {
      setError(err.response?.data?.message || "Error adding subcategory");
    }
  };

  const handleDeleteCategory = async (categoryId) => {
    setError(null);
    try {
      const config = { headers: { Authorization: `Bearer ${user.token}` } };
      const { data } = await axios.delete(
        `${API_BASE}/api/auth/admin/support/subcategory/${categoryId}`,
        config
      );
      setCategories(categories.filter((cat) => cat._id !== categoryId));
      setSubcategories(subcategories.filter((sub) => !categoryIdEquals(sub.categoryId, categoryId)));
      setSuccess(data.message);
    } catch (err) {
      setError(err.response?.data?.message || "Error deleting category");
    }
  };

  const handleDeleteSubcategory = async (subcategoryId) => {
    setError(null);
    try {
      const config = { headers: { Authorization: `Bearer ${user.token}` } };
      const { data } = await axios.delete(
        `${API_BASE}/api/auth/admin/support/subcategory/${subcategoryId}`,
        config
      );
      setSubcategories(subcategories.filter((sub) => sub._id !== subcategoryId));
      setSuccess(data.message);
    } catch (err) {
      setError(err.response?.data?.message || "Error deleting subcategory");
    }
  };

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

  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 categories - Admin - EduConnect";
  }, []);

  const resolveCategoryName = (sub) => {
    const cat = categories.find((c) => categoryIdEquals(c._id, sub.categoryId));
    return cat?.name ?? "—";
  };

  return (
    <div className="min-h-screen bg-slate-50">
      <AdminHeader
        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]"
          }`}
        >
          <AdminSidebar 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="/admin/dashboard"
                underline="hover"
                sx={{ color: "rgb(79 70 229)", fontWeight: 500, fontSize: "0.875rem" }}
              >
                Dashboard
              </MuiLink>
              {breadcrumbItems}
            </Breadcrumbs>
          </div>

          <div className="mt-[104px] min-h-[calc(100vh-104px)] overflow-y-auto px-4 py-6 md:px-8">
            <div className="mx-auto max-w-5xl">
              <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 shrink-0" aria-hidden />
                  Support categories
                </Typography>
                <Typography sx={{ mt: 0.75, color: "rgb(100 116 139)", fontWeight: 500, fontSize: "0.9375rem" }}>
                  Topics and sub-topics used on teacher and institute support forms.
                </Typography>
              </Box>

              <Stack direction="row" spacing={1} flexWrap="wrap" useFlexGap sx={{ mb: 3 }}>
                <Chip
                  label={`${categories.length} categories`}
                  sx={{ bgcolor: "rgba(79, 70, 229, 0.1)", fontWeight: 600, color: "rgb(79 70 229)" }}
                />
                <Chip
                  label={`${subcategories.length} subcategories`}
                  sx={{ bgcolor: "rgba(15, 23, 42, 0.06)", fontWeight: 600, color: "rgb(15 23 42)" }}
                />
              </Stack>

              {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>
              )}

              <Grid container spacing={3} sx={{ mb: 3 }}>
                <Grid item xs={12} md={6}>
                  <Paper elevation={0} sx={{ ...paperCardSx, p: { xs: 2, md: 2.5 }, height: "100%" }}>
                    <Stack direction="row" alignItems="center" spacing={1} sx={{ mb: 2 }}>
                      <Tags size={22} strokeWidth={1.75} className="text-indigo-600" />
                      <Typography variant="subtitle1" sx={{ fontWeight: 700, color: "rgb(15 23 42)" }}>
                        New category
                      </Typography>
                    </Stack>
                    <Stack spacing={2}>
                      <TextField
                        fullWidth
                        size="small"
                        label="Category name"
                        value={newCategory}
                        onChange={(e) => setNewCategory(e.target.value)}
                        placeholder="e.g. Billing, Technical"
                        sx={fieldSx}
                        onKeyDown={(e) => e.key === "Enter" && newCategory.trim() && handleAddCategory()}
                      />
                      <Button
                        variant="contained"
                        disableElevation
                        startIcon={<Plus size={18} strokeWidth={2.25} />}
                        onClick={handleAddCategory}
                        disabled={!newCategory.trim()}
                        sx={{
                          alignSelf: "flex-start",
                          textTransform: "none",
                          fontWeight: 600,
                          borderRadius: 2,
                          px: 2.5,
                          bgcolor: "rgb(79 70 229)",
                          boxShadow: "0 2px 10px rgba(79, 70, 229, 0.35)",
                          "&:hover": { bgcolor: "rgb(67 56 202)", boxShadow: "0 4px 14px rgba(79, 70, 229, 0.4)" },
                        }}
                      >
                        Add category
                      </Button>
                    </Stack>
                  </Paper>
                </Grid>

                <Grid item xs={12} md={6}>
                  <Paper elevation={0} sx={{ ...paperCardSx, p: { xs: 2, md: 2.5 }, height: "100%" }}>
                    <Stack direction="row" alignItems="center" spacing={1} sx={{ mb: 2 }}>
                      <Layers size={22} strokeWidth={1.75} className="text-indigo-600" />
                      <Typography variant="subtitle1" sx={{ fontWeight: 700, color: "rgb(15 23 42)" }}>
                        New subcategory
                      </Typography>
                    </Stack>
                    <Stack spacing={2}>
                      <FormControl fullWidth size="small" sx={fieldSx}>
                        <InputLabel id="support-cat-parent">Parent category</InputLabel>
                        <Select
                          labelId="support-cat-parent"
                          value={selectedCategoryId}
                          onChange={(e) => setSelectedCategoryId(e.target.value)}
                          label="Parent category"
                          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>
                      <TextField
                        fullWidth
                        size="small"
                        label="Subcategory name"
                        value={newSubcategory}
                        onChange={(e) => setNewSubcategory(e.target.value)}
                        placeholder="e.g. Payment issue"
                        sx={fieldSx}
                        onKeyDown={(e) =>
                          e.key === "Enter" &&
                          selectedCategoryId &&
                          newSubcategory.trim() &&
                          handleAddSubcategory()
                        }
                      />
                      <Button
                        variant="contained"
                        disableElevation
                        startIcon={<Plus size={18} strokeWidth={2.25} />}
                        onClick={handleAddSubcategory}
                        disabled={!selectedCategoryId || !newSubcategory.trim()}
                        sx={{
                          alignSelf: "flex-start",
                          textTransform: "none",
                          fontWeight: 600,
                          borderRadius: 2,
                          px: 2.5,
                          bgcolor: "rgb(79 70 229)",
                          boxShadow: "0 2px 10px rgba(79, 70, 229, 0.35)",
                          "&:hover": { bgcolor: "rgb(67 56 202)", boxShadow: "0 4px 14px rgba(79, 70, 229, 0.4)" },
                        }}
                      >
                        Add subcategory
                      </Button>
                    </Stack>
                  </Paper>
                </Grid>
              </Grid>

              <Paper elevation={0} sx={{ ...paperCardSx, mb: 3 }}>
                <Box
                  sx={{
                    px: 2,
                    py: 1.5,
                    borderBottom: "1px solid rgba(15, 23, 42, 0.08)",
                    bgcolor: "rgba(248, 250, 252, 0.9)",
                    display: "flex",
                    alignItems: "center",
                    gap: 1,
                  }}
                >
                  <FolderTree size={20} strokeWidth={1.75} className="text-indigo-600" />
                  <Typography variant="subtitle1" sx={{ fontWeight: 700, color: "rgb(15 23 42)" }}>
                    Categories
                  </Typography>
                </Box>
                <TableContainer sx={{ overflowX: "auto" }}>
                  <Table size="small">
                    <TableHead>
                      <TableRow
                        sx={{
                          bgcolor: "rgba(79, 70, 229, 0.06)",
                          "& th": {
                            fontWeight: 700,
                            fontSize: "0.75rem",
                            textTransform: "uppercase",
                            letterSpacing: "0.05em",
                            color: "rgb(15 23 42)",
                            borderBottom: "1px solid rgba(15, 23, 42, 0.08)",
                          },
                        }}
                      >
                        <TableCell>Name</TableCell>
                        <TableCell align="right" width={120}>
                          Actions
                        </TableCell>
                      </TableRow>
                    </TableHead>
                    <TableBody>
                      {loading ? (
                        [1, 2, 3].map((i) => (
                          <TableRow key={i}>
                            <TableCell colSpan={2}>
                              <Skeleton variant="rounded" height={40} sx={{ borderRadius: 1 }} />
                            </TableCell>
                          </TableRow>
                        ))
                      ) : categories.length === 0 ? (
                        <TableRow>
                          <TableCell colSpan={2} sx={{ py: 4, textAlign: "center" }}>
                            <Typography color="text.secondary" fontWeight={500}>
                              No categories yet. Add one above.
                            </Typography>
                          </TableCell>
                        </TableRow>
                      ) : (
                        categories.map((category) => (
                          <TableRow
                            key={category._id}
                            hover
                            sx={{
                              "&:nth-of-type(even)": { bgcolor: "rgba(248, 250, 252, 0.6)" },
                              "& td": { borderColor: "rgba(15, 23, 42, 0.06)" },
                            }}
                          >
                            <TableCell>
                              <Typography fontWeight={600} color="rgb(15 23 42)">
                                {category.name}
                              </Typography>
                            </TableCell>
                            <TableCell align="right">
                              <Button
                                size="small"
                                variant="contained"
                                disableElevation
                                color="error"
                                startIcon={<Trash2 size={14} strokeWidth={2.25} />}
                                onClick={() => handleDeleteCategory(category._id)}
                                sx={{
                                  textTransform: "none",
                                  fontWeight: 600,
                                  borderRadius: 2,
                                  minHeight: 32,
                                  boxShadow: "0 1px 4px rgba(220, 38, 38, 0.25)",
                                }}
                              >
                                Delete
                              </Button>
                            </TableCell>
                          </TableRow>
                        ))
                      )}
                    </TableBody>
                  </Table>
                </TableContainer>
              </Paper>

              <Paper elevation={0} sx={paperCardSx}>
                <Box
                  sx={{
                    px: 2,
                    py: 1.5,
                    borderBottom: "1px solid rgba(15, 23, 42, 0.08)",
                    bgcolor: "rgba(248, 250, 252, 0.9)",
                    display: "flex",
                    alignItems: "center",
                    gap: 1,
                  }}
                >
                  <Layers size={20} strokeWidth={1.75} className="text-indigo-600" />
                  <Typography variant="subtitle1" sx={{ fontWeight: 700, color: "rgb(15 23 42)" }}>
                    Subcategories
                  </Typography>
                </Box>
                <TableContainer sx={{ overflowX: "auto" }}>
                  <Table size="small">
                    <TableHead>
                      <TableRow
                        sx={{
                          bgcolor: "rgba(79, 70, 229, 0.06)",
                          "& th": {
                            fontWeight: 700,
                            fontSize: "0.75rem",
                            textTransform: "uppercase",
                            letterSpacing: "0.05em",
                            color: "rgb(15 23 42)",
                            borderBottom: "1px solid rgba(15, 23, 42, 0.08)",
                          },
                        }}
                      >
                        <TableCell>Name</TableCell>
                        <TableCell>Parent category</TableCell>
                        <TableCell align="right" width={120}>
                          Actions
                        </TableCell>
                      </TableRow>
                    </TableHead>
                    <TableBody>
                      {loading ? (
                        [1, 2, 3].map((i) => (
                          <TableRow key={i}>
                            <TableCell colSpan={3}>
                              <Skeleton variant="rounded" height={40} sx={{ borderRadius: 1 }} />
                            </TableCell>
                          </TableRow>
                        ))
                      ) : subcategories.length === 0 ? (
                        <TableRow>
                          <TableCell colSpan={3} sx={{ py: 4, textAlign: "center" }}>
                            <Typography color="text.secondary" fontWeight={500}>
                              No subcategories yet.
                            </Typography>
                          </TableCell>
                        </TableRow>
                      ) : (
                        subcategories.map((subcategory) => (
                          <TableRow
                            key={subcategory._id}
                            hover
                            sx={{
                              "&:nth-of-type(even)": { bgcolor: "rgba(248, 250, 252, 0.6)" },
                              "& td": { borderColor: "rgba(15, 23, 42, 0.06)" },
                            }}
                          >
                            <TableCell>
                              <Typography fontWeight={600} color="rgb(15 23 42)">
                                {subcategory.name}
                              </Typography>
                            </TableCell>
                            <TableCell>
                              <Chip
                                size="small"
                                label={resolveCategoryName(subcategory)}
                                sx={{
                                  fontWeight: 600,
                                  bgcolor: "rgba(79, 70, 229, 0.08)",
                                  color: "rgb(79 70 229)",
                                  border: "none",
                                }}
                              />
                            </TableCell>
                            <TableCell align="right">
                              <Button
                                size="small"
                                variant="contained"
                                disableElevation
                                color="error"
                                startIcon={<Trash2 size={14} strokeWidth={2.25} />}
                                onClick={() => handleDeleteSubcategory(subcategory._id)}
                                sx={{
                                  textTransform: "none",
                                  fontWeight: 600,
                                  borderRadius: 2,
                                  minHeight: 32,
                                  boxShadow: "0 1px 4px rgba(220, 38, 38, 0.25)",
                                }}
                              >
                                Delete
                              </Button>
                            </TableCell>
                          </TableRow>
                        ))
                      )}
                    </TableBody>
                  </Table>
                </TableContainer>
              </Paper>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};

export default AdminSupportCategories;
