import React, { useState, useEffect } from "react";
import {
  Box,
  Typography,
  TextField,
  Button,
  Paper,
  Grid,
  Snackbar,
  Alert,
  InputAdornment
} from "@mui/material";
import { useStyles } from "../dashboardStyles";
import { getSignupMasterPricing, setSignupMasterPricing } from "../../../services/dashboard.services";

const PaymentConfig = () => {
  const classes = useStyles();
  
  // Initial payment configuration state
  const [paymentConfig, setPaymentConfig] = useState({
    setup_fees: "0.00",
    subscription_fees: "0.00",
    per_call_charges: "0.00"
  });

  const fetchPaymentConfig = async () => {
    try {
      const response = await getSignupMasterPricing();
      const apiData = response?.data?.data || {};
      setPaymentConfig({
        setup_fees: apiData?.setup_fees,
        subscription_fees: apiData?.subscription_fees,
        per_call_charges: apiData?.per_call_charges
      });
    } catch (error) {
      console.error("Error fetching payment configuration:", error);
    }
  };

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

  // State for tracking if form has been edited
  const [isEdited, setIsEdited] = useState(false);
  
  // State for notification
  const [notification, setNotification] = useState({
    open: false,
    message: "",
    severity: "success"
  });

  // Handle input change
  const handleInputChange = (e) => {
    const { name, value } = e.target;
    
    // Allow empty values, numbers, and decimal points with up to 2 decimal places
    // This regex allows for more flexible input including empty string and partial numbers
    if (value !== "" && !/^\d*(\.\d{0,2})?$/.test(value)) {
      return;
    }
    
    setPaymentConfig({
      ...paymentConfig,
      [name]: value
    });
    
    setIsEdited(true);
  };

  // Handle save configuration
  const handleSaveConfig = async () => {
    try {
      const response = await setSignupMasterPricing(paymentConfig);
      const apiData = response?.data?.data || {};
      setPaymentConfig({
        setup_fees: apiData?.setup_fees,
        subscription_fees: apiData?.subscription_fees,
        per_call_charges: apiData?.per_call_charges
      });
    } catch (error) {
      console.error("Error fetching payment configuration:", error);
    }
    
    setNotification({
      open: true,
      message: "Payment configuration saved successfully",
      severity: "success"
    });
    
    setIsEdited(false);
    
    // In a real implementation, you would save this data to your backend
    console.log("Saving payment configuration:", paymentConfig);
  };

  // Handle notification close
  const handleCloseNotification = () => {
    setNotification({
      ...notification,
      open: false
    });
  };

  return (
    <Paper elevation={3} sx={{ p: 3, mb: 4, borderRadius: 2 }}>
      <Box mb={2}>
        <Typography variant="h6" fontWeight="bold">
          Signup Charges
        </Typography>
        <Typography variant="body2" color="text.secondary">
          Configure payment details for new clinic registrations
        </Typography>
      </Box>
      
      <Grid container spacing={3}>
        <Grid item xs={12} md={4}>
          <TextField
            fullWidth
            label="Setup Fee"
            name="setup_fees"
            value={paymentConfig.setup_fees}
            onChange={handleInputChange}
            InputProps={{
              startAdornment: <InputAdornment position="start">$</InputAdornment>,
            }}
            variant="outlined"
          />
        </Grid>
        
        <Grid item xs={12} md={4}>
          <TextField
            fullWidth
            label="Subscription Fee (Monthly)"
            name="subscription_fees"
            value={paymentConfig.subscription_fees}
            onChange={handleInputChange}
            InputProps={{
              startAdornment: <InputAdornment position="start">$</InputAdornment>,
            }}
            variant="outlined"
          />
        </Grid>
        
        <Grid item xs={12} md={4}>
          <TextField
            fullWidth
            label="Per Minute Charges"
            name="per_call_charges"
            value={paymentConfig.per_call_charges}
            onChange={handleInputChange}
            InputProps={{
              startAdornment: <InputAdornment position="start">$</InputAdornment>,
              endAdornment: <InputAdornment position="end">/min</InputAdornment>,
            }}
            variant="outlined"
          />
        </Grid>
      </Grid>
      
      <Box mt={3} display="flex" justifyContent="flex-end">
        <Button
          variant="contained"
          color="primary"
          onClick={handleSaveConfig}
          disabled={!isEdited}
          sx={{
            borderRadius: 50,
            px: 3,
            textTransform: "none",
            backgroundColor: "#ff3366",
            "&:hover": {
              backgroundColor: "#e61653",
            },
            "&:disabled": {
              backgroundColor: "#ffb3c3",
              color: "#ffffff"
            }
          }}
        >
          Save Configuration
        </Button>
      </Box>
      
      {/* Notification */}
      <Snackbar
        open={notification.open}
        autoHideDuration={6000}
        onClose={handleCloseNotification}
        anchorOrigin={{ vertical: "top", horizontal: "right" }}
      >
        <Alert 
          onClose={handleCloseNotification} 
          severity={notification.severity}
          sx={{ width: "100%" }}
        >
          {notification.message}
        </Alert>
      </Snackbar>
    </Paper>
  );
};

export default PaymentConfig;
