import React, { useEffect, useState } from "react";
import {
  Box,
  Button,
  FormControl,
  InputLabel,
  MenuItem,
  Select,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  TextField,
  Typography,
  Snackbar,
  Alert,
  Paper,
  useTheme,
  useMediaQuery,
  Grid,
} from "@mui/material";
import axios from "axios";

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

interface IDataPlan {
  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;
  description: string;
}

const networks = ["MTN", "Airtel", "9mobile", "Glo"];
const planTypes = [
  "SME",
  "Gifting",
  "SME2",
  "Data Share",
  "Corporate Gifting",
  "Data Coupons",
  "Awoof Data",
  "ThryveData",
];
const planSizes = [500, 1000, 2000, 3000, 5000, 10000]; // in MB

interface DataPageProps {
  isAddPlan: boolean;
  selectedPlan?: Partial<IDataPlan>;
  apiDetails?: IApiDetail[];
  handleCloseModal: () => void;
  fetchPlans: () => void;
}

const DataPage: React.FC<DataPageProps> = ({
  isAddPlan,
  selectedPlan,
  apiDetails,
  handleCloseModal,
  fetchPlans,
}) => {
  const theme = useTheme();
  const isMobile = useMediaQuery(theme.breakpoints.down("sm"));
  const [currentNetwork, setCurrentNetwork] = useState(networks[0]);
  const [vendingMethod, setVendingMethod] = useState("API");
  const [selectedPlanType, setSelectedPlanType] = useState(planTypes[0]);
  const [snackbar, setSnackbar] = useState({
    open: false,
    message: "",
    severity: "success" as "success" | "error" | "warning" | "info",
  });

  const [formData, setFormData] = useState<IDataPlan>({
    network: "",
    planSize: 0,
    planType: "",
    planAmount: 0,
    affiliatePrice: 0,
    topUserPrice: 0,
    planVolume: "GB",
    smsCommand: "",
    smartEarnerPrice: 0,
    apiPrice: 0,
    apiDetails: [],
    planDuration: "30 days",
    available: true,
    vendingMethod: "API",
    description: "",
  });

  useEffect(() => {
    if (!isAddPlan && selectedPlan) {
      // Populate fields when editing a plan
      setFormData({
        network: selectedPlan.network || "",
        planSize: selectedPlan.planSize || 0,
        planType: selectedPlan.planType || "",
        planAmount: selectedPlan.planAmount || 0,
        affiliatePrice: selectedPlan.affiliatePrice || 0,
        topUserPrice: selectedPlan.topUserPrice || 0,
        planVolume: "GB",
        smsCommand: "",
        smartEarnerPrice: selectedPlan.smartEarnerPrice || 0,
        apiPrice: selectedPlan.apiPrice || 0,
        apiDetails: apiDetails || [],
        planDuration: "30 days",
        available: true,
        vendingMethod: selectedPlan.vendingMethod || "API",
        description: selectedPlan.description || "",
      });

      setCurrentNetwork(selectedPlan.network || "");
      setVendingMethod(selectedPlan.vendingMethod || "API");
      setSelectedPlanType(selectedPlan.planType || "");
    }
  }, [isAddPlan, selectedPlan, apiDetails]);

  const handleInputChange = (
    field: string,
    value: string | number | { apiName: string; apiIds: any[] }[]
  ) => {
    setFormData((prev) => ({ ...prev, [field]: value }));
  };

  const handleAddApiDetail = () => {
    const updatedApiDetails = [
      ...formData.apiDetails,
      { apiName: "", apiIds: Array(planSizes.length).fill("") },
    ];
    handleInputChange("apiDetails", updatedApiDetails);
  };

  const handleDeleteApiDetail = (index: number) => {
    const updatedApiDetails = formData.apiDetails.filter((_, i) => i !== index);
    handleInputChange("apiDetails", updatedApiDetails);
  };

  const handleSave = async () => {
    const {
      smartEarnerPrice,
      affiliatePrice,
      topUserPrice,
      apiPrice,
      description,
    } = formData;

    const calculatedPlans: IDataPlan[] = planSizes.map((size, sizeIndex) => ({
      network: currentNetwork,
      planSize: size / 1000,
      planType: selectedPlanType,
      vendingMethod,
      planAmount: apiPrice * (size / 1000),
      affiliatePrice: affiliatePrice * (size / 1000),
      topUserPrice: topUserPrice * (size / 1000),
      planVolume: "GB",
      smsCommand: "",
      smartEarnerPrice: smartEarnerPrice * (size / 1000),
      apiPrice: apiPrice * (size / 1000),
      apiDetails: formData.apiDetails
        .map((detail) => ({
          apiName: detail.apiName,
          apiId: detail.apiIds[sizeIndex],
          apiIds: detail.apiIds,
        }))
        .filter((detail) => detail.apiId),
      planDuration: "30 days",
      available: true,
      description: description,
    }));

    try {
      if (isAddPlan) {
        const response = await axios.post("/api/adminapi/data", {
          plans: calculatedPlans,
        });
        handleCloseModal();
        fetchPlans();
        if (response.status === 201) {
          setSnackbar({
            open: true,
            message: "Plan Added Successfully",
            severity: "success",
          });
        }
      } else {
        await axios.delete(
          `/api/adminapi/data?network=${formData.network}&planType=${formData.planType}`
        );
        const response = await axios.post("/api/adminapi/data", {
          plans: calculatedPlans,
        });
        if (response.status === 200) {
          setSnackbar({
            open: true,
            message: "Plans Updated Successfully",
            severity: "success",
          });
        }
      }
      handleCloseModal();
      fetchPlans();
    } catch (error) {
      console.error("Error saving plan:", error);
      setSnackbar({
        open: true,
        message: "Error saving plan.",
        severity: "error",
      });
    }
  };

  return (
    <Box sx={{ p: isMobile ? 2 : 3 }}>
      <Snackbar
        open={snackbar.open}
        autoHideDuration={6000}
        onClose={() => setSnackbar({ ...snackbar, open: false })}
        anchorOrigin={{ vertical: "top", horizontal: "center" }}
      >
        <Alert
          onClose={() => setSnackbar({ ...snackbar, open: false })}
          severity={snackbar.severity}
          sx={{ width: "100%" }}
        >
          {snackbar.message}
        </Alert>
      </Snackbar>

      <Typography variant="h5" gutterBottom sx={{ mb: 3 }}>
        {isAddPlan ? "Create New Data Plan" : "Edit Data Plan"}
      </Typography>

      <Paper sx={{ p: 3, mb: 3 }} elevation={1}>
        <Typography variant="h6" gutterBottom sx={{ mb: 2 }}>
          Basic Information
        </Typography>

        <Grid container spacing={2}>
          <Grid size={{ xs: 12, sm: 6, md: 4 }}>
            <FormControl fullWidth>
              <InputLabel>Vending Method</InputLabel>
              <Select
                value={vendingMethod}
                onChange={(e) => setVendingMethod(e.target.value)}
                label="Vending Method"
              >
                <MenuItem value="API">API</MenuItem>
                <MenuItem value="SIMhosting">SIM Hosting</MenuItem>
              </Select>
            </FormControl>
          </Grid>

          <Grid size={{ xs: 12, sm: 6, md: 4 }}>
            <FormControl fullWidth>
              <InputLabel>Network</InputLabel>
              <Select
                value={currentNetwork}
                onChange={(e) => setCurrentNetwork(e.target.value)}
                label="Network"
              >
                {networks.map((network) => (
                  <MenuItem key={network} value={network}>
                    {network}
                  </MenuItem>
                ))}
              </Select>
            </FormControl>
          </Grid>

          <Grid size={{ xs: 12, sm: 6, md: 4 }}>
            <FormControl fullWidth>
              <InputLabel>Plan Type</InputLabel>
              <Select
                value={selectedPlanType}
                onChange={(e) => setSelectedPlanType(e.target.value)}
                label="Plan Type"
              >
                {planTypes.map((type) => (
                  <MenuItem key={type} value={type}>
                    {type}
                  </MenuItem>
                ))}
              </Select>
            </FormControl>
          </Grid>

          <Grid size={{ xs: 12, sm: 6, md: 4 }}>
            <TextField
              fullWidth
              label="Smart Earner Price (per GB)"
              type="number"
              value={formData.smartEarnerPrice}
              onChange={(e) =>
                handleInputChange("smartEarnerPrice", Number(e.target.value))
              }
            />
          </Grid>

          <Grid size={{ xs: 12, sm: 6, md: 4 }}>
            <TextField
              fullWidth
              label="Affiliate Price (per GB)"
              type="number"
              value={formData.affiliatePrice}
              onChange={(e) =>
                handleInputChange("affiliatePrice", Number(e.target.value))
              }
            />
          </Grid>

          <Grid size={{ xs: 12, sm: 6, md: 4 }}>
            <TextField
              fullWidth
              label="Top User Price (per GB)"
              type="number"
              value={formData.topUserPrice}
              onChange={(e) =>
                handleInputChange("topUserPrice", Number(e.target.value))
              }
            />
          </Grid>

          <Grid size={{ xs: 12 }}>
            <TextField
              fullWidth
              label="Plan Description"
              multiline
              rows={3}
              value={formData.description}
              onChange={(e) => handleInputChange("description", e.target.value)}
              placeholder="Enter a description for this plan..."
            />
          </Grid>
        </Grid>
      </Paper>

      {/* API Details */}
      {vendingMethod === "API" && (
        <Paper sx={{ p: 3, mb: 3 }} elevation={1}>
          <Box
            sx={{
              display: "flex",
              justifyContent: "space-between",
              alignItems: "center",
              mb: 2,
            }}
          >
            <Typography variant="h6">API Configuration</Typography>
            <Button
              variant="contained"
              color="primary"
              onClick={handleAddApiDetail}
              size="small"
            >
              Add API
            </Button>
          </Box>

          <TableContainer>
            <Table size={isMobile ? "small" : "medium"}>
              <TableHead>
                <TableRow>
                  <TableCell>API Name</TableCell>
                  {planSizes.map((size) => (
                    <TableCell key={size} align="center">
                      {size}MB
                    </TableCell>
                  ))}
                  <TableCell>Action</TableCell>
                </TableRow>
              </TableHead>
              <TableBody>
                {formData.apiDetails.map((apiDetail, index) => (
                  <TableRow key={index}>
                    <TableCell>
                      <TextField
                        fullWidth
                        size="small"
                        value={apiDetail.apiName}
                        onChange={(e) => {
                          const updatedApiDetails = [...formData.apiDetails];
                          updatedApiDetails[index].apiName = e.target.value;
                          handleInputChange("apiDetails", updatedApiDetails);
                        }}
                      />
                    </TableCell>
                    {planSizes.map((_, sizeIndex) => (
                      <TableCell key={sizeIndex}>
                        <TextField
                          fullWidth
                          size="small"
                          value={apiDetail.apiIds[sizeIndex] || ""}
                          onChange={(e) => {
                            const updatedApiDetails = [...formData.apiDetails];
                            updatedApiDetails[index].apiIds[sizeIndex] =
                              e.target.value;
                            handleInputChange("apiDetails", updatedApiDetails);
                          }}
                        />
                      </TableCell>
                    ))}
                    <TableCell>
                      <Button
                        color="error"
                        size="small"
                        onClick={() => handleDeleteApiDetail(index)}
                      >
                        Remove
                      </Button>
                    </TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          </TableContainer>
        </Paper>
      )}

      <Box sx={{ display: "flex", justifyContent: "flex-end", gap: 2 }}>
        <Button variant="outlined" onClick={handleCloseModal}>
          Cancel
        </Button>
        <Button variant="contained" color="primary" onClick={handleSave}>
          {isAddPlan ? "Create Plan" : "Update Plan"}
        </Button>
      </Box>
    </Box>
  );
};

export default DataPage;
