import React, { useEffect, useState } from "react";
import {
  Box,
  Button,
  FormControl,
  InputLabel,
  MenuItem,
  Select,
  TextField,
  Typography,
  Snackbar,
  Alert,
} from "@mui/material";
import axios from "axios";

interface IApiDetail {
  apiName: string;
  apiId: string;
}

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;
  description?: string; // Added description field
}

const networks = ["MTN", "Airtel", "9mobile", "Glo"];
const planTypes = [
  "SME",
  "Gifting",
  "SME2",
  "Data Share",
  "Corporate Gifting",
  "Data Coupons",
  "Awoof Data",
  "ThryveData",
];

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

const IndividualDataPlan: React.FC<DataPageProps> = ({
  isAddPlan,
  selectedPlan,
  handleCloseModal,
  fetchPlans,
}) => {
  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: "", // Initialize description field
  });

  useEffect(() => {
    if (!isAddPlan && selectedPlan) {
      // Populate fields when editing a plan
      setFormData({
        id: selectedPlan.id,
        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: selectedPlan.apiDetails || [],
        planDuration: selectedPlan.planDuration || "30 days",
        available: selectedPlan.available !== false,
        vendingMethod: selectedPlan.vendingMethod || "API",
        description: selectedPlan.description || "", // Set description from selected plan
      });

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

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

  const handleSave = async () => {
    const planSizeInGB = formData.planSize / 1000;
    const planToSubmit = {
      ...formData,
      planSize: planSizeInGB,
      network: currentNetwork,
      planType: selectedPlanType,
      vendingMethod,
    };

    try {
      if (isAddPlan) {
        const response = await axios.post("/api/adminapi/data", {
          individualPlan: planToSubmit,
        });
        handleCloseModal();
        fetchPlans();
        if (response.status === 201) {
          setSnackbar({
            open: true,
            message: "Plan Added Successfully",
            severity: "success",
          });
        }
      } else {
        await axios.put(`/api/adminapi/data/${selectedPlan?.id}`, {
          individualPlan: planToSubmit,
        });
        setSnackbar({
          open: true,
          message: "Plan 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={{ padding: 2 }}>
      <Snackbar
        open={snackbar.open}
        autoHideDuration={6000}
        onClose={() => setSnackbar({ ...snackbar, open: false })}
      >
        <Alert
          onClose={() => setSnackbar({ ...snackbar, open: false })}
          severity={snackbar.severity}
        >
          {snackbar.message}
        </Alert>
      </Snackbar>
      <Typography variant="h4" gutterBottom>
        {isAddPlan ? "Create New Plan" : "Edit Plan"}
      </Typography>

      {/* Form fields */}
      <Box sx={{ display: "flex", flexWrap: "wrap", gap: 2, marginBottom: 2 }}>
        <FormControl sx={{ flex: "1 1 200px" }}>
          <InputLabel>Vending Method</InputLabel>
          <Select
            value={vendingMethod}
            onChange={(e) => setVendingMethod(e.target.value)}
          >
            <MenuItem value="API">API</MenuItem>
            <MenuItem value="SIMhosting">SIM Hosting</MenuItem>
          </Select>
        </FormControl>

        <FormControl sx={{ flex: "1 1 200px" }}>
          <InputLabel>Network</InputLabel>
          <Select
            value={currentNetwork}
            onChange={(e) => setCurrentNetwork(e.target.value)}
          >
            {networks.map((network) => (
              <MenuItem key={network} value={network}>
                {network}
              </MenuItem>
            ))}
          </Select>
        </FormControl>

        <FormControl sx={{ flex: "1 1 200px" }}>
          <InputLabel>Plan Type</InputLabel>
          <Select
            value={selectedPlanType}
            onChange={(e) => setSelectedPlanType(e.target.value)}
          >
            {planTypes.map((type) => (
              <MenuItem key={type} value={type}>
                {type}
              </MenuItem>
            ))}
          </Select>
        </FormControl>

        <TextField
          label="Plan Size (MB)"
          type="number"
          value={formData.planSize}
          onChange={(e) =>
            handleInputChange("planSize", Number(e.target.value))
          }
          sx={{ flex: "1 1 200px" }}
        />

        <TextField
          label="Smart Earner Price"
          type="number"
          value={formData.smartEarnerPrice}
          onChange={(e) =>
            handleInputChange("smartEarnerPrice", Number(e.target.value))
          }
          sx={{ flex: "1 1 200px" }}
        />

        <TextField
          label="Affiliate Price"
          type="number"
          value={formData.affiliatePrice}
          onChange={(e) =>
            handleInputChange("affiliatePrice", Number(e.target.value))
          }
          sx={{ flex: "1 1 200px" }}
        />

        <TextField
          label="Top User Price"
          type="number"
          value={formData.topUserPrice}
          onChange={(e) =>
            handleInputChange("topUserPrice", Number(e.target.value))
          }
          sx={{ flex: "1 1 200px" }}
        />

        <TextField
          label="API Name"
          value={formData.apiDetails[0]?.apiName || ""}
          onChange={(e) => {
            const updatedApiDetails = [...formData.apiDetails];
            if (updatedApiDetails.length === 0) {
              updatedApiDetails.push({ apiName: e.target.value, apiId: "" });
            } else {
              updatedApiDetails[0].apiName = e.target.value;
            }
            handleInputChange("apiDetails", updatedApiDetails);
          }}
          sx={{ flex: "1 1 200px" }}
        />

        <TextField
          label="API Plan ID"
          value={formData.apiDetails[0]?.apiId || ""}
          onChange={(e) => {
            const updatedApiDetails = [...formData.apiDetails];
            if (updatedApiDetails.length === 0) {
              updatedApiDetails.push({ apiName: "", apiId: e.target.value });
            } else {
              updatedApiDetails[0].apiId = e.target.value;
            }
            handleInputChange("apiDetails", updatedApiDetails);
          }}
          sx={{ flex: "1 1 200px" }}
        />

        {/* New Description Field */}
        <TextField
          label="Description"
          value={formData.description || ""}
          onChange={(e) => handleInputChange("description", e.target.value)}
          multiline
          rows={3}
          sx={{ flex: "1 1 100%" }}
          placeholder="Enter plan description or special notes"
        />
      </Box>

      {/* Save Button */}
      <Box sx={{ marginTop: 2, textAlign: "right" }}>
        <Button variant="contained" color="primary" onClick={handleSave}>
          {isAddPlan ? "Save New Plan" : "Update Plan"}
        </Button>
      </Box>
    </Box>
  );
};

export default IndividualDataPlan;
