import React, { useState, useEffect } from "react";
import {
  Box,
  Button,
  Typography,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  Modal,
  Snackbar,
  Alert,
  Paper,
  useMediaQuery,
  useTheme,
  IconButton,
  Tooltip,
} from "@mui/material";
import axios from "axios";
import DataPage from "./datapage";
import IndividualDataPlan from "./datapageindividual";
import LoadingComponent from "./loadingcomponent";
import EditIcon from "@mui/icons-material/Edit";
import DeleteIcon from "@mui/icons-material/Delete";
import AddIcon from "@mui/icons-material/Add";

interface IApiDetail {
  apiName: string;
  apiIds: string[];
}

const Data = () => {
  interface IDataPlan {
    _id: string;
    network: string;
    planSize: number;
    planType: string;
    planAmount: number;
    affiliatePrice: number;
    topUserPrice: number;
    planVolume: string;
    smsCommand: string;
    smartEarnerPrice: number;
    apiPrice: number;
    apiDetails: IApiDetail[];
    planDuration: string;
    available: boolean;
    vendingMethod: string;
  }

  const [savedPlans, setSavedPlans] = useState<IDataPlan[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [isIndividualPlanModalOpen, setIsIndividualPlanModalOpen] =
    useState(false);
  const [selectedPlan, setSelectedPlan] = useState<IDataPlan | null>(null);
  const [isAddPlan, setIsAddPlan] = useState(false);
  const [apiDetails, setApiDetails] = useState<IApiDetail[]>([]);

  const [snackbar, setSnackbar] = useState({
    open: false,
    message: "",
    severity: "success" as "success" | "error" | "warning" | "info",
  });

  const theme = useTheme();
  const isMobile = useMediaQuery(theme.breakpoints.down("sm"));

  const fetchPlans = async () => {
    try {
      const response = await axios.get("/api/adminapi/data");
      setSavedPlans(response.data);
    } catch (err) {
      setError("Failed to fetch plans");
      setSnackbar({
        open: true,
        message: "Failed to fetch plans",
        severity: "error",
      });
    } finally {
      setLoading(false);
    }
  };

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

  const handleCloseModal = () => {
    setIsModalOpen(false);
    fetchPlans();
  };

  const handleCloseIndividualPlanModal = () => {
    setIsIndividualPlanModalOpen(false);
    fetchPlans();
  };

  const handleEdit = async (_id: string) => {
    try {
      const response = await axios.get(`/api/adminapi/data?id=${_id}`);
      setSelectedPlan(response.data);

      const apiDetailsResponse = await axios.get(
        `/api/adminapi/data?network=${response.data?.network}&planType=${response.data?.planType}`
      );
      setApiDetails(apiDetailsResponse.data);
      setIsAddPlan(false);
      setIsModalOpen(true);
    } catch (error) {
      console.error("Error fetching plan:", error);
      setSnackbar({
        open: true,
        message: "Failed to Fetch Plan",
        severity: "error",
      });
    }
  };

  const handleDeletePlan = async (_id: string) => {
    try {
      await axios.delete(`/api/adminapi/data?id=${_id}`);
      setSavedPlans((prev) => prev.filter((plan) => plan._id !== _id));
      setSnackbar({
        open: true,
        message: "Deleted Successfully",
        severity: "success",
      });
      fetchPlans();
    } catch (err) {
      console.error("Error deleting plan:", err);
      setSnackbar({
        open: true,
        message: "Failed to delete plan",
        severity: "error",
      });
    }
  };

  const handleAddPlan = () => {
    setSelectedPlan(null);
    setIsAddPlan(true);
    setIsModalOpen(true);
  };

  const handleAddIndividualPlan = () => {
    setSelectedPlan(null);
    setIsIndividualPlanModalOpen(true);
  };

  const closeModal = () => {
    setIsModalOpen(false);
    setSelectedPlan(null);
    setIsAddPlan(false);
    fetchPlans();
  };

  const handleSnackbarClose = (
    event?: React.SyntheticEvent | Event,
    reason?: string
  ) => {
    if (reason === "clickaway") return;
    setSnackbar({ ...snackbar, open: false });
  };

  return (
    <Paper sx={{ p: 3, borderRadius: 2 }}>
      <Snackbar
        open={snackbar.open}
        autoHideDuration={4000}
        onClose={handleSnackbarClose}
        anchorOrigin={{ vertical: "bottom", horizontal: "center" }}
      >
        <Alert
          onClose={handleSnackbarClose}
          severity={snackbar.severity}
          variant="filled"
        >
          {snackbar.message}
        </Alert>
      </Snackbar>

      <Box
        sx={{
          display: "flex",
          justifyContent: "space-between",
          alignItems: "center",
          mb: 3,
        }}
      >
        <Typography variant="h5" component="h2" fontWeight="bold">
          Data Plans
        </Typography>
        <Box sx={{ display: "flex", gap: 1 }}>
          <Tooltip title="Add Bulk Plan">
            <Button
              variant="contained"
              color="primary"
              onClick={handleAddPlan}
              startIcon={<AddIcon />}
              size={isMobile ? "small" : "medium"}
            >
              {isMobile ? "Bulk" : "Add Bulk Plan"}
            </Button>
          </Tooltip>
          <Tooltip title="Add Individual Plan">
            <Button
              variant="outlined"
              color="primary"
              onClick={handleAddIndividualPlan}
              startIcon={<AddIcon />}
              size={isMobile ? "small" : "medium"}
            >
              {isMobile ? "Single" : "Add Single Plan"}
            </Button>
          </Tooltip>
        </Box>
      </Box>

      {loading ? (
        <LoadingComponent />
      ) : error ? (
        <Typography color="error">{error}</Typography>
      ) : (
        <>
          <Typography variant="subtitle1" gutterBottom sx={{ mb: 2 }}>
            Saved Plans
          </Typography>
          <TableContainer
            component={Paper}
            sx={{ maxHeight: "70vh", overflow: "auto" }}
          >
            <Table stickyHeader size={isMobile ? "small" : "medium"}>
              <TableHead>
                <TableRow>
                  <TableCell>Network</TableCell>
                  <TableCell>Size</TableCell>
                  <TableCell>Type</TableCell>
                  <TableCell>Method</TableCell>
                  <TableCell>Price</TableCell>
                  <TableCell align="center">Actions</TableCell>
                </TableRow>
              </TableHead>
              <TableBody>
                {savedPlans.map((plan) => (
                  <TableRow key={plan._id} hover>
                    <TableCell>{plan.network}</TableCell>
                    <TableCell>{plan.planSize}</TableCell>
                    <TableCell>{plan.planType}</TableCell>
                    <TableCell>{plan.vendingMethod}</TableCell>
                    <TableCell>
                      ₦{plan.smartEarnerPrice?.toLocaleString()}
                    </TableCell>
                    <TableCell align="center">
                      {plan.planSize === 1 && (
                        <Tooltip title="Edit">
                          <IconButton
                            color="primary"
                            onClick={() => handleEdit(plan._id)}
                            size="small"
                          >
                            <EditIcon fontSize="small" />
                          </IconButton>
                        </Tooltip>
                      )}
                      <Tooltip title="Delete">
                        <IconButton
                          color="error"
                          onClick={() => handleDeletePlan(plan._id)}
                          size="small"
                        >
                          <DeleteIcon fontSize="small" />
                        </IconButton>
                      </Tooltip>
                    </TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          </TableContainer>
        </>
      )}

      {/* Modal for adding/editing bulk plans */}
      <Modal
        open={isModalOpen}
        onClose={closeModal}
        aria-labelledby="modal-title"
        aria-describedby="modal-description"
      >
        <Box
          sx={{
            position: "absolute",
            top: "50%",
            left: "50%",
            transform: "translate(-50%, -50%)",
            width: isMobile ? "90%" : 600,
            bgcolor: "background.paper",
            boxShadow: 24,
            p: 3,
            borderRadius: 2,
            maxHeight: "90vh",
            overflowY: "auto",
          }}
        >
          <DataPage
            selectedPlan={selectedPlan ?? undefined}
            isAddPlan={isAddPlan}
            handleCloseModal={handleCloseModal}
            fetchPlans={fetchPlans}
            apiDetails={apiDetails}
          />
        </Box>
      </Modal>

      {/* Modal for adding individual plans */}
      <Modal
        open={isIndividualPlanModalOpen}
        onClose={handleCloseIndividualPlanModal}
        aria-labelledby="individual-plan-modal-title"
        aria-describedby="individual-plan-modal-description"
      >
        <Box
          sx={{
            position: "absolute",
            top: "50%",
            left: "50%",
            transform: "translate(-50%, -50%)",
            width: isMobile ? "90%" : 600,
            bgcolor: "background.paper",
            boxShadow: 24,
            p: 3,
            borderRadius: 2,
            maxHeight: "90vh",
            overflowY: "auto",
          }}
        >
          <IndividualDataPlan
            isAddPlan={true}
            handleCloseModal={handleCloseIndividualPlanModal}
            fetchPlans={fetchPlans}
          />
        </Box>
      </Modal>
    </Paper>
  );
};

export default Data;
